public void Test(ITestContext context)
        {
            if (this.url.IsNullOrEmpty() || this.url == "/" || this.url == "~" || this.url == "~/")
            {
                this.url = this.FullyQualifiedApplicationPath(context);
            }

            if (this.action.IsNullOrEmpty())
            {
                throw new ApplicationException(Errors.UrlAndActionCannotBeEmpty);
            }

            this.service = new WebApiService { Timeout = this.timeout };

            try
            {
                var result = this.arguments == null
                                 ? this.service.Get<object>(this.url, this.action)
                                 : this.service.Get<object>(this.url, this.action, this.arguments);
            }
            catch (WebApiException ex)
            {
                Assert.Fails(Errors.FailedToAccessService, ex.Message);
            }
        }
Example #2
0
        public async Task Api_1_Test()
        {
            var locator = new WebApiLocator(); // {ServiceDomain = "dev-test.rnd.ipzo.net"};

            Console.WriteLine("Testing in {0}", locator.ServiceDomain);

            WebApiService svc = await locator.Locate("api1");

            Assert.IsNotNull(svc);

            svc.Decryptor.KeyPhrase = "dev";

            Uri[] uriArray = svc.Uris.ToArray();
            Assert.IsTrue(uriArray.Length > 0);

            foreach (Uri u in uriArray)
            {
                Console.WriteLine(u.ToString());
            }

            Assert.AreEqual(
                "https://[email protected]/api",
                uriArray[0].ToString()
                );

            Assert.IsTrue(svc.Headers.Count > 0);
            Assert.AreEqual("Banana", svc.Headers["X-Custom-Header"]);
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            string fullLink     = $"{baseUri}/SchoolUser";
            var    userIdentity = User as ClaimsPrincipal;

            string loggedUserId = _user.GetUserId(userIdentity);

            if (loggedUserId == null)
            {
                var viewModel = new NavbarVm()
                {
                    Action     = "Index",
                    Controller = "Home"
                };
                return(await Task.FromResult <IViewComponentResult>(View(viewModel)));
            }
            string userByIdentityReference = $"{fullLink}/IdRef/{loggedUserId}";
            var    user = WebApiService.GetApiResult <SchoolUser>(userByIdentityReference);

            ViewBag.Mode = user.SchoolUserCategory.Category;

            if (user.SchoolUserCategory.Category == "Teacher")
            {
                var viewModel = new NavbarVm()
                {
                    Action     = "Index",
                    Controller = "Home",
                    Area       = "Teacher"
                };
                return(await Task.FromResult <IViewComponentResult>(View(viewModel)));
            }
            if (user.SchoolUserCategory.Category == "Admin")
            {
                var viewModel = new NavbarVm()
                {
                    Action     = "Index",
                    Controller = "Home",
                    Area       = "Admin"
                };
                return(await Task.FromResult <IViewComponentResult>(View(viewModel)));
            }
            if (user.SchoolUserCategory.Category == "Student")
            {
                var viewModel = new NavbarVm()
                {
                    Action     = "IndexWithoutRedirect",
                    Controller = "Home"
                };
                return(await Task.FromResult <IViewComponentResult>(View(viewModel)));
            }
            else
            {
                var viewModel = new NavbarVm()
                {
                    Action     = "Index",
                    Controller = "Home"
                };
                return(await Task.FromResult <IViewComponentResult>(View(viewModel)));
            }
        }
        public async Task <IActionResult> Save(List <AssessmentFirstLangCreateTestDetailVm> vm)
        {
            var    questionsToAdd = new List <Question>();
            string fullLink       = $"{baseUri}/Assessment/{2}";
            var    langAssessment = WebApiService.GetApiResult <Assessment>(fullLink);

            try
            {
                foreach (var question in vm)
                {
                    if (question.IsToBeAdded)
                    {
                        var questionToAdd = WebApiService.GetApiResult <Question>($"{baseUri}/Question/{question.QuestionId}");
                        questionsToAdd.Add(questionToAdd);
                    }
                }

                var assessment = new AssessmentDetail()
                {
                    AssessmentTitle = $"{langAssessment.AssessmentTitle}, {DateTime.Now.Date}",
                    Questions       = questionsToAdd,
                    AssessmentId    = 2,
                    Assessment      = langAssessment
                };
                await WebApiService.PostCallApi <AssessmentDetail, AssessmentDetail>($"{baseUri}/assessmentdetail", assessment);

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return(RedirectToAction(nameof(Index)));
        }
        public MyListViewPage()
        {
            InitializeComponent();
            this.BindingContext = this;
            this.myWebApiService = new WebApiService();

            this.Cities = new List<string>
            {
                "宜蘭縣",
                "花蓮縣",
                "台東縣",
                "基隆市",
                "台北市",
                "新北市",
                "桃園市",
                "新竹市",
                "新竹縣",
                "苗栗縣",
                "雲林縣",
                "嘉義市",
                "嘉義縣",
                "台南市",
                "高雄市",
                "屏東縣",
                "澎湖縣",
                "金門縣",
                "台中市",
                "彰化縣",
                "南投縣"
            };
            //this.ddlCity.SelectedIndex = 0;

            this.listView.ItemTemplate =
                new DataTemplate(typeof(MyListViewCell));
        }
        public void Test(ITestContext context)
        {
            if (this.url.IsNullOrEmpty() || this.url == "/" || this.url == "~" || this.url == "~/")
            {
                this.url = this.FullyQualifiedApplicationPath(context);
            }

            if (this.action.IsNullOrEmpty())
            {
                throw new ApplicationException(Errors.UrlAndActionCannotBeEmpty);
            }

            this.service = new WebApiService {
                Timeout = this.timeout
            };

            try
            {
                var result = this.arguments == null
                                 ? this.service.Get <object>(this.url, this.action)
                                 : this.service.Get <object>(this.url, this.action, this.arguments);
            }
            catch (WebApiException ex)
            {
                Assert.Fails(Errors.FailedToAccessService, ex.Message);
            }
        }
        public async Task <IActionResult> Edit(EditUserViewModel editUserViewModel)
        {
            string fullLink       = $"{baseUri}/SchoolUser";
            string categoryLink   = $"{baseUri}/SchoolUserCategory";
            string classgroupLink = $"{baseUri}/ClassGroup";

            string userById   = fullLink + "/" + editUserViewModel.Id;
            var    schoolUser = WebApiService.GetApiResult <SchoolUser>(userById);

            schoolUser.FirstName = editUserViewModel.FirstName;
            schoolUser.LastName  = editUserViewModel.LastName;

            string categoryById   = categoryLink + "/" + editUserViewModel.SelectedSchoolUserCategoryId;
            string classgroupById = classgroupLink + "/" + editUserViewModel.SelectedClassGroupId;

            var schoolUserCategory = WebApiService.GetApiResult <SchoolUserCategory>(categoryById);
            var classGroup         = WebApiService.GetApiResult <ClassGroup>(classgroupById);

            schoolUser.ClassGroup           = classGroup;
            schoolUser.ClassGroupId         = classGroup.Id;
            schoolUser.SchoolUserCategory   = schoolUserCategory;
            schoolUser.SchoolUserCategoryId = schoolUserCategory.Id;

            await WebApiService.PutCallApi <SchoolUser, SchoolUser>(userById, schoolUser);

            return(new RedirectToActionResult("Index", "User", new { id = editUserViewModel.Id }));
        }
Example #8
0
        public static void Main(string[] args)
        {
            MongoService ms = new MongoService();
            WebApiService ws = new WebApiService();

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                _keepRunning = false;
            };

            ms.OnServiceStart += delegate(object msSender)
            {
                    Console.WriteLine("MongoDB has started.");
            };

            ws.OnServiceStart += delegate(object wsSender)
            {
                    Console.WriteLine("Panza service has started.");
                Console.WriteLine("\nHit control-c to exit.");
            };

            Task.Factory.StartNew(new Action(ms.Start));
            Thread.Sleep(500);
            Task.Factory.StartNew(new Action(ws.Start));

            while (_keepRunning)
            {
                Thread.Sleep(500);
            }

            ws.Stop();
            ms.Stop();
        }
        public IActionResult Edit(Guid id)
        {
            string fullLink       = $"{baseUri}/SchoolUser";
            string categoryLink   = $"{baseUri}/SchoolUserCategory";
            string classgroupLink = $"{baseUri}/ClassGroup";

            string userById   = fullLink + "/" + id;
            var    schoolUser = WebApiService.GetApiResult <SchoolUser>(userById);

            var classGroups          = new SelectList(WebApiService.GetApiResult <ICollection <ClassGroup> >(classgroupLink), nameof(ClassGroup.Id), nameof(ClassGroup.ClassGroupName), schoolUser.ClassGroup.Id.ToString());
            var schoolUserCategories = new SelectList(WebApiService.GetApiResult <ICollection <SchoolUserCategory> >(categoryLink), nameof(SchoolUserCategory.Id), nameof(SchoolUserCategory.Category), schoolUser.SchoolUserCategory.Id.ToString());

            EditUserViewModel editUserViewModel = new EditUserViewModel
            {
                Id                        = schoolUser.Id,
                FirstName                 = schoolUser.FirstName,
                LastName                  = schoolUser.LastName,
                ClassGroup                = schoolUser.ClassGroup,
                AvatarURL                 = schoolUser.AvatarURL,
                IdentityReference         = schoolUser.IdentityReference,
                SchoolUserCategory        = schoolUser.SchoolUserCategory,
                ClassGroupOptions         = classGroups,
                SchoolUserCategoryOptions = schoolUserCategories
            };

            return(View(editUserViewModel));
        }
 public void TestStartStop()
 {
     using (var service = new WebApiService("http://localhost:12351/RestService", GetMockSendingManager(), GetMockReceivingManager()))
     {
         RunSBComponentFullCycle(service);
     }
 }
