Example #1
0
        /// <summary>
        /// Loads the information from the dto into the data object. Except...
        /// Does NOT load dto.Id.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dto"></param>
        public static void LoadDataFromDto(ref TranslationData data,
                                           TranslationDto dto,
                                           LearnLanguagesContext context)
        {
            //COPY USER INFO
            data.UserDataId = dto.UserId;
            data.UserData   = EfHelper.GetUserData(dto.UserId, context);

            var currentPhraseIds = (from phrase in data.PhraseDatas
                                    select phrase.Id);

            //COPY PHRASEID INFO
            //ADD NEW PHRASEDATAS IN THE DTO
            foreach (var id in dto.PhraseIds)
            {
                if (!currentPhraseIds.Contains(id))
                {
                    PhraseData phraseData = EfHelper.GetPhraseData(id, context);
                    data.PhraseDatas.Add(phraseData);
                }
            }

            //REMOVE PHRASEDATAS THAT ARE NOT IN DTO ANYMORE
            foreach (var phraseId in currentPhraseIds)
            {
                if (!dto.PhraseIds.Contains(phraseId))
                {
                    var dataToRemove = (from phraseData in data.PhraseDatas
                                        where phraseData.Id == phraseId
                                        select phraseData).First();
                    data.PhraseDatas.Remove(dataToRemove);
                }
            }
        }
