示例#1
0
        public CompetitionDTO ImportCompetition(string competitionId)
        {
            CompetitionDTO _competition = null;

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(Util.Util.URICompetition());
                    client.DefaultRequestHeaders.Add(Util.Util.APITokenName(), Util.Util.APITokenValue());
                    //HTTP GET
                    var responseTask = client.GetAsync(competitionId);
                    responseTask.Wait();

                    var result = responseTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        var readTask = result.Content.ReadAsAsync <CompetitionDTO>();
                        readTask.Wait();
                        _competition = readTask.Result;
                    }
                    else
                    {
                        throw new Exception(result.StatusCode.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(_competition);
        }
示例#2
0
        public static IList <CompetitionDTO> ObjectsToDTOs(IList <Competition> objs)
        {
            IList <CompetitionDTO> list = new List <CompetitionDTO>();

            foreach (Competition obj in objs)
            {
                CompetitionDTO dto = ObjectToDTO(obj);
                list.Add(dto);
            }

            return(list);
        }
示例#3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CompetitionCI"/> class
        /// </summary>
        /// <param name="eventSummary">The event summary</param>
        /// <param name="dataRouterManager">The <see cref="IDataRouterManager"/> used to obtain summary and fixtureDTO</param>
        /// <param name="semaphorePool">The semaphore pool</param>
        /// <param name="currentCulture">The current culture</param>
        /// <param name="defaultCulture">The default culture</param>
        /// <param name="fixtureTimestampCache">A <see cref="MemoryCache"/> used to cache the sport events fixtureDTO timestamps</param>
        public CompetitionCI(CompetitionDTO eventSummary,
                             IDataRouterManager dataRouterManager,
                             ISemaphorePool semaphorePool,
                             CultureInfo currentCulture,
                             CultureInfo defaultCulture,
                             MemoryCache fixtureTimestampCache)
            : base(eventSummary, dataRouterManager, semaphorePool, currentCulture, defaultCulture, fixtureTimestampCache)
        {
            Guard.Argument(eventSummary, nameof(eventSummary)).NotNull();
            Guard.Argument(currentCulture, nameof(currentCulture)).NotNull();

            Merge(eventSummary, currentCulture, true);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompetitionCI"/> class
        /// </summary>
        /// <param name="eventSummary">The event summary</param>
        /// <param name="dataRouterManager">The <see cref="IDataRouterManager"/> used to obtain summary and fixture</param>
        /// <param name="semaphorePool">The semaphore pool</param>
        /// <param name="currentCulture">The current culture</param>
        /// <param name="defaultCulture">The default culture</param>
        /// <param name="fixtureTimestampCache">A <see cref="ObjectCache"/> used to cache the sport events fixture timestamps</param>
        public CompetitionCI(CompetitionDTO eventSummary,
                             IDataRouterManager dataRouterManager,
                             ISemaphorePool semaphorePool,
                             CultureInfo currentCulture,
                             CultureInfo defaultCulture,
                             ObjectCache fixtureTimestampCache)
            : base(eventSummary, dataRouterManager, semaphorePool, currentCulture, defaultCulture, fixtureTimestampCache)
        {
            Contract.Requires(eventSummary != null);
            Contract.Requires(currentCulture != null);

            Merge(eventSummary, currentCulture, true);
        }
示例#5
0
        /// <summary>
        /// Merges the specified event summary
        /// </summary>
        /// <param name="eventSummary">The event summary</param>
        /// <param name="culture">The culture</param>
        private void ActualMerge(CompetitionDTO eventSummary, CultureInfo culture)
        {
            base.Merge(eventSummary, culture, false);

            if (eventSummary.Venue != null)
            {
                if (_venue == null)
                {
                    _venue = new VenueCI(eventSummary.Venue, culture);
                }
                else
                {
                    _venue.Merge(eventSummary.Venue, culture);
                }
            }
            if (eventSummary.Conditions != null)
            {
                if (_conditions == null)
                {
                    _conditions = new SportEventConditionsCI(eventSummary.Conditions, culture);
                }
                else
                {
                    _conditions.Merge(eventSummary.Conditions, culture);
                }
            }
            if (eventSummary.Competitors != null)
            {
                Competitors = new List <URN>(eventSummary.Competitors.Select(t => t.Id));
                GenerateMatchName(eventSummary.Competitors, culture);
                FillCompetitorsQualifiers(eventSummary.Competitors);
                FillCompetitorsReferences(eventSummary.Competitors);
                FillCompetitorsVirtual(eventSummary.Competitors);
            }
            if (eventSummary.BookingStatus != null)
            {
                _bookingStatus = eventSummary.BookingStatus;
            }
            if (!string.IsNullOrEmpty(eventSummary.LiveOdds))
            {
                _liveOdds = eventSummary.LiveOdds;
            }
            if (eventSummary.Type != null)
            {
                _sportEventType = eventSummary.Type;
            }
            if (eventSummary.StageType != null)
            {
                _stageType = eventSummary.StageType;
            }
        }
示例#6
0
 /// <summary>
 /// Merges the specified event summary
 /// </summary>
 /// <param name="eventSummary">The event summary</param>
 /// <param name="culture">The culture</param>
 /// <param name="useLock">Should the lock mechanism be used during merge</param>
 public void Merge(CompetitionDTO eventSummary, CultureInfo culture, bool useLock)
 {
     if (useLock)
     {
         lock (MergeLock)
         {
             ActualMerge(eventSummary, culture);
         }
     }
     else
     {
         ActualMerge(eventSummary, culture);
     }
 }
        public async System.Threading.Tasks.Task HttpCall()
        {
            results = new List <CompetitionDTO>();
            var result = new CompetitionDTO()
            {
                Caption         = "tytul",
                CurrentMatchday = 2,
                Id                = 1,
                League            = "premier liga",
                NumberOfMatchdays = 3,
                NumberOfTeams     = 4,
            };

            results.Add(result);
        }
        public bool UpdateCompetition(CompetitionDTO competition)
        {
            try
            {
                this.competitionUnitOfWork.CompetitionRepository.Update(
                    ObjectMapper <CompetitionDTO, CompetitionEntity> .Map(competition));
                this.competitionUnitOfWork.SaveChanges();
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
示例#9
0
        /// <summary>
        /// Update a competition
        /// </summary>
        /// <param name="competitionDto">Competition to update</param>
        /// <returns></returns>
        /// <exception cref="EntityNotFoundException<Competition>"></exception>
        public async Task UpdateAsync(CompetitionDTO competitionDto)
        {
            await this.Repository.TransactionalExecutionAsync(
                action : async(competition, transaction) =>
            {
                //Check if the competition already exists
                var toUpdateCompetition = await this.Repository.GetByIdAsync(competition.Id);
                if (toUpdateCompetition == null)
                {
                    throw new EntityNotFoundException <Competition>();
                }

                toUpdateCompetition.CopyFrom(competition);

                //Save the competition
                await this.Repository.SaveChangesAsync();
            },
                obj : this.Mapper.Map <Competition>(competitionDto));
        }
        public static ResultsElementResponseModel ToResultsElementResponseModel(
            CompetitionDTO competitionDTO,
            string stage,
            IAccountService accountService)
        {
            StringBuilder stringBuilder = new StringBuilder();
            var           resultElement = new ResultsElementResponseModel()
            {
                Skill       = competitionDTO.Skill.Name,
                DateOfBegin = competitionDTO.DateTimeBegin.ToShortDateString(),
                DateOfEnd   = competitionDTO.DateTimeEnd.ToShortDateString()
            };

            foreach (var stageDTO in competitionDTO.Stages)
            {
                if ((stage != "All" && stageDTO.StageType.Name == stage) || stage == "All")
                {
                    var resultsStage = new ResultsStage()
                    {
                        Type = stageDTO.StageType.Name
                    };
                    foreach (var task in stageDTO.Tasks)
                    {
                        foreach (var answer in task.Answers)
                        {
                            var result = new ResultsResultRecords()
                            {
                                Mark = answer.Result.Mark
                            };
                            var    participant         = accountService.GetAccountById(answer.AccountId);
                            string participantFullName =
                                $"{participant.PersonalData.Surname} {participant.PersonalData.Name} {participant.PersonalData.Patronymic}";
                            result.Participant = participantFullName;
                            resultsStage.ResultRecords.Add(result);
                        }
                    }

                    resultElement.Stages.Add(resultsStage);
                }
            }

            return(resultElement);
        }
示例#11
0
        }// End of ObjectToDTO function

        public static Competition DTOToObject(CompetitionDTO dto)
        {
            return(new Competition
            {
                name = dto.name,
                description = dto.description,
                date_start = DataConvert.StringJsonToDateTime(dto.date_start),
                date_finish = DataConvert.StringJsonToDateTime(dto.date_finish),
                competition_event = dto.competition_event,
                competition_type = dto.competition_type,
                competitors_limit = dto.competitors_limit,
                categories = dto.categories,
                image_url = dto.image_url,
                user = dto.user,
                cost = dto.cost,
                timestamp = DataConvert.StringJsonToDateTime(dto.timestamp),
                updated = DataConvert.StringJsonToDateTime(dto.updated),
            });
        }
        public async Task <ActionResult <CompetitionDTO> > GetById(int id)
        {
            Competition competition = await _competitionRepositry.GetById(id);

            CompetitionDTO competitionDTO = competition.ToDTO();
            IEnumerable <CompetitionApplication> applications = await _competitionRepositry.GetAllApplications(competitionDTO.Id);

            Educator edc = await _educatorRepository.GetByCourseId(competitionDTO.CourseId);

            competitionDTO.Educator = edc.ToDTO();
            if (applications.Count() != 0)
            {
                competitionDTO.Applications = applications.ToDTOList();

                competitionDTO.CurrentCandidatesNumber = applications.Count();
            }


            return(Ok(competitionDTO));
        }
示例#13
0
        /// <summary>
        /// Object to data transfer object
        /// </summary>
        /// <param name="authentication"></param>
        /// <returns></returns>
        public static CompetitionDTO ObjectToDTO(Competition competition)
        {
            CompetitionDTO dto = new CompetitionDTO();

            dto.name              = competition.name;
            dto.description       = competition.description;
            dto.date_start        = DataConvert.DateTimeToJsonStringWithTime(competition.date_start);
            dto.date_finish       = DataConvert.DateTimeToJsonStringWithTime(competition.date_finish);
            dto.competition_event = competition.competition_event;
            dto.competition_type  = competition.competition_type;
            dto.competitors_limit = competition.competitors_limit;
            dto.categories        = competition.categories;
            dto.image_url         = competition.image_url;
            dto.user              = competition.user;
            dto.cost              = competition.cost;
            dto.timestamp         = DataConvert.DateTimeToJsonString(competition.timestamp);
            dto.updated           = DataConvert.DateTimeToJsonString(competition.updated);


            return(dto);
        }// End of ObjectToDTO function
        public static CompetitionResponseModel ToCompetitionForAdminResponseModel(CompetitionDTO competitionDTO)
        {
            StringBuilder stringBuilder = new StringBuilder();
            var           competitionForAdminResponseModel = new CompetitionResponseModel()
            {
                Id          = competitionDTO.Id,
                Skill       = competitionDTO.Skill.Name,
                DateOfBegin = competitionDTO.DateTimeBegin.ToString(dateFormat),
                DateOfEnd   = competitionDTO.DateTimeEnd.ToString(dateFormat)
            };

            foreach (var stageDTO in competitionDTO.Stages)
            {
                var stage = new StageResponseModel()
                {
                    Id   = stageDTO.Id,
                    Type = stageDTO.StageType.Name
                };
                foreach (var taskDTO in stageDTO.Tasks)
                {
                    var task = new TaskResponseModel()
                    {
                        Id              = taskDTO.Id,
                        Description     = taskDTO.Description,
                        TaskDateOfBegin = taskDTO.DateTimeBegin.ToString(dateFormat)
                    };
                    var dateOfEnd = taskDTO.DateTimeBegin + taskDTO.DurationTime;
                    task.TaskDateOfEnd = dateOfEnd.ToString(dateFormat);
                    task.IsActual      = dateOfEnd < DateTime.Now;
                    foreach (var address in taskDTO.Addresses)
                    {
                        stringBuilder.Append(address + "; ");
                    }
                    task.Addresses = stringBuilder.ToString();
                    stage.Tasks.Add(task);
                }
                competitionForAdminResponseModel.Stages.Add(stage);
            }
            return(competitionForAdminResponseModel);
        }
        public static ScheduleElementResponseModel ToModel(CompetitionDTO competitionDTO)
        {
            StringBuilder stringBuilder   = new StringBuilder();
            var           scheduleElement = new ScheduleElementResponseModel()
            {
                Skill       = competitionDTO.Skill.Name,
                DateOfBegin = competitionDTO.DateTimeBegin.ToShortDateString(),
                DateOfEnd   = competitionDTO.DateTimeEnd.ToShortDateString()
            };

            foreach (var stage in competitionDTO.Stages)
            {
                var competitionStage = new ScheduleElementResponseModel.CompetitionStage()
                {
                    Type = stage.StageType.Name
                };
                foreach (var task in stage.Tasks)
                {
                    var stageTask = new ScheduleElementResponseModel.CompetitionStage.StageTask()
                    {
                        TaskDateOfBegin = task.DateTimeBegin.ToString(dateFormatForDateTime)
                    };
                    var dateOfEnd = task.DateTimeBegin + task.DurationTime;
                    stageTask.TaskDateOfEnd = dateOfEnd.ToString(dateFormatForDateTime);
                    stageTask.IsActual      = dateOfEnd < DateTime.Now;
                    foreach (var address in task.Addresses)
                    {
                        stringBuilder.Append(address);
                        stringBuilder.Append("; ");
                    }

                    stageTask.Addresses = stringBuilder.ToString();
                    competitionStage.Tasks.Add(stageTask);
                }

                scheduleElement.Stages.Add(competitionStage);
            }

            return(scheduleElement);
        }
示例#16
0
        //
        // GET: /Discgolftouren/
        public ActionResult Index()
        {
            var vm           = new CompetitionsViewModel();
            var competitions = new List <Competition>();

            using (var session = NHibernateFactory.OpenSession())
            {
                competitions = session.Query <Competition>().Where(c => c.Date.Year == DateTime.Now.Year).OrderBy(c => c.Date).ToList();
            }
            foreach (var competition in competitions)
            {
                var cp = new CompetitionDTO()
                {
                    Id   = competition.Id,
                    Name = competition.Name,
                    Date = competition.Date
                };
                vm.Competitions.Add(cp);
            }

            return(View(vm));
        }
        /// <summary>
        /// Metoda do pobrania z API danych oraz wczytywanie ich do widoku.
        /// </summary>
        /// <param name="caption">Labelka nagłówka</param>
        /// <param name="currentMatchday">Labelka informujaca o obecnej turze ligi</param>
        /// <param name="numberOfMatchdays">Labelka informujaca o ilosci rozgrywanych meczy</param>
        /// <param name="numberOfTeams">Labelka informujaca o ilosci druzyn</param>
        /// <param name="year">Labelka informujaca o roku danych rozgrywek</param>
        public async void DownloadData(Label caption, Label year, Label currentMatchday, Label numberOfMatchdays, Label numberOfTeams)
        {
            try
            {
                HttpClient          client   = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(new Uri(Configuration.API_COMPETITIONS + "/" + (Application.Current as App).CompetitionId));

                string responseJson = await response.Content.ReadAsStringAsync();

                Result = JsonConvert.DeserializeObject <CompetitionDTO>(responseJson);
            }
            catch (Exception ex)
            { }

            if (Result != null)
            {
                caption.Text           = Result.Caption;
                year.Text              = Result.Year;
                currentMatchday.Text   = Result.CurrentMatchday.ToString();
                numberOfMatchdays.Text = Result.NumberOfMatchdays.ToString();
                numberOfTeams.Text     = Result.NumberOfTeams.ToString();
            }
        }
示例#18
0
        /// <summary>
        /// Create a new competition
        /// </summary>
        /// <param name="competitionDto">Competition to crate</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="EntityAlreadyExistsException{TEntity}"<Competition>"></exception>
        public async Task <CompetitionDTO> CreateAsync(CompetitionDTO competitionDto)
        {
            if (competitionDto == null)
            {
                throw new ArgumentNullException(nameof(competitionDto));
            }

            return(await this.Repository.TransactionalExecutionAsync(
                       action : async(competition, transaction) =>
            {
                //Check if the competition does not already exist
                var searchedCompetition = await this.Repository.GetByUniqueKeyAsync(competition);
                if (searchedCompetition != null)
                {
                    throw new EntityAlreadyExistsException <Competition>(competition);
                }

                //Add the competition
                await this.Repository.AddAsync(competition);
                await this.Repository.SaveChangesAsync();
            },
                       obj : this.Mapper.Map <Competition>(competitionDto),
                       onSuccessFunc : (createdCompetition => this.Mapper.Map <CompetitionDTO>(createdCompetition))));
        }
示例#19
0
        public ActionResult Tournament(CompetitionsViewModel vm, int id = -1)
        {
            vm.YearsList = new List <SelectListItem>();

            AddYear(vm.YearsList, "2015", vm.SelectedYear);
            AddYear(vm.YearsList, "2016", vm.SelectedYear);


            if (id != -1)
            {
                // hämta data för tävling
                using (var session = NHibernateFactory.OpenSession())
                {
                    var competition = session.Get <Competition>(id);
                    if (competition != null)
                    {
                        vm.Competition = new CompetitionDTO()
                        {
                            Id          = competition.Id,
                            Name        = competition.Name,
                            Date        = competition.Date,
                            PGDAWebPage = competition.PdgaWebPage,
                            Description = competition.Description
                        };

                        var players = session.Query <PlayerStatus>().Where(p => p.Competition.Id == competition.Id);

                        foreach (var player in players.Where(p => p.Status == NHibernate.Enums.PlayerCompetitionStatus.Payed))
                        {
                            vm.Competition.Players.Add(new PlayerDTO()
                            {
                                Namn   = string.Format("{0} {1}", player.Player.FirstName, player.Player.LastName),
                                PDGA   = player.Player.PdgaNumber,
                                Rating = player.Player.Rating
                            });
                        }

                        foreach (var player in players.Where(p => p.Status == NHibernate.Enums.PlayerCompetitionStatus.Registered))
                        {
                            vm.Competition.RegisteredPlayers.Add(new PlayerDTO()
                            {
                                Namn   = string.Format("{0} {1}", player.Player.FirstName, player.Player.LastName),
                                PDGA   = player.Player.PdgaNumber,
                                Rating = player.Player.Rating
                            });
                        }

                        foreach (var player in players.Where(p => p.Status == NHibernate.Enums.PlayerCompetitionStatus.Waiting))
                        {
                            vm.Competition.WaitingPlayers.Add(new PlayerDTO()
                            {
                                Namn   = string.Format("{0} {1}", player.Player.FirstName, player.Player.LastName),
                                PDGA   = player.Player.PdgaNumber,
                                Rating = player.Player.Rating
                            });
                        }
                    }
                }
            }
            else
            {
                // hämta data för tävlingar
                var competitions = new List <Competition>();
                using (var session = NHibernateFactory.OpenSession())
                {
                    competitions = session.Query <Competition>().Where(c => c.Date.Year == int.Parse(vm.SelectedYear)).OrderBy(c => c.Date).ToList();
                }

                foreach (var competition in competitions)
                {
                    var cp = new CompetitionDTO()
                    {
                        Id   = competition.Id,
                        Name = competition.Name,
                        Date = competition.Date,
                    };
                    vm.Competitions.Add(cp);
                }
            }

            return(View(vm));
        }
示例#20
0
        public HttpResponseMessage Get(string id)
        {
            CompetitionDTO _competitionDTO = null;

            try
            {
                //
                //var container = ContainerConfig.Configure();


                using (var scope = this.Configuration.DependencyResolver.BeginScope()) {
                    var _competition = scope.GetService(typeof(Dom.ICompetition));
                }

                using (var scope = container.BeginLifetimeScope())
                {
                    var _competitionLogic = scope.Resolve <Dom.ICompetition>();
                    var _teamLogic        = scope.Resolve <Dom.ITeam>();
                    var _playerLogic      = scope.Resolve <Dom.IPlayer>();
                    var _areaLogic        = scope.Resolve <Dom.IArea>();

                    #region importando Conpeticion

                    _competitionDTO = _competitionLogic.ImportCompetition(id);

                    if (_competitionDTO == null)
                    {
                        throw new Exception("504");
                    }

                    //Importamos lo equipos

                    var _teamsLogic = scope.Resolve <Dom.ITeam>();
                    _competitionDTO.Teams = _teamsLogic.ImportTeamsFromCompetition(id);

                    if (_competitionDTO.Teams != null)
                    {
                        int i = 0;///por solo traer 8
                        foreach (TeamDTO team in _competitionDTO.Teams)
                        {
                            if (i == 8)// SOlo importa los jugadores de los primeros 8 equipos
                            {
                                break;
                            }
                            team.Squad = _playerLogic.ImportPlayersFromTeam(team.Id);
                            i++;
                        }
                    }

                    #endregion importando Conpeticion

                    #region Portando DTO to EF Model
                    //Convertimos DTO a Entity Model
                    var _competitionModelDestino = _mapper.Map <CompetitionModel>(_competitionDTO);
                    _competitionModelDestino.Teams = _mapper.Map <List <TeamDTO>, List <TeamModel> >(_competitionDTO.Teams);

                    #endregion Portando DTO to EF Model

                    #region Guardado Competition

                    //Guardamos la competicion en la DB
                    int _insert = 0;
                    _insert = _competitionLogic.SaveUniqueEntireCompetition(_competitionModelDestino, _playerLogic, _teamLogic, _areaLogic);

                    if (_insert == -1)
                    {
                        //Ya existe la Competicion
                        throw new Exception("429");
                    }
                    else if (_insert == 0)
                    {
                        throw new Exception("0");
                    }

                    #endregion Guardado Competition
                }
            }
            catch (Exception ex)
            {
                int code;
                if (Int32.TryParse(ex.Message, out code))
                {
                    switch (code)
                    {
                    case 400:
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Bad Request"));

                    case 403:
                        return(Request.CreateResponse(HttpStatusCode.Forbidden, "Restricted Resource"));

                    case 404:
                        return(Request.CreateResponse(HttpStatusCode.NotFound, "Not Found"));

                    case 429:
                        return(Request.CreateResponse(HttpStatusCode.Forbidden, "Too Many Requests"));    //"Error:429, Too Many Requests";

                    case 409:
                        return(Request.CreateResponse(HttpStatusCode.Conflict, "League already imported"));

                    case 504:
                        return(Request.CreateResponse(HttpStatusCode.GatewayTimeout, "Server Error"));

                    case 0:
                        return(Request.CreateResponse(HttpStatusCode.Conflict, "No se pudo guardar la competición."));

                    default:
                        return(Request.CreateResponse(HttpStatusCode.GatewayTimeout, "Server Error"));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.Conflict, ex.Message));
                }
            }

            /*
             *   HttpCode 201, {"message": "Successfully imported"} --> When the leagueCode was successfully imported.
             * o	 HttpCode 409, {"message": "League already imported"} --> If the given leagueCode was already imported into the DB (and in this case, it doesn't need to be imported again).
             * o	 HttpCode 404, {"message": "Not found" } --> if the leagueCode was not found.
             * o	 HttpCode 504, {"message": "Server Error" } --> If there is any connectivity issue either with the football API or the DB server.
             */
            return(Request.CreateResponse(HttpStatusCode.Created, "Successfully imported"));
        }
        public async Task <ActionResult <CompetitionDTO> > CreateAsync(CompetitionDTO competitionDto)
        {
            var addedCompetition = await this.Service.CreateAsync(competitionDto);

            return(this.Created($"{HttpContext.Request.Path}/{addedCompetition.Id}", addedCompetition));
        }
        public async Task <ActionResult> UpdateAsync(CompetitionDTO competitionDto)
        {
            await this.Service.UpdateAsync(competitionDto);

            return(this.NoContent());
        }