Example #11
0
        static void Main(string[] args)
        {
            var warmupRep = new WarmUpRepository();

            warmupRep.WarmUp();

            Logger.Info("Cлужба запущена.");
#if DEBUG
            var service = new WebApiService();
            service.Start();
            Console.ReadLine();
            service.Stop();
#else
            HostFactory.Run(x =>
            {
                x.Service <WebApiService>(s =>
                {
                    s.ConstructUsing(name => new WebApiService());
                    s.WhenStarted(svc => svc.Start());
                    s.WhenStopped(svc => svc.Stop());
                });

                x.RunAsLocalSystem();
                x.SetDescription("Тестовый сервис для эмуляции нагрузки");
                x.SetDisplayName("Сервис GPS координат");
                x.SetServiceName("WebApiService");
            });
#endif
        }
Example #12
0
        public IActionResult Index()
        {
            string fullLink = $"{baseUri}/SchoolUser";

            string loggedUserid = _user.GetUserId(User);

            string userByIdentityReference = $"{fullLink}/IdRef/{loggedUserid}";
            var    user = WebApiService.GetApiResult <SchoolUser>(userByIdentityReference);

            string categoryLink        = $"{baseUri}/SchoolUserCategory";
            string getCategoryByIdLink = categoryLink + "/" + 1;
            var    userCategory        = WebApiService.GetApiResult <SchoolUserCategory>(getCategoryByIdLink);

            if (user.SchoolUserCategory.Category != userCategory.Category)
            {
                return(RedirectToAction("Index", "Home", new { Area = "" }));
            }

            string classgroupLink = $"{baseUri}/ClassGroup";

            ICollection <ClassGroup> classGroup  = WebApiService.GetApiResult <ICollection <ClassGroup> >(classgroupLink);
            ICollection <SchoolUser> schoolUsers = WebApiService.GetApiResult <ICollection <SchoolUser> >(fullLink);

            UserViewModel userViewModel = new UserViewModel
            {
                ClassGroups = classGroup,
                Users       = schoolUsers
            };

            return(View(userViewModel));
        }
        public IActionResult Index(Guid id)
        {
            string fullLink = $"{baseUri}/SchoolUser";

            string loggedUserid = _user.GetUserId(User);

            string categoryLink        = $"{baseUri}/SchoolUserCategory";
            string getCategoryByIdLink = categoryLink + "/" + 1;
            var    userCategory        = WebApiService.GetApiResult <SchoolUserCategory>(getCategoryByIdLink);

            string userByIdentityReference = $"{fullLink}/IdRef/{loggedUserid}";
            var    user = WebApiService.GetApiResult <SchoolUser>(userByIdentityReference);

            if (user.SchoolUserCategory.Category != userCategory.Category)
            {
                return(RedirectToAction("Index", "Home", new { Area = "" }));
            }

            string userById   = fullLink + "/" + id;
            var    schoolUser = WebApiService.GetApiResult <SchoolUser>(userById);

            UserDetailViewModel userDetailViewModel = new UserDetailViewModel
            {
                Id                 = schoolUser.Id,
                FirstName          = schoolUser.FirstName,
                LastName           = schoolUser.LastName,
                ClassGroup         = schoolUser.ClassGroup,
                AvatarURL          = schoolUser.AvatarURL,
                IdentityReference  = schoolUser.IdentityReference,
                SchoolUserCategory = schoolUser.SchoolUserCategory
            };

            return(View(userDetailViewModel));
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientAppId = context.Ticket.Properties.Dictionary["as:client_app_id"];

            if (string.IsNullOrEmpty(clientAppId))
            {
                return;
            }

            //We are generating a unique identifier for the refresh token
            var refreshTokenId = Guid.NewGuid().ToString("n");

            WebApiService service = new WebApiService();

            var client = service.FindClientByAppId(clientAppId);

            /*
             * We are reading the refresh token life time value from the Owin
             * context where we set this value once we validate the client,
             * this value will be used to determine how long the refresh token
             * will be valid for, this should be in minutes.
             */
            var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");

            var token = new RefreshToken()
            {
                RefreshTokenId = Core.Utility.Authentication.AuthHelper.GetHash(refreshTokenId),
                ClientAppId    = clientAppId,
                Name           = context.Ticket.Identity.Name ?? client.Name,
                IssuedUtc      = DateTime.UtcNow,
                ExpiresUtc     = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };


            /*
             * we are setting the IssuedUtc, and ExpiresUtc values for the ticket,
             * setting those properties will determine how long the refresh token will be valid for.
             */
            context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            // serialize the ticket content
            token.ProtectedTicket = context.SerializeTicket();

            // save record in RefreshTokens table

            /*
             * We are checking that the token which will be saved on the database is unique
             * for this User and the Client, if it not unique we’ll delete the existing one
             * and store new refresh token.
             */
            var result = await service.AddRefreshToken(token);

            if (result)
            {
                //send back the refresh token id
                context.SetToken(refreshTokenId);
            }
        }
 public async void Test_if_edit_return_edit_view()
 {
     WebApiService apiService = new WebApiService();
     var result = await playerController.Edit(1) as ViewResult;
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.Model);
     Assert.AreEqual("Edit", result.ViewName);
 }
        public async Task <IActionResult> Delete(int id)
        {
            string fullLink = $"{baseUri}/SchoolUserCategory";

            string schoolUserCategoryById = fullLink + "/" + id;
            await WebApiService.DeleteCallApi <SchoolUserCategory>(schoolUserCategoryById);

            return(RedirectToAction("Index", "UserCategory"));
        }
        public async Task <IActionResult> Delete(int id)
        {
            string fullLink = $"{baseUri}/ClassGroup";

            string classgroupById = fullLink + "/" + id;
            await WebApiService.DeleteCallApi <ClassGroup>(classgroupById);

            return(RedirectToAction("Index", "Classgroup"));
        }