Example #2
0
        public ActionResult Wording(string key)
        {
            var model = new TranslationDto()
            {
                IsRemovable  = true,
                Translations = new System.Collections.Generic.Dictionary <LanguageEnum, string>
                {
                    { LanguageEnum.Russian, "" },
                    { LanguageEnum.Ukrainian, "" }
                }
            };

            if (string.IsNullOrEmpty(key))
            {
                ViewBag.AddNew = true;
                return(View(model));
            }

            var translation = LanguageHelper.GetBaseTranslationDtoByKey(key);

            if (translation != null)
            {
                return(View(translation));
            }

            return(Redirect("Error"));
        }
        protected override TranslationDto InsertImpl(TranslationDto dto)
        {
            var results = from item in SeedData.Ton.Translations
                          where item.Id == dto.Id
                          select item;

            if (results.Count() == 0)
            {
                CheckValidity(dto);
                dto.Id = Guid.NewGuid();
                SeedData.Ton.Translations.Add(dto);
                return(dto);
            }
            else
            {
                if (results.Count() == 1) //ID ALREADY EXISTS
                {
                    throw new Exceptions.IdAlreadyExistsException(dto.Id);
                }
                else              //MULTIPLE IDS ALREADY EXIST??
                {
                    throw new Exceptions.VeryBadException();
                }
            }
        }
        protected override TranslationDto UpdateImpl(TranslationDto dto)
        {
            var results = from item in SeedData.Ton.Translations
                          where item.Id == dto.Id
                          select item;

            if (results.Count() == 1)
            {
                CheckValidity(dto);
                CheckReferentialIntegrity(dto);
                var TranslationToUpdate = results.First();
                SeedData.Ton.Translations.Remove(TranslationToUpdate);
                dto.Id = Guid.NewGuid();
                SeedData.Ton.Translations.Add(dto);
                return(dto);
            }
            else
            {
                if (results.Count() == 0)
                {
                    throw new Exceptions.IdNotFoundException(dto.Id);
                }
                else
                {
                    throw new Exceptions.VeryBadException();
                }
            }
        }
        public void Add(TranslationDto incomingXltn)
        {
            var xltn = _mapper.Map <Translation>(incomingXltn);

            _ = _trnsCtx.Translations.Add(xltn);
            _ = _trnsCtx.SaveChanges();
        }
        // PUT api/Translation/5
        public async Task <IHttpActionResult> PutTranslation(int id, TranslationDto translationDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var entity = translationDto.ToEntity();

            if (entity == null)
            {
                return(BadRequest());
            }
            entity.Id = id;

            db.Entry(entity).State = EntityState.Modified;

            try {
                await db.SaveChangesAsync();
            } catch (DbUpdateConcurrencyException) {
                if (!TranslationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Example #7
0
        public async Task <ActionResult> InsertAsync([FromBody] TranslationDto translation)
        {
            _service.Token = await getAccessToken();

            var inserted = await _service.InsertAsync(_mapper.Map <Translation>(translation));

            return(CreatedAtAction("GetTranslationById", new { id = inserted.Id }, inserted));
        }
Example #8
0
        public async Task <ActionResult> UpdateAsync([FromBody] TranslationDto translation)
        {
            _service.Token = await getAccessToken();

            await _service.UpdateAsync(_mapper.Map <Translation>(translation));

            return(Ok());
        }
        public async Task AddAsync(TranslationDto incomingXltn)
        {
            var xltn = _mapper.Map <Translation>(incomingXltn);

            _ = await _trnsCtx.Translations.AddAsync(xltn);

            _ = await _trnsCtx.SaveChangesAsync();
        }
Example #10
0
        public async Task <IActionResult> PostTranslation(string app, [FromBody] TranslateDto request)
        {
            var result = await translator.TranslateAsync(request.Text, request.TargetLanguage, request.SourceLanguage, HttpContext.RequestAborted);

            var response = TranslationDto.FromDomain(result);

            return(Ok(response));
        }
        public IActionResult VerifyTranslation([FromBody] VerifyTranslationInput value, string languageId, string translationKey)
        {
            var upsertObject = new TranslationDto();

            upsertObject.Key         = translationKey;
            upsertObject.SpanishWord = value.value;
            upsertObject.IsVerified  = true;
            translationRepository.Upsert(upsertObject);
            return(Ok(JsonSerializer.Serialize(new { value = value.value, languageId = languageId, translationKey = translationKey })));
        }
 protected override TranslationDto InsertImpl(TranslationDto dto)
 {
     using (var ctx = LearnLanguagesContextManager.Instance.GetManager())
     {
         var newTranslationData = EfHelper.AddToContext(dto, ctx.ObjectContext);
         ctx.ObjectContext.SaveChanges();
         dto.Id = newTranslationData.Id;
         return(dto);
     }
 }
        public async Task <TranslationDto> UpsertAsync(TranslationDto incomingXltn)
        {
            var xltn = _mapper.Map <Translation>(incomingXltn);

            _trnsCtx.Translations.Upsert(xltn);
            _ = await _trnsCtx.SaveChangesAsync();

            var result2 = await _trnsCtx.FindAsync <Translation>(incomingXltn.Key);

            return(_mapper.Map <TranslationDto>(result2));
        }
Example #14
0
        public IActionResult PutTranslation([FromRoute] int id, [FromBody] TranslationDto translation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            TranslationService.Update(translation);

            return(NoContent());
        }
        //public Result<TranslationDto> New(object criteria)
        //{
        //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
        //  try
        //  {
        //    var dto = new TranslationDto()
        //    {
        //      Id = Guid.NewGuid(),
        //      LanguageId = SeedData.Ton.DefaultLanguageId
        //    };
        //    retResult = Result<TranslationDto>.Success(dto);
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}
        //public Result<TranslationDto> Fetch(Guid id)
        //{
        //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
        //  try
        //  {
        //    var results = from item in SeedData.Ton.Translations
        //                  where item.Id == id
        //                  select item;

        //    if (results.Count() == 1)
        //      retResult = Result<TranslationDto>.Success(results.First());
        //    else
        //    {
        //      if (results.Count() == 0)
        //        retResult = Result<TranslationDto>.FailureWithInfo(null,
        //          new Exceptions.FetchFailedException(DalResources.ErrorMsgIdNotFoundException));
        //      else
        //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
        //    }
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}
        //public Result<TranslationDto> Update(TranslationDto dto)
        //{
        //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
        //  try
        //  {
        //    var results = from item in SeedData.Ton.Translations
        //                  where item.Id == dto.Id
        //                  select item;

        //    if (results.Count() == 1)
        //    {
        //      var TranslationToUpdate = results.First();
        //      SeedData.Ton.Translations.Remove(TranslationToUpdate);
        //      dto.Id = Guid.NewGuid();
        //      SeedData.Ton.Translations.Add(dto);
        //      retResult = Result<TranslationDto>.Success(dto);
        //    }
        //    else
        //    {
        //      if (results.Count() == 0)
        //        retResult = Result<TranslationDto>.FailureWithInfo(null,
        //          new Exceptions.UpdateFailedException(DalResources.ErrorMsgIdNotFoundException));
        //      else
        //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
        //    }
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}
        //public Result<TranslationDto> Insert(TranslationDto dto)
        //{
        //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
        //  try
        //  {
        //    var results = from item in SeedData.Ton.Translations
        //                  where item.Id == dto.Id
        //                  select item;

        //    if (results.Count() == 0)
        //    {
        //      dto.Id = Guid.NewGuid();
        //      //MIMIC LANGUAGEID REQUIRED CONSTRAINT IN DB
        //      if (dto.LanguageId == Guid.Empty || !SeedData.Ton.ContainsLanguageId(dto.LanguageId))
        //      {
        //        //I'VE RESTRUCTURED HOW TO DO EXCEPTIONHANDLING, SO THIS IS NOT QUITE HOW IT SHOULD BE DONE.
        //        //THIS SHOULD BE AN INSERTIMPL METHOD, AND IT SHOULD THROW ITS OWN EXCEPTION THAT IS WRAPPED IN THE
        //        //TranslationDALBASE CLASS IN AN INSERTFAILEDEXCEPTION.
        //        throw new Exceptions.InsertFailedException(string.Format(DalResources.ErrorMsgIdNotFoundException, dto.LanguageId));
        //      }
        //      SeedData.Ton.Translations.Add(dto);
        //      retResult = Result<TranslationDto>.Success(dto);
        //    }
        //    else
        //    {
        //      if (results.Count() == 1) //ID ALREADY EXISTS
        //        retResult = Result<TranslationDto>.FailureWithInfo(dto,
        //          new Exceptions.UpdateFailedException(DalResources.ErrorMsgIdNotFoundException));
        //      else                      //MULTIPLE IDS ALREADY EXIST??
        //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
        //    }
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}
        //public Result<TranslationDto> Delete(Guid id)
        //{
        //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
        //  try
        //  {
        //    var results = from item in SeedData.Ton.Translations
        //                  where item.Id == id
        //                  select item;

        //    if (results.Count() == 1)
        //    {
        //      var TranslationToRemove = results.First();
        //      SeedData.Ton.Translations.Remove(TranslationToRemove);
        //      retResult = Result<TranslationDto>.Success(TranslationToRemove);
        //    }
        //    else
        //    {
        //      if (results.Count() == 0)
        //        retResult = Result<TranslationDto>.FailureWithInfo(null,
        //          new Exceptions.DeleteFailedException(DalResources.ErrorMsgIdNotFoundException));
        //      else
        //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.DeleteFailedException());
        //    }
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}
        //public LearnLanguages.Result<ICollection<TranslationDto>> GetAll()
        //{
        //  Result<ICollection<TranslationDto>> retResult = Result<ICollection<TranslationDto>>.Undefined(null);
        //  try
        //  {
        //    var allDtos = new List<TranslationDto>(SeedData.Ton.Translations);
        //    retResult = Result<ICollection<TranslationDto>>.Success(allDtos);
        //  }
        //  catch (Exception ex)
        //  {
        //    retResult = Result<ICollection<TranslationDto>>.FailureWithInfo(null, ex);
        //  }
        //  return retResult;
        //}

        protected override TranslationDto NewImpl(object criteria)
        {
            var dto = new TranslationDto()
            {
                Id       = Guid.NewGuid(),
                UserId   = SeedData.Ton.GetTestValidUserDto().Id,
                Username = SeedData.Ton.TestValidUsername
            };

            return(dto);
        }