Example #18
0
        private void btnGetAllApplication_Click(object sender, EventArgs e)
        {
            WebApiService was = new WebApiService();
            var apps = was.GetAllApplications();

            if (apps == null)
                MessageBox.Show("No record");
            else
                MessageBox.Show(apps.Count.ToString());
        }
        public WebApiServiceFixture()
        {
            // Arrange.
            SendManager = new Mock <ISendingManager>();
            RecManager  = new Mock <IReceivingManager>();

            var service = new WebApiService(BaseAddress, SendManager.Object, RecManager.Object);

            service.Start();
        }
Example #20
0
        public MyListViewPage(string title)
        {
            myStoreDataList = new List <FamilyStore>();
            myWebApiService = new WebApiService();
            Title           = title;

            SetUI();
            SetEvent();
            SetListView();
        }
 public async void Test_You_Can_Get_Players_from_view_model()
 {
     WebApiService apiService = new WebApiService();
     var player = await apiService.GetAsync<Player>("api/player/" + 1);
     PlayerModel pm = new PlayerModel();
     pm.Player = player;
     Assert.IsNotNull(pm.Player);
     Assert.AreEqual(player.Id, pm.Player.Id);
     Assert.AreEqual(player.Teams[0].Id, pm.Player.Teams[0].Id);
 }
 public async void Test_can_get_player_through_controller()
 {
     WebApiService apiService = new WebApiService();
     Player player = await apiService.GetAsync<Player>("api/player/" + 1);
     Assert.IsNotNull(player);
     var result = await playerController.Details(1) as ViewResult;
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.Model);
     Assert.AreEqual("Details", result.ViewName);
 }