Example #16
0
        /// <summary>
        /// Adds the TranslationDto to the context, loading UserData and PhraseDatas into the newly
        /// created PhraseData.  Does NOT save changes to the context.
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="learnLanguagesContext"></param>
        /// <returns></returns>
        public static TranslationData AddToContext(TranslationDto dto, LearnLanguagesContext context)
        {
            //CREATE NEW TRANSLATIONDATA
            var newTranslationData = context.TranslationDatas.CreateObject();

            //ASSIGN USER INFO
            newTranslationData.UserDataId = dto.UserId;
            //var userResults = (from user in context.UserDatas
            //                   where user.Id == dto.UserId
            //                   select user);
            //if (userResults.Count() == 1)
            //  newTranslationData.UserData = userResults.First();
            //else if (userResults.Count() == 0)
            //  throw new Exceptions.IdNotFoundException(dto.UserId);
            //else
            //{
            //  var errorMsg = string.Format(DalResources.ErrorMsgVeryBadException,
            //                               DalResources.ErrorMsgVeryBadExceptionDetail_ResultCountNotOneOrZero);
            //  throw new Exceptions.VeryBadException(errorMsg);
            //}


            //GET AND ADD PHRASEDATAS TO TRANSLATIONDATA
            if (dto.PhraseIds != null)
            {
                foreach (var id in dto.PhraseIds)
                {
                    var results = (from phrase in context.PhraseDatas
                                   where phrase.Id == id
                                   select phrase);

                    if (results.Count() == 1)
                    {
                        var phraseData = results.First();
                        newTranslationData.PhraseDatas.Add(phraseData);
                    }
                    else if (results.Count() == 0)
                    {
                        throw new Exceptions.IdNotFoundException(id);
                    }
                    else
                    {
                        var errorMsg = string.Format(DalResources.ErrorMsgVeryBadException,
                                                     DalResources.ErrorMsgVeryBadExceptionDetail_ResultCountNotOneOrZero);
                        throw new Exceptions.VeryBadException(errorMsg);
                    }
                }
            }

            //ADD TRANSLATIONDATA TO CONTEXT
            context.TranslationDatas.AddObject(newTranslationData);

            return(newTranslationData);
        }
Example #17
0
        public IActionResult PostTranslation([FromBody] TranslationDto translation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            TranslationService.Create(translation);

            return(CreatedAtAction("GetTranslation", new { id = translation.Id }, translation));
        }
        private static void CheckReferentialIntegrity(TranslationDto dto)
        {
            //PHRASE IDS ARE VALID
            foreach (var id in dto.PhraseIds)
            {
                var count = (from p in SeedData.Ton.Phrases
                             where p.Id == id
                             select p).Count();

                if (count == 1)
                {
                    continue;
                }
                else if (count == 0)
                {
                    throw new Exceptions.IdNotFoundException(id);
                }
                else
                {
                    throw new Exceptions.VeryBadException();
                }
            }

            //CONTEXT PHRASE ID IS VALID
            if (dto.ContextPhraseId != Guid.Empty)
            {
                var contextPhraseIdCount = (from phrase in SeedData.Ton.Phrases
                                            where phrase.Id == dto.ContextPhraseId
                                            select phrase).Count();
                if (contextPhraseIdCount == 0)
                {
                    throw new Exceptions.IdNotFoundException(dto.ContextPhraseId);
                }
                else if (contextPhraseIdCount != 1)
                {
                    throw new Exceptions.VeryBadException();
                }
            }

            //USER IS VALID
            var userCount = (from user in SeedData.Ton.Users
                             where user.Id == dto.UserId &&
                             user.Username == dto.Username
                             select user).Count();

            if (userCount == 0)
            {
                throw new Exceptions.IdNotFoundException(dto.UserId);
            }
            else if (userCount != 1)
            {
                throw new Exceptions.VeryBadException();
            }
        }
 private void CheckValidity(TranslationDto dto)
 {
     //VALIDITY
     if (dto == null)
     {
         throw new ArgumentNullException("dto");
     }
     if (dto.PhraseIds.Count < int.Parse(DalResources.MinPhrasesPerTranslation))
     {
         throw new ArgumentOutOfRangeException("dto.PhraseIds.Count");
     }
 }
        public Task <TranslationDto> GetTranslationAsync(string text)
        {
            var translationDto = new TranslationDto
            {
                Contents = new ContentsDto
                {
                    Translation = "To figure on t springeth season up. H'r provision acuteness hadst excellent two wherefore intention"
                }
            };

            return(Task.Run(() => translationDto));
        }
        public void Delete(TranslationDto incomingXltn)
        {
            var existingXltn = _trnsCtx.Translations.Find(incomingXltn.Key);

            if (existingXltn == null)
            {
                return;
            }

            _trnsCtx.Translations.Remove(existingXltn);
            _trnsCtx.SaveChanges();
        }
Example #22
0
        public static TranslationDto ToDto(TranslationData data)
        {
            var dto = new TranslationDto()
            {
                Id        = data.Id,
                PhraseIds = (from phrase in data.PhraseDatas
                             select phrase.Id).ToList(),
                UserId   = data.UserDataId,
                Username = data.UserData.Username
            };

            return(dto);
        }