Example #23
0
        public void CanGetAuthorization()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            var response = WebApiService.GetAuthorization("SmithCaesars", "1970/01/01", "4321");

            Assert.IsNotNull(response);
        }
Example #24
0
        public void CanGetVideoCampaignMemberData()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            var response = WebApiService.GetVideoCampaignMemberData("57020", 11);

            Assert.IsNotNull(response);
        }
Example #25
0
        public void CanGetUserSessionVideoData()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            var response = WebApiService.GetUserSessionVideoData("57020", 11);

            Assert.IsNotNull(response);
        }
Example #26
0
        public void Exercise_PostBattleResult()
        {
            // Arrange
            var filePath = @"C:\Users\rglos\AppData\Roaming\Wargaming.net\WorldOfTanks\battle_results\KJFF6OZRGYYDMOA=\24128337383252994.dat";

            // Act
            var actual = WebApiService.PostBattleResult(filePath).Result;

            // Assert
            Assert.Inconclusive();
        }
Example #27
0
        public void CanGetCampaignIntro()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            var response = WebApiService.GetCampaignIntro(11, 1);

            Assert.IsNotNull(response);
        }
Example #28
0
        public void CanGetCampaignSession()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            //This will not work without refactoring away from sessions
            var response = WebApiService.GetCampaignSession(CampaignSessionModel.Current);

            Assert.IsNotNull(response);
        }