Example #23
0
        /// <summary>
        /// Adds the TranslationDto to the context, loading UserData and PhraseDatas into the newly
        /// created PhraseData.  Does NOT save changes to the context.
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="learnLanguagesContext"></param>
        /// <returns></returns>
        public static TranslationData AddToContext(TranslationDto dto, LearnLanguagesContext context)
        {
            //CREATE NEW TRANSLATIONDATA
              var newTranslationData = context.TranslationDatas.CreateObject();

              //ASSIGN USER INFO
              newTranslationData.UserDataId = dto.UserId;
              //var userResults = (from user in context.UserDatas
              //                   where user.Id == dto.UserId
              //                   select user);
              //if (userResults.Count() == 1)
              //  newTranslationData.UserData = userResults.First();
              //else if (userResults.Count() == 0)
              //  throw new Exceptions.IdNotFoundException(dto.UserId);
              //else
              //{
              //  var errorMsg = string.Format(DalResources.ErrorMsgVeryBadException,
              //                               DalResources.ErrorMsgVeryBadExceptionDetail_ResultCountNotOneOrZero);
              //  throw new Exceptions.VeryBadException(errorMsg);
              //}

              //GET AND ADD PHRASEDATAS TO TRANSLATIONDATA
              if (dto.PhraseIds != null)
              {
            foreach (var id in dto.PhraseIds)
            {
              var results = (from phrase in context.PhraseDatas
                         where phrase.Id == id
                         select phrase);

              if (results.Count() == 1)
              {
            var phraseData = results.First();
            newTranslationData.PhraseDatas.Add(phraseData);
              }
              else if (results.Count() == 0)
            throw new Exceptions.IdNotFoundException(id);
              else
              {
            var errorMsg = string.Format(DalResources.ErrorMsgVeryBadException,
                                         DalResources.ErrorMsgVeryBadExceptionDetail_ResultCountNotOneOrZero);
            throw new Exceptions.VeryBadException(errorMsg);
              }
            }
              }

              //ADD TRANSLATIONDATA TO CONTEXT
              context.TranslationDatas.AddObject(newTranslationData);

              return newTranslationData;
        }
Example #24
0
        public IHttpActionResult CreateNewTranslation(TranslationDto translationDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var translation = Mapper.Map <TranslationDto, Translation>(translationDto);

            _context.Translations.Add(translation);
            _context.SaveChanges();

            return(Created(new Uri(Request.RequestUri + "/" + translation.Id), translationDto));
        }
Example #25
0
        public string GetValueOfLanguage(TranslationDto translation, string language)
        {
            switch (language)
            {
            case "en":
                return(translation.EnglishWord);

            case "es":
                return(translation.SpanishWord);

            default:
                throw new Exception($"Failed to get value of langauge {language} from translation.");
            }
        }
Example #26
0
        public static void SaveTranslationDto(TranslationDto translationDto, TranslationsTypeEnum translationType)
        {
            var newUkranianTranslation = translationDto.Translations.FirstOrDefault(t => t.Key == LanguageEnum.Ukrainian);
            var newRussianTranslation  = translationDto.Translations.FirstOrDefault(t => t.Key == LanguageEnum.Russian);

            if (newUkranianTranslation.Equals(default(KeyValuePair <LanguageEnum, string>)) ||
                newRussianTranslation.Equals(default(KeyValuePair <LanguageEnum, string>)))
            {
                throw new Exception("There is no translations for one of the languages");
            }

            SaveTranslation(LanguageEnum.Ukrainian, translationDto.Key, newUkranianTranslation.Value, translationType);
            SaveTranslation(LanguageEnum.Russian, translationDto.Key, newRussianTranslation.Value, translationType);
        }
Example #27
0
        public static TranslationDto FromQueryResponse(this TranslationDto dto, GetMovieTranslationsResponse.Item response)
        {
            if (response == null)
            {
                return(dto);
            }

            return(new TranslationDto
            {
                Language = response.language,
                Overview = response.overview,
                Title = response.title
            });
        }
        public async Task DeleteAsync(TranslationDto incomingXltn)
        {
            var existingXltn = await _trnsCtx.Translations.FindAsync(incomingXltn.Key);

            if (existingXltn == null)
            {
                return;
            }

            // There is no RemoveAsync in EFCore
            // https://github.com/dotnet/efcore/issues/18746
            _ = _trnsCtx.Translations.Remove(existingXltn);
            _ = await _trnsCtx.SaveChangesAsync();
        }
Example #29
0
        public static TranslationDto FromQueryResponse(this TranslationDto dto, GetMovieTranslationsResponse.Translation response)
        {
            if (response == null)
            {
                return(dto);
            }

            return(new TranslationDto
            {
                Language = response.iso_639_1,
                Overview = response.data.overview,
                Title = response.data.title
            });
        }