Example #29
0
        public void CanGetAuthorizationByCchId()
        {
            if (!Debugger.IsAttached)
            {
                return;
            }

            var response = WebApiService.GetAuthorizationByCchId(11, 57020);

            Assert.IsNotNull(response);
            Assert.IsFalse(string.IsNullOrEmpty(response.AuthHash));
        }
        public IActionResult Index()
        {
            string fullLink = $"{baseUri}/SchoolUserCategory";

            var schoolUserCategories = WebApiService.GetApiResult <ICollection <SchoolUserCategory> >(fullLink);

            SchoolUserCategoryViewModel schoolUserCategoryViewModel = new SchoolUserCategoryViewModel
            {
                schoolUserCategories = schoolUserCategories
            };

            return(View(schoolUserCategoryViewModel));
        }
        public BackgroundRefreshController(
            ILogger mlogger,
            ITinyMessengerHub mmessenger,
            WebApiService mwebapi
            )
        {
            this.logger    = mlogger;
            this.messenger = mmessenger;
            this.webapi    = mwebapi;

            this.messenger.Subscribe <StopMessage>(Stop);
            logger.Trace("BackgroundRefreshController instance initialized");
        }
        public async Task <IActionResult> Add(SchoolUserCategoryDetailViewModel schoolUserCategoryDetailViewModel)
        {
            string fullLink = $"{baseUri}/SchoolUserCategory";

            SchoolUserCategory schoolUserCategory = new SchoolUserCategory
            {
                Category = schoolUserCategoryDetailViewModel.Category
            };

            await WebApiService.PostCallApi <SchoolUserCategory, SchoolUserCategory>(fullLink, schoolUserCategory);

            return(RedirectToAction("Index", "UserCategory"));
        }
        public IActionResult Index()
        {
            string fullLink = $"{baseUri}/Question/LangFirstGradeQuestions";

            var allFirstLangQuestions = WebApiService.GetApiResult <List <LangFirstGradeQuestionDto> >(fullLink);

            var viewModel = new LangFirstQuestionsIndexVm()
            {
                Questions = allFirstLangQuestions
            };

            return(View(viewModel));
        }
Example #34
0
        public IActionResult Create()
        {
            ViewBag.Mode = "Create";
            var categoryLink        = $"{baseUri}/QuestionCategory";
            var categories          = WebApiService.GetApiResult <List <QuestionCategory> >(categoryLink);
            var availableCategories = categories.Where(c => c.CategoryQuestion == QuestionCategories.LangQuestionSecondGrade || c.CategoryQuestion == QuestionCategories.LangQuestionThirdGrade);
            var viewModel           = new LangQuestionsDetailVm()
            {
                AvailableCategories = availableCategories
            };

            return(View("Detail", viewModel));
        }
        public IActionResult Add()
        {
            string fullLink = $"{baseUri}/YearGrade";

            var yearGrades = new SelectList(WebApiService.GetApiResult <ICollection <YearGrade> >(fullLink), nameof(YearGrade.Id), nameof(YearGrade.Grade));

            ClassGroupDetailViewModel classGroupDetailViewModel = new ClassGroupDetailViewModel
            {
                YearGradeOptions = yearGrades
            };

            return(View(classGroupDetailViewModel));
        }
        public IActionResult Index()
        {
            string fullLink = $"{baseUri}/ClassGroup";

            var classGroups = WebApiService.GetApiResult <ICollection <ClassGroup> >(fullLink);

            ClassGroupViewModel classGroupViewModel = new ClassGroupViewModel
            {
                classGroups = classGroups
            };

            return(View(classGroupViewModel));
        }
Example #37
0
 public static void LoadStationList()
 {
     try
     {
         var data = WebApiService.GetDataFromWeb("api/Stations");
         ListOfStations = JsonConvert.DeserializeObject <ObservableCollection <Station> >(data);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
 public async void Test_Can_Create_and_delete_player_Through_controller()
 {
     var result = await playerController.Create(player);
     WebApiService apiService = new WebApiService();
     var players = await apiService.GetAsync<List<Player>>("api/player/");
     var createdePlayer = players.FirstOrDefault(a => a.Name == player.Name);
     Assert.IsNotNull(player);
     Assert.IsNotNull(players);
     Assert.IsNotNull(createdePlayer);
     var newPlayer = await apiService.GetAsync<Player>("api/player/" + createdePlayer.Id);
     Assert.AreEqual(newPlayer.Name, createdePlayer.Name);
     Assert.AreEqual(newPlayer.Id, createdePlayer.Id);
     await playerController.DeleteConfirmed(newPlayer.Id);
 }
Example #39
0
        private void btnPushApplication_Click(object sender, EventArgs e)
        {
            try
            {
                Data.Application p = new Data.Application();
                p.Applicant.FullName = "Ahmad " + name++.ToString();

                WebApiService was = new WebApiService();
                was.AddApplication(p);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 public void SetUp()
 {
     gateway = new WebApiService();
     TournamentViewModel = new TournamentViewModel();
    
 }
 public void SetUp()
 {
     genre = new Genre() {Name = "TestGenre"};
     apiService = new WebApiService();
     genreController = new GenreController();
 }
 public void TearDown()
 {
     genre = null;
     apiService = null;
     genreController = null;
 }
        public async void Test_if_create_return_view()

        {
            WebApiService apiService = new WebApiService();
            var result = playerController.Create() as ViewResult;
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Model);
            Assert.AreEqual("Create", result.ViewName);
        }
        public MyListViewPage(string title)
        {
            myWebApiService = new WebApiService();

            // 搜尋店鋪 Button 按鈕

            searchButton = new Button { Text = "Search" };

            // 建立縣市 Picker 下拉選單
            cityPicker = new Picker
            {
                Title = "縣市選單",
                VerticalOptions = LayoutOptions.CenterAndExpand
            };

            // 初始化選項
            foreach (string cityName in nameToCity.Keys)
            {
                cityPicker.Items.Add(cityName);
            }

            // 預設選取第一個項目
            cityPicker.SelectedIndex = 0;

            areaPicker = new Picker
            {
                Title = "鄉鎮市區選單",
                VerticalOptions = LayoutOptions.CenterAndExpand
            };

            foreach (var item in defaultAreaList)
            {
                areaPicker.Items.Add(item.town);
            }

            areaPicker.SelectedIndex = 4;

            // 註冊 cityPicker SelectedIndexChanged 事件
            cityPicker.SelectedIndexChanged += async (sender, args) =>
            {
                if (cityPicker.SelectedIndex != -1)
                {
                    // 將舊有的鄉鎮區項目刪除
                    // Error : 因為沒辦法全部刪除,會顯示 Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index,所以留下一個,加新項目後在刪掉
                    int count = areaPicker.Items.Count - 1;

                    for (int i = 0; i < count; i++)
                    {
                        areaPicker.Items.RemoveAt(0);
                    }

                    // 透過 api 拿到對應縣市的鄉鎮區項目
                    var areaResult = await myWebApiService.GetAreaDataAsync(cityPicker.Items[cityPicker.SelectedIndex]);

                    // 將 Json 轉為 List<AreaData>
                    var myAreaDataList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AreaData>>(areaResult);

                    // 替鄉鎮區下拉選單,增加對應縣市的新項目
                    foreach (var item in myAreaDataList)
                    {
                        areaPicker.Items.Add(item.town);
                    }

                    // 將之前留下來最後一個舊項目刪除
                    areaPicker.Items.RemoveAt(0);

                    // 預設選取第一個項目
                    areaPicker.SelectedIndex = 0;
                }
            };

            // 註冊 areaPicker SelectedIndexChanged 事件
            areaPicker.SelectedIndexChanged += (sender, args) =>
            {
                // log 記錄
                if (areaPicker.SelectedIndex != -1)
                {
                    Debug.WriteLine("AreaName is " + areaPicker.Items[areaPicker.SelectedIndex]);
                }
            };

            Title = title;

            var listView = new ListView
            {
                IsPullToRefreshEnabled = true,
                RowHeight = 80,
                ItemsSource = new List<StoreData>()
                {
                    new StoreData {Name = "全家大安店", Address = "台北市大安區大安路一段20號", Tel = "02-27117896"},
                    new StoreData {Name = "全家仁慈店", Address = "台北市大安區仁愛路四段48巷6號", Tel = "02-27089002"},
                    new StoreData {Name = "全家明曜店", Address = "台北市大安區仁愛路四段151巷34號", Tel = "02-27780326"},
                    new StoreData {Name = "全家國泰店", Address = "台北市大安區仁愛路四段266巷15弄10號", Tel = "02-27542056"},
                    new StoreData {Name = "全家忠愛店", Address = "台北市大安區仁愛路四段27巷43號", Tel = "02-27314580"},
                },
                ItemTemplate = new DataTemplate(typeof(MyListViewCell))
            };

            listView.ItemTapped += (sender, e) =>
            {
                var baseUrl = "https://www.google.com.tw/maps/place/";
                var storeData = e.Item as StoreData;

                if (storeData != null)
                    Device.OpenUri(new Uri($"{baseUrl}{storeData.Address}"));

                ((ListView)sender).SelectedItem = null;
            };

            // 註冊 searchButton Clicked 事件
            searchButton.Clicked += async (sender, e) =>
            {
                // 透過 api 拿到對應區域的全家店鋪資料
                var resultData = await myWebApiService.GetFamilyStoreDataAsync(cityPicker.Items[cityPicker.SelectedIndex], areaPicker.Items[areaPicker.SelectedIndex]);

                // 將 Json 轉為 List<FamilyStore>
                var familyStoreList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<FamilyStore>>(resultData);

                // 將 List<FamilyStore> 轉為 List<StoreData>
                var myStoreDataList = familyStoreList.Select(p => new StoreData()
                {
                    Address = p.addr,
                    Name = p.NAME,
                    Tel = p.TEL
                }).ToList();

                // 更換店鋪資訊
                listView.ItemsSource = myStoreDataList;
                Debug.WriteLine(myStoreDataList.Count);
            };

            Padding = new Thickness(0, 20, 0, 0);
            Content = new StackLayout
            {
                Orientation = StackOrientation.Vertical,
                Children =
                {
                    cityPicker,
                    areaPicker,
                    searchButton,
                    new Label
                    {
                        HorizontalTextAlignment= TextAlignment.Center,
                        Text = Title,
                        FontSize = 30
                    },
                    listView
                }
            };
        }
        public async void SetUp()
        {
            apiService = new WebApiService();
            matchController = new MatchController();

        }
 public void TearDown()
 {
     apiService = null;
     matchController = null;
     match = null;
 }
        public async void Test_if_a_team_can_be_added_to_a_player()
        {
            Player player1 = new Player() {Name = "TestPlayer1"};
            Player player2 = new Player() {Name = "Testplayer2"};
            WebApiService apiService = new WebApiService();
            await playerController.Create(player1);
            await playerController.Create(player2);
            var players = await apiService.GetAsync<List<Player>>("api/player/");
            var player1WithOutTeam = players.FirstOrDefault(a => a.Name == player1.Name);
            var player2WithOutTeam = players.FirstOrDefault(a => a.Name == player2.Name);
            List<Player> testList1 = new List<Player>() { player1WithOutTeam };
            List<Player> testList2 = new List<Player>() { player2WithOutTeam };
            Team teamOne = new Team() { Name = "TestTeam1", Draw = 0, Loss = 0, Win = 0, Players = testList1 };
            Team teamTwo = new Team() { Name = "TestTeam2", Draw = 0, Loss = 0, Win = 0, Players = testList2 };
            await apiService.PostAsync("api/team/", teamOne);
            await apiService.PostAsync("api/team/", teamTwo);
            var playerlist = await apiService.GetAsync<List<Player>>("api/player/");
            var createdePlayer1 = playerlist.FirstOrDefault(a => a.Name == player1.Name);
            var createdePlayer2 = playerlist.FirstOrDefault(a => a.Name == player2.Name);

            Assert.IsNotNull(createdePlayer1);
            Assert.IsNotNull(createdePlayer2);
            int teamSizeBefore = createdePlayer1.Teams.Count;
            int teamId1ToRemove = createdePlayer1.Teams[0].Id;
            int teamId2ToRemove = createdePlayer2.Teams[0].Id;
            Team teamToAdd = await apiService.GetAsync<Team>("api/team/" + createdePlayer2.Teams[0].Id);

            await playerController.Add(teamToAdd.Id, createdePlayer1.Id);
            Player playerAfter = await apiService.GetAsync<Player>("api/player/" + createdePlayer1.Id);
            int teamSizeAfter = playerAfter.Teams.Count;
            Assert.AreNotEqual(teamSizeAfter, teamSizeBefore);
            await apiService.DeleteAsync<Team>("api/team/" + teamId1ToRemove);
            await apiService.DeleteAsync<Team>("api/team/" + teamId2ToRemove);
            await playerController.DeleteConfirmed(createdePlayer1.Id);
            await playerController.DeleteConfirmed(createdePlayer2.Id);
        }
 public async void Test_if_a_team_can_be_removed_from_a_player()
 {
     WebApiService apiService = new WebApiService();
     await playerController.Create(player);
     var players = await apiService.GetAsync<List<Player>>("api/player/");
     var playerWithOutTeam = players.FirstOrDefault(a => a.Name == player.Name);
     List<Player> testList = new List<Player>() { playerWithOutTeam };
     Team team = new Team() { Name = "TestTeam", Draw = 0, Loss = 0, Win = 0, Players = testList };
     await apiService.PostAsync("api/team/", team);
     Assert.IsNotNull(player);
     Assert.IsNotNull(players);
     var playerlist = await apiService.GetAsync<List<Player>>("api/player/");
     var createdePlayer = playerlist.FirstOrDefault(a => a.Name == player.Name);
     Assert.IsNotNull(createdePlayer);
     int teamSizeBefore = createdePlayer.Teams.Count;
     int teamIdToRemove = createdePlayer.Teams[0].Id;
     await playerController.Remove(createdePlayer.Teams[0].Id, createdePlayer.Id);
     Player playerAfter = await apiService.GetAsync<Player>("api/player/" + createdePlayer.Id);
     int teamSizeAfter = playerAfter.Teams.Count;
     Assert.AreNotEqual(teamSizeAfter, teamSizeBefore);
     await apiService.DeleteAsync<Team>("api/team/" + teamIdToRemove);
     await playerController.DeleteConfirmed(createdePlayer.Id);
 }
 public async void Test_if_a_player_with_a_team_can_be_edited()
 {
     var result = await playerController.Create(player);
     string newName = "changedName";
     WebApiService apiService = new WebApiService();
     var players = await apiService.GetAsync<List<Player>>("api/player/");
     var createdePlayer = players.FirstOrDefault(a => a.Name == player.Name);
     Assert.IsNotNull(player);
     Assert.IsNotNull(players);
     Assert.IsNotNull(createdePlayer);
     var testPlayer = await apiService.GetAsync<Player>("api/player/" + createdePlayer.Id);
     testPlayer.Name = newName;
     string[] teamId = new string[] { "1" };
     await playerController.Edit(testPlayer, teamId);
     var changedPlayer = await apiService.GetAsync<Player>("api/player/" + testPlayer.Id);
     Assert.AreEqual(newName, changedPlayer.Name);
     Assert.AreEqual(testPlayer.Id, changedPlayer.Id);
     Assert.AreEqual(testPlayer.Teams[0].Id, changedPlayer.Teams[0].Id);
     await playerController.DeleteConfirmed(testPlayer.Id);
 }
        public async void Test_if_edit_with_missing_data_returns_edit_view()
        {
            string newName = "changedName";
            WebApiService apiService = new WebApiService();
            Assert.IsNotNull(player);
            string[] teamId = null;
            var result = await playerController.Edit(player, teamId) as ViewResult;
            Assert.AreEqual("Edit", result.ViewName);

        }