Example #30
0
        public static IShakespeareTranslationService GetMocked200TranslationService()
        {
            var translationDto = new TranslationDto
            {
                Contents = new ContentsDto
                {
                    Translation = "To figure on t springeth season up. H'r provision acuteness hadst excellent two wherefore intention"
                }
            };
            var httpClient = new HttpClient(new GenericServiceReturn200ResponseHandler <TranslationDto>(translationDto))
            {
                BaseAddress = new System.Uri("http://dummy.com/")
            };
            var logger = Mock.Of <ILogger <ShakespeareTranslationService> >();

            return(new ShakespeareTranslationService(httpClient, logger));
        }
        protected override TranslationDto NewImpl(object criteria)
        {
            var    identity        = (UserIdentity)Csla.ApplicationContext.User.Identity;
            string currentUsername = identity.Name;
            Guid   currentUserId   = identity.UserId;

            TranslationDto newTranslationDto = new TranslationDto()
            {
                Id              = Guid.NewGuid(),
                PhraseIds       = null,
                ContextPhraseId = Guid.Empty,
                UserId          = currentUserId,
                Username        = currentUsername,
            };

            return(newTranslationDto);
        }
Example #32
0
    protected override TranslationDto NewImpl(object criteria)
    {
      var identity = (UserIdentity)Csla.ApplicationContext.User.Identity;
      string currentUsername = identity.Name;
      Guid currentUserId = identity.UserId;

      TranslationDto newTranslationDto = new TranslationDto()
      {
        Id = Guid.NewGuid(),
        PhraseIds = null,
        ContextPhraseId = Guid.Empty,
        UserId = currentUserId,
        Username = currentUsername,
      };

      return newTranslationDto;
    }
        protected override TranslationDto InsertImpl(TranslationDto dto)
        {
            var results = from item in SeedData.Instance.Translations
                    where item.Id == dto.Id
                    select item;

              if (results.Count() == 0)
              {
            CheckValidity(dto);
            dto.Id = Guid.NewGuid();
            SeedData.Instance.Translations.Add(dto);
            return dto;
              }
              else
              {
            if (results.Count() == 1) //ID ALREADY EXISTS
              throw new Exceptions.IdAlreadyExistsException(dto.Id);
            else                      //MULTIPLE IDS ALREADY EXIST??
              throw new Exceptions.VeryBadException();
              }
        }
        private static void CheckReferentialIntegrity(TranslationDto dto)
        {
            //PHRASE IDS ARE VALID
              foreach (var id in dto.PhraseIds)
              {
            var count = (from p in SeedData.Ton.Phrases
                     where p.Id == id
                     select p).Count();

            if (count == 1)
              continue;
            else if (count == 0)
              throw new Exceptions.IdNotFoundException(id);
            else
              throw new Exceptions.VeryBadException();
              }

              //CONTEXT PHRASE ID IS VALID
              if (dto.ContextPhraseId != Guid.Empty)
              {
            var contextPhraseIdCount = (from phrase in SeedData.Ton.Phrases
                                    where phrase.Id == dto.ContextPhraseId
                                    select phrase).Count();
            if (contextPhraseIdCount == 0)
              throw new Exceptions.IdNotFoundException(dto.ContextPhraseId);
            else if (contextPhraseIdCount != 1)
              throw new Exceptions.VeryBadException();
              }

              //USER IS VALID
              var userCount = (from user in SeedData.Ton.Users
                       where user.Id == dto.UserId &&
                             user.Username == dto.Username
                       select user).Count();
              if (userCount == 0)
            throw new Exceptions.IdNotFoundException(dto.UserId);
              else if (userCount != 1)
            throw new Exceptions.VeryBadException();
        }
Example #35
0
    /// <summary>
    /// Loads the information from the dto into the data object. Except...
    /// Does NOT load dto.Id.
    /// </summary>
    /// <param name="data"></param>
    /// <param name="dto"></param>
    public static void LoadDataFromDto(ref TranslationData data, 
                                       TranslationDto dto, 
                                       LearnLanguagesContext context)
    {
      //COPY USER INFO
      data.UserDataId = dto.UserId;
      data.UserData = EfHelper.GetUserData(dto.UserId, context);

      var currentPhraseIds = (from phrase in data.PhraseDatas
                              select phrase.Id);

      //COPY PHRASEID INFO
      //ADD NEW PHRASEDATAS IN THE DTO
      foreach (var id in dto.PhraseIds)
      {
        if (!currentPhraseIds.Contains(id))
        {
          PhraseData phraseData = EfHelper.GetPhraseData(id, context);
          data.PhraseDatas.Add(phraseData);
        }
      }

      //REMOVE PHRASEDATAS THAT ARE NOT IN DTO ANYMORE
      foreach (var phraseId in currentPhraseIds)
      {
        if (!dto.PhraseIds.Contains(phraseId))
        {
          var dataToRemove = (from phraseData in data.PhraseDatas
                              where phraseData.Id == phraseId
                              select phraseData).First();
          data.PhraseDatas.Remove(dataToRemove);
        }
      }
    }
        protected override TranslationDto UpdateImpl(TranslationDto dto)
        {
            using (var ctx = LearnLanguagesContextManager.Instance.GetManager())
              {
            var results = (from translationData in ctx.ObjectContext.TranslationDatas
                       where translationData.Id == dto.Id &&
                             translationData.UserDataId == dto.UserId
                       select translationData);

            if (results.Count() == 1)
            {
              //UPDATE THE TRANSLATIONDATA IN THE CONTEXT
              var translationData = results.First();
              EfHelper.LoadDataFromDto(ref translationData, dto, ctx.ObjectContext);

              //SAVE TO MAKE SURE AFFECTED USERS ARE UPDATED TO REMOVE THIS PHRASE
              ctx.ObjectContext.SaveChanges();

              var updatedDto = EfHelper.ToDto(translationData);
              return updatedDto;
            }
            else
            {
              if (results.Count() == 0)
            throw new Exceptions.IdNotFoundException(dto.Id);
              else
              {
            //results.count is not one or zero.  either it's negative, which would be framework absurd, or its more than one,
            //which means that we have multiple phrases with the same id.  this is very bad.
            var errorMsg = string.Format(DalResources.ErrorMsgVeryBadException,
                                         DalResources.ErrorMsgVeryBadExceptionDetail_ResultCountNotOneOrZero);
            throw new Exceptions.VeryBadException(errorMsg);
              }
            }
              }
        }
 private void CheckValidity(TranslationDto dto)
 {
     //VALIDITY
       if (dto == null)
     throw new ArgumentNullException("dto");
       if (dto.PhraseIds.Count < int.Parse(DalResources.MinPhrasesPerTranslation))
     throw new ArgumentOutOfRangeException("dto.PhraseIds.Count");
 }
        private static void CheckReferentialIntegrity(TranslationDto dto)
        {
            //REFERENTIAL INTEGRITY
              foreach (var id in dto.PhraseIds)
              {
            var count = (from p in SeedData.Instance.Phrases
                     where p.Id == id
                     select p).Count();

            if (count == 1)
              continue;
            else if (count == 0)
              throw new Exceptions.IdNotFoundException(id);
            else
              throw new Exceptions.VeryBadException();
              }
        }
        protected override TranslationDto UpdateImpl(TranslationDto dto)
        {
            var results = from item in SeedData.Instance.Translations
                    where item.Id == dto.Id
                    select item;

              if (results.Count() == 1)
              {
            CheckValidity(dto);
            CheckReferentialIntegrity(dto);
            var TranslationToUpdate = results.First();
            SeedData.Instance.Translations.Remove(TranslationToUpdate);
            dto.Id = Guid.NewGuid();
            SeedData.Instance.Translations.Add(dto);
            return dto;
              }
              else
              {
            if (results.Count() == 0)
              throw new Exceptions.IdNotFoundException(dto.Id);
            else
              throw new Exceptions.VeryBadException();
              }
        }
 //public Result<TranslationDto> New(object criteria)
 //{
 //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
 //  try
 //  {
 //    var dto = new TranslationDto()
 //    {
 //      Id = Guid.NewGuid(),
 //      LanguageId = SeedData.Instance.DefaultLanguageId
 //    };
 //    retResult = Result<TranslationDto>.Success(dto);
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 //public Result<TranslationDto> Fetch(Guid id)
 //{
 //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
 //  try
 //  {
 //    var results = from item in SeedData.Instance.Translations
 //                  where item.Id == id
 //                  select item;
 //    if (results.Count() == 1)
 //      retResult = Result<TranslationDto>.Success(results.First());
 //    else
 //    {
 //      if (results.Count() == 0)
 //        retResult = Result<TranslationDto>.FailureWithInfo(null,
 //          new Exceptions.FetchFailedException(DalResources.ErrorMsgIdNotFoundException));
 //      else
 //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
 //    }
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 //public Result<TranslationDto> Update(TranslationDto dto)
 //{
 //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
 //  try
 //  {
 //    var results = from item in SeedData.Instance.Translations
 //                  where item.Id == dto.Id
 //                  select item;
 //    if (results.Count() == 1)
 //    {
 //      var TranslationToUpdate = results.First();
 //      SeedData.Instance.Translations.Remove(TranslationToUpdate);
 //      dto.Id = Guid.NewGuid();
 //      SeedData.Instance.Translations.Add(dto);
 //      retResult = Result<TranslationDto>.Success(dto);
 //    }
 //    else
 //    {
 //      if (results.Count() == 0)
 //        retResult = Result<TranslationDto>.FailureWithInfo(null,
 //          new Exceptions.UpdateFailedException(DalResources.ErrorMsgIdNotFoundException));
 //      else
 //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
 //    }
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 //public Result<TranslationDto> Insert(TranslationDto dto)
 //{
 //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
 //  try
 //  {
 //    var results = from item in SeedData.Instance.Translations
 //                  where item.Id == dto.Id
 //                  select item;
 //    if (results.Count() == 0)
 //    {
 //      dto.Id = Guid.NewGuid();
 //      //MIMIC LANGUAGEID REQUIRED CONSTRAINT IN DB
 //      if (dto.LanguageId == Guid.Empty || !SeedData.Instance.ContainsLanguageId(dto.LanguageId))
 //      {
 //        //I'VE RESTRUCTURED HOW TO DO EXCEPTIONHANDLING, SO THIS IS NOT QUITE HOW IT SHOULD BE DONE.
 //        //THIS SHOULD BE AN INSERTIMPL METHOD, AND IT SHOULD THROW ITS OWN EXCEPTION THAT IS WRAPPED IN THE
 //        //TranslationDALBASE CLASS IN AN INSERTFAILEDEXCEPTION.
 //        throw new Exceptions.InsertFailedException(string.Format(DalResources.ErrorMsgIdNotFoundException, dto.LanguageId));
 //      }
 //      SeedData.Instance.Translations.Add(dto);
 //      retResult = Result<TranslationDto>.Success(dto);
 //    }
 //    else
 //    {
 //      if (results.Count() == 1) //ID ALREADY EXISTS
 //        retResult = Result<TranslationDto>.FailureWithInfo(dto,
 //          new Exceptions.UpdateFailedException(DalResources.ErrorMsgIdNotFoundException));
 //      else                      //MULTIPLE IDS ALREADY EXIST??
 //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.FetchFailedException());
 //    }
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 //public Result<TranslationDto> Delete(Guid id)
 //{
 //  Result<TranslationDto> retResult = Result<TranslationDto>.Undefined(null);
 //  try
 //  {
 //    var results = from item in SeedData.Instance.Translations
 //                  where item.Id == id
 //                  select item;
 //    if (results.Count() == 1)
 //    {
 //      var TranslationToRemove = results.First();
 //      SeedData.Instance.Translations.Remove(TranslationToRemove);
 //      retResult = Result<TranslationDto>.Success(TranslationToRemove);
 //    }
 //    else
 //    {
 //      if (results.Count() == 0)
 //        retResult = Result<TranslationDto>.FailureWithInfo(null,
 //          new Exceptions.DeleteFailedException(DalResources.ErrorMsgIdNotFoundException));
 //      else
 //        retResult = Result<TranslationDto>.FailureWithInfo(null, new Exceptions.DeleteFailedException());
 //    }
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<TranslationDto>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 //public LearnLanguages.Result<ICollection<TranslationDto>> GetAll()
 //{
 //  Result<ICollection<TranslationDto>> retResult = Result<ICollection<TranslationDto>>.Undefined(null);
 //  try
 //  {
 //    var allDtos = new List<TranslationDto>(SeedData.Instance.Translations);
 //    retResult = Result<ICollection<TranslationDto>>.Success(allDtos);
 //  }
 //  catch (Exception ex)
 //  {
 //    retResult = Result<ICollection<TranslationDto>>.FailureWithInfo(null, ex);
 //  }
 //  return retResult;
 //}
 protected override TranslationDto NewImpl(object criteria)
 {
     var dto = new TranslationDto()
       {
     Id = Guid.NewGuid(),
     UserId = SeedData.Instance.GetTestValidUserDto().Id,
     Username = SeedData.Instance.TestValidUsername
       };
       return dto;
 }
Example #41
0
    public static TranslationDto ToDto(TranslationData data)
    {
      var dto = new TranslationDto()
      {
        Id = data.Id,
        PhraseIds = (from phrase in data.PhraseDatas
                     select phrase.Id).ToList(),
        UserId = data.UserDataId,
        Username = data.UserData.Username
      };

      return dto;
    }
 protected override TranslationDto InsertImpl(TranslationDto dto)
 {
     using (var ctx = LearnLanguagesContextManager.Instance.GetManager())
       {
     var newTranslationData = EfHelper.AddToContext(dto, ctx.ObjectContext);
     ctx.ObjectContext.SaveChanges();
     dto.Id = newTranslationData.Id;
     return dto;
       }
 }