Пример #1
0
        public ActionResult Trades(bool?isAuthed)
        {
            ViewBag.Success = false;

            if (isAuthed.HasValue && isAuthed.Value && !String.IsNullOrEmpty(AccessToken))
            {
                try
                {
                    var wrapper = new ApiWrapper("nfl");
                    var leagues = wrapper.GetLeagues(AccessToken, TokenSecret);

                    foreach (var league in leagues.Item1.Leagues)
                    {
                        var key      = league.LeagueKey;
                        var settings = wrapper.GetLeagueSettings(AccessToken, TokenSecret, key);
                        var trans    = wrapper.GetTransactions(AccessToken, TokenSecret, key);

                        SaveSettings(settings.Item1, leagues.Item2, settings.Item2, trans);

                        ViewBag.Success = true;
                    }
                }
                catch
                {
                    ViewBag.ErrorMessage = "Something went awry :( ... try again?";
                }
            }

            return(View());
        }
Пример #2
0
        public void ApiWrapper_ReturnAllProjectWithCoverage_ExepctUnitTests()
        {
            var dataSource = new BuildDetails
            {
                information = new[]
                {
                    new Information
                    {
                        coverageData = new Coveragedata
                        {
                            modules = new[]
                            {
                                new Module {
                                    blocksCovered = 1, blocksNotCovered = 1, name = "newBlock"
                                },
                                new Module {
                                    blocksCovered = 1, blocksNotCovered = 1, name = "newBlockUnitTest"
                                },
                            }
                        }
                    }
                }
            };

            var result = ApiWrapper.ComputeCoverage(dataSource);


            Assert.AreEqual(1, result.Length);
        }
Пример #3
0
        public override async Task InvokeAsync(MiddlewareContext context)
        {
            var filters = context.Action.GetCustomAttributes(typeof(NetRpcFilterAttribute), true);

            foreach (NetRpcFilterAttribute f in filters)
            {
                await f.InvokeAsync(context);
            }
            NetRpcContext.ThreadHeader.CopyFrom(context.Header);

            dynamic ret;

            try
            {
                // ReSharper disable once PossibleNullReferenceException
                ret = context.Action.Invoke(context.Target, context.Args);
            }
            catch (TargetInvocationException e)
            {
                if (e.InnerException != null)
                {
                    var edi = ExceptionDispatchInfo.Capture(e.InnerException);
                    edi.Throw();
                }
                throw;
            }

            var isGenericType = context.Action.ReturnType.IsGenericType;

            context.Result = await ApiWrapper.GetTaskResult(ret, isGenericType);
        }
Пример #4
0
        private async Task <(HttpDataObj dataObj, ProxyStream stream)> GetHttpDataObjAndStream(ActionInfo ai)
        {
            //dataObjType
            var method      = ApiWrapper.GetMethodInfo(ai, _contracts, _serviceProvider);
            var dataObjType = method.contractMethod.MergeArgType.Type;

            if (_context.Request.ContentType != null)
            {
                //multipart/form-data
                if (_context.Request.ContentType.StartsWith("multipart/form-data"))
                {
                    return(await GetFromFormDataAsync(dataObjType));
                }

                //application/json
                if (_context.Request.ContentType.StartsWith("application/json"))
                {
                    string body;
                    using (var sr = new StreamReader(_context.Request.Body, Encoding.UTF8))
                        body = await sr.ReadToEndAsync();

                    var dataObj = Helper.ToHttpDataObj(body, dataObjType);
                    return(dataObj, null);
                }

                throw new HttpFailedException($"ContentType:'{_context.Request.ContentType}' is not supported.");
            }

            //_context.Request.ContentType == null
            return(null, null);
        }
Пример #5
0
        static void Main(string[] args)
        {
            // Initialize the interfaces
            using (var myhelloworldApi = new ApiWrapper <helloworldApi>())
            {
                ClientApiOptions clientApiOptions = new ClientApiOptions(); //fill this object to override default xcApi parameters

                myhelloworldApi.Api.HelloWorld_Component.HelloResponse_StateMachine.InstanceUpdated += instance => Console.WriteLine(instance.PublicMember.Text);

                if (myhelloworldApi.Init(myhelloworldApi.Api.DefaultXcApiFileName, clientApiOptions))
                {
                    var context = myhelloworldApi.Api.HelloWorld_Component.GetEntryPoint().Context;

                    var name = GetName();
                    while (!string.IsNullOrWhiteSpace(name))
                    {
                        myhelloworldApi.Api.HelloWorld_Component.HelloWorldManager_StateMachine.EntryPoint_State.SayHello(context, new SayHello {
                            Name = name
                        });
                        name = GetName();
                    }
                }
                else
                {
                    AnalyseReport(myhelloworldApi.Report);
                }
            }
        }
Пример #6
0
        private async void Load()
        {
            _loading = true;
            var data = await LoadFromDisk();

            Log.Info($"Loaded from disk: {data}");
            if (data?.IsStale ?? true)
            {
                Log.Info("Cached data was not found or stale. Fetching latest...");
                data = await ApiWrapper.GetAvailableDecks();

                if (data == null)
                {
                    Log.Warn("No data. Can retry in 30 minutes.");
                    data = new DecksData
                    {
                        ClientTimeStamp = DateTime.Now.Subtract(TimeSpan.FromHours(23.5)),
                    };
                }
                Log.Info("Writing hsreplay_decks.cache to disk...");
                await WriteToDisk(data);
            }
            _data = data;
            Log.Info($"Complete: {data}");
            OnLoaded?.Invoke();
            _loading = false;
        }
Пример #7
0
    private async void Start()
    {
        try
        {
            var response = await ApiWrapper.GamePrices();

            var propertyPricesArray = (JArray)response["properties"];
            var propertyPrices      = new List <int>(propertyPricesArray.Count);
            foreach (var price in propertyPricesArray)
            {
                var p = (int)price["price"];
                propertyPrices.Add(p);
            }

            var taxPricesArray = (JArray)response["taxes"];
            var taxPrices      = new List <int>(taxPricesArray.Count);
            foreach (var price in taxPricesArray)
            {
                var p = (int)price["price"];
                taxPrices.Add(p);
            }

            LoadPrices(propertyPrices, taxPrices);
        }
        catch (Exception e)
        {
            Debug.Log(e); // TODO: Show error to player
        }
    }
Пример #8
0
        // ##########################################################
        // ################# Internal functions #####################
        // ##########################################################

        /// <summary>
        /// Thread safe function for the thread DkimSignerAvailable
        /// </summary>
        private async void CheckDkimSignerAvailable()
        {
            cbxPrereleases.Enabled = false;

            await Task.Run(() => versionAvailable = ApiWrapper.GetAllRelease(cbxPrereleases.Checked, new Version("2.0.0")));

            cbxPrereleases.Enabled = true;

            cbVersionWeb.Items.Clear();
            if (versionAvailable != null)
            {
                if (versionAvailable.Count > 0)
                {
                    foreach (Release oVersionAvailable in versionAvailable)
                    {
                        cbVersionWeb.Items.Add(oVersionAvailable.TagName);
                    }

                    cbVersionWeb.Enabled = true;
                }
                else
                {
                    MessageBox.Show(this, "No release information from the Web available.", "Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbVersionWeb.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show(this, "Could not obtain release information from the Web. Check your Internet connection or retry later.", "Error fetching version", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cbVersionWeb.Enabled = false;
            }

            cbxPrereleases.Enabled = true;
        }
Пример #9
0
        //public ActionResult Players(FilterViewModel filter = null)
        //{
        //	var playersData = new PlayersGrid(GetPlayerData(filter));

        //	return PartialView("_Players", playersData);
        //}

        //public DataTablesResult<PlayerAnnualViewModel> GetPlayers(DataTablesParam param, FilterViewModel filter)
        //{
        //	if(filter != null && filter.SelectedYear != null)
        //	{
        //		PlayerFilter = filter;
        //	}

        //	var players = GetPlayerData(filter ?? PlayerFilter);
        //	return DataTablesResult.Create(players, param);
        //}

        private IQueryable <PlayerAnnualViewModel> GetPlayerData(FilterViewModel filter)
        {
            if (PlayerFilter != null && (filter == null || filter.SelectedYear == null))
            {
                filter = PlayerFilter;
            }
            else
            {
                PlayerFilter = filter;
            }

            if (filter == null || filter.SelectedYear == null)
            {
                return(new List <PlayerAnnualViewModel>().AsQueryable());
            }

            var api          = new ApiWrapper("nfl");
            var players      = api.GetPlayersByPosition(filter.SelectedPosition.Key).Take(25);
            var categories   = api.GetStatCategories();
            var playersModel = new List <PlayerAnnualViewModel>();

            foreach (var player in players)
            {
                var playerModel = new PlayerAnnualViewModel
                {
                    Name     = player.Name.Full,
                    Position = player.EligiblePositions.FirstOrDefault().Position,
                    Team     = player.EditorialTeamAbbr
                };

                var stats = api.GetStatsByPlayer(player.PlayerId, filter.SelectedYear);

                foreach (var stat in stats)
                {
                    var props = playerModel.GetType().GetProperties();
                    foreach (var prop in props)
                    {
                        if (prop.CustomAttributes.Any(p => p.AttributeType == typeof(PlayerMappingAttribute)))
                        {
                            var attr   = prop.GetCustomAttributes(typeof(PlayerMappingAttribute), false).FirstOrDefault();
                            var statId = ((PlayerMappingAttribute)attr).YahooStatId;

                            if (stat.StatDetail.StatId == statId)
                            {
                                var statValue = Convert.ChangeType(stat.StatDetail.Value, prop.PropertyType);
                                prop.SetValue(playerModel, statValue);
                            }
                        }
                    }
                }

                if (playerModel.GamesPlayed > 0)
                {
                    playersModel.Add(playerModel);
                }
            }

            return(playersModel.AsQueryable());
        }
Пример #10
0
    private void Awake()
    {
        var canvasBtn = canvas.GetComponent <Button>();

        canvasBtn.onClick.AddListener(() =>
        {
            gameObject.SetActive(false);
        });

        var seatsTxt  = seats.GetComponent <TextInput>();
        var createBtn = create.GetComponent <Button>();

        createBtn.onClick.AddListener(async() =>
        {
            seatsTxt.Highlight = false;

            if (int.TryParse(seatsTxt.Value, out var seatsNumber) && seatsNumber > 0)
            {
                try
                {
                    var response = await ApiWrapper.GameNew(seatsNumber);
                    Game.Join(response);
                }
                catch (BadResponseException e)
                {
                    var response = e.Response;

                    if (response["error"] != null)
                    {
                        Debug.Log((string)response["error"]["message"]);
                    }
                    else if (response["errors"] != null)
                    {
                        var errors = (JArray)response["errors"];
                        foreach (var err in errors.Children())
                        {
                            if ((string)err["msg"] != "Invalid value")
                            {
                                continue;
                            }

                            if ((string)err["param"] == "seats")
                            {
                                seatsTxt.Highlight = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e); // TODO: Show error to player
                }
            }
            else
            {
                seatsTxt.Highlight = true;
            }
        });
    }
Пример #11
0
        public static IDataService CreateDataService()
        {
            var api    = new ApiWrapper();
            var parser = new XmlApiResponseParser();
            var ds     = new DataService(api, parser);

            return(ds);
        }
Пример #12
0
            /// <summary>
            /// Reads the movie details for based on a movie id.
            /// </summary>
            /// <param name="movieId">The id of the movie that's details should get queried.</param>
            /// <returns>A detailed set of information for the queried movie.</returns>
            public static MovieDetails GetMovieDetails(int movieId)
            {
                // Queries Yify for movie details
                MovieDetailsData temp = ApiWrapper.GetMovieDetails(movieId).Data;

                // Maps the DTO to the business model
                return(new MovieDetails(temp));
            }
        public TasksFixture()
        {
            LightUnitTest.PrepareUnitTestMode("runsettings", WorkBench.EnvironmentName);
            var fullAccessToken = LightUnitTest.GetAuthorization("BackofficeAdmin");

            api = new ApiWrapper("TASKS", fullAccessToken);
            api.Get("reseed/Unit");
        }
Пример #14
0
        private static void RunPetStore(ApiWrapper <RestConsumerApiApi> myRestConsumerApi)
        {
            var petName = "Juan";

            var addOperationDone = new ManualResetEvent(false);
            var getOperationDone = new ManualResetEvent(false);

            myRestConsumerApi.Api.SwaggerPetstore_Component.AddPetOperation_StateMachine.InstanceUpdated +=
                instance =>
            {
                Console.WriteLine(string.Format("AddPetOperation current state: {0}", instance.StateName));

                if (instance.StateCode ==
                    (int)AddPetOperation_StateMachine.AddPetOperationStateEnum.SuccessResponseReceived
                    ||
                    instance.StateCode ==
                    (int)AddPetOperation_StateMachine.AddPetOperationStateEnum.ErrorResponseReceived)
                {
                    addOperationDone.Set();
                }
            };

            myRestConsumerApi.Api.SwaggerPetstore_Component.GetPetByIdOperation_StateMachine.InstanceUpdated +=
                instance =>
            {
                if (instance.StateCode ==
                    (int)GetPetByIdOperation_StateMachine.GetPetByIdOperationStateEnum.SuccessResponseReceived)
                {
                    Console.WriteLine(string.Format("Found pet called {0}",
                                                    instance.PublicMember.OperationResult.Name));
                    getOperationDone.Set();
                }
                else if (instance.StateCode ==
                         (int)GetPetByIdOperation_StateMachine.GetPetByIdOperationStateEnum.ErrorResponseReceived)
                {
                    Console.WriteLine(string.Format("An error occured: {0}", instance.PublicMember.Message));
                    getOperationDone.Set();
                }
            };

            myRestConsumerApi.Api.SwaggerPetstore_Component.SwaggerPetstore_StateMachine.SendEvent(new AddPet()
            {
                body = new Pet(petName, new List <string>(), 1001)
            });

            Console.WriteLine(string.Format("Adding a new pet called {0}..", petName));
            addOperationDone.WaitOne();
            Console.WriteLine("Add operation done");

            Console.WriteLine("Asking for info about a pet..");
            myRestConsumerApi.Api.SwaggerPetstore_Component.SwaggerPetstore_StateMachine.SendEvent(new GetPetById()
            {
                petId = 1001
            });

            getOperationDone.WaitOne();
            Console.ReadLine();
        }
Пример #15
0
        public static void Main(string[] args)
        {
            var musicApiWrapper         = new ApiWrapper();
            IEnumerable <IAlbum> albums = musicApiWrapper.FindAlbumsByArtists("Jack Johnson");

            foreach (IAlbum album in albums)
            {
                Console.WriteLine($"Genre: {album.Genre}; Name: {album.Name}; Year: {album.Date.Year}");
            }
        }
    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        var osrss = await ApiWrapper.GETOsrs();

        foreach (var item in osrss.Values)
        {
            Osrss.Add(item);
        }
        _tempList = Osrss;
    }
Пример #17
0
        public AllianceView(ApiWrapper api)
        {
            vm          = new AllianceViewModel(api);
            DataContext = vm;

            AddAlly    = new SimpleCommand(AddAllyCode);
            RemoveAlly = new SimpleCommand(RemoveAllyCode);

            InitializeComponent();
        }
Пример #18
0
 public static void Init(string appId, string appKey, Auth.Callback callback)
 {
     if (appId == null || appKey == null || callback == null)
     {
         throw new InvalidOperationException("publicKey == null || appId == null || callback == null");
     }
     ApiWrapper apiWrapper = new ApiWrapper();
     ApiWrapper.InitCallback initCallback = new MyInitCallback(callback);
     apiWrapper.Init(appId, appKey, initCallback);
 }
Пример #19
0
 public async void OnClick()
 {
     try
     {
         await ApiWrapper.PlayerEndTurn();
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
        public async Task <Tuple <MissionAttachmentDTO, string> > Upload(int id, byte[] ImageData)
        {
            if (!Helper.IsInternetAvailable())
            {
                return(null);
            }

            var result = await ApiWrapper <MissionAttachmentDTO> .UploadImage(Api.Missions.Upload.Replace("{id}", id.ToString()), ImageData);

            return(result);
        }
        /// <summary>
        /// Creates a new mission (deploys a new rover)
        /// </summary>
        /// <param name="missionDTO"></param>
        /// <returns></returns>
        public async Task <Tuple <MissionDTO, string> > Create(MissionRequestDTO missionRequestDTO)
        {
            if (!Helper.IsInternetAvailable())
            {
                return(null);
            }

            var result = await ApiWrapper <MissionDTO> .Post(Api.Missions.Create, missionRequestDTO);

            return(result);
        }
        /// <summary>
        /// Fetches all the missions performed
        /// </summary>
        /// <returns></returns>
        public async Task <Tuple <IEnumerable <MissionDTO>, string> > All()
        {
            if (!Helper.IsInternetAvailable())
            {
                return(null);
            }

            var result = await ApiWrapper <IEnumerable <MissionDTO> > .Get(Api.Missions.All);

            return(result);
        }
Пример #23
0
 private async void GetFacts()
 {
     try
     {
         allFacts = await ApiWrapper.RetrieveFacts();
     }
     catch (Exception)
     {
         throw;
     }
 }
        /// <summary>
        /// Fetches one mission from the server
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <Tuple <MissionDTO, string> > Get(int id)
        {
            if (!Helper.IsInternetAvailable())
            {
                return(null);
            }

            var result = await ApiWrapper <MissionDTO> .Get(Api.Missions.Get.Replace("{id}", id.ToString()));

            return(result);
        }
        /// <summary>
        /// Updates a mission (moves an existing rover)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="missionRequestDTO"></param>
        /// <returns></returns>
        public async Task <Tuple <MissionDTO, string> > Update(int id, MissionRequestDTO missionRequestDTO)
        {
            if (!Helper.IsInternetAvailable())
            {
                return(null);
            }

            var result = await ApiWrapper <MissionDTO> .Put(Api.Missions.Move.Replace("{id}", id.ToString()), missionRequestDTO);

            return(result);
        }
Пример #26
0
 public async void OnClick()
 {
     try
     {
         await ApiWrapper.PlayerRollDice();
     }
     catch (Exception e)
     {
         Debug.Log(e); // TODO: Show error to player
     }
 }
Пример #27
0
        /// <summary>
        /// Called whenever a game ends. Detects if the game was played with a different deck than before, and uploads the results accordingly.
        /// </summary>
        internal void OnGameEnd()
        {
            try
            {
                // Try to get played deck
                Deck   deck     = Deck.FromContext();
                string deckCode = deck.GenerateDeckCode();

                // if deckcode equals the previously played one, then return

                /*
                 * if (deckCode.Equals(Config.Instance.LastDeckcodeUploaded))
                 * {
                 *  return;
                 * }*/

                var    stats        = Hearthstone_Deck_Tracker.Core.Game.CurrentGameStats;
                string opponentDeck = "";

                try
                {
                    opponentDeck = Deck.FromOpponent(deck.Format).GenerateDeckCode();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }

                var uploadTask = Task.Run <bool>(async() =>
                                                 await ApiWrapper.UploadDeckWithResult(
                                                     deck.Name,
                                                     deckCode,
                                                     stats.OpponentName,
                                                     opponentDeck,
                                                     stats.EndTime.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz"),
                                                     stats.Result
                                                     )
                                                 );
                uploadTask.Wait();

                // and remember the uploaded deck, if the upload was successfull
                if (uploadTask.Result)
                {
                    Config.Instance.LastDeckcodeUploaded = deckCode;
                    Config.Save();
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                return;
            }
        }
Пример #28
0
        public FixerViewModel()
        {
            TeamWorkClient.Created += (s, e) =>
            {
                api = new ApiWrapper(TeamWorkClient.Current);
            };
#if DEBUG

            // TeamWorkClient.Make(Settings.Default.ApiKey);
            // DoCommand.Execute(null);
#endif
        }
Пример #29
0
    private async void Start()
    {
        try
        {
            var response = await ApiWrapper.GamePrices();

            var propertyPricesArray = (JArray)response["properties"];
            propertiesList = new List <PropertyCard>(propertyPricesArray.Count);
            stationsList   = new List <StationCard>(propertyPricesArray.Count);
            utilitiesList  = new List <UtilityCard>(propertyPricesArray.Count);
            foreach (var property in propertyPricesArray)
            {
                var propertyName = property["name"].ToString();
                var color        = property["color"]?.ToString();
                var location     = (int)property["location"];
                var rents        = ((JArray)property["rents"]).Select(rent => (int)rent).ToArray();
                var mortgage     = (int)property["mortgage"];

                var type = (int)property["type"];
                switch (type)
                {
                case 0:
                {
                    var houseCosts = (JArray)response["houses"];

                    var houseCost = (int)houseCosts[location / 10];

                    var card = new PropertyCard(propertyName, color, location, rents, houseCost, mortgage);
                    propertiesList.Add(card);
                    break;
                }

                case 1:
                {
                    var card = new StationCard(propertyName, location, rents, mortgage);
                    stationsList.Add(card);
                    break;
                }

                default:
                {
                    var card = new UtilityCard(propertyName, location, rents, mortgage);
                    utilitiesList.Add(card);
                    break;
                }
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(e); // TODO: Show error to player
        }
    }
Пример #30
0
        public static void UpdateBanCache(ApiWrapper wrapper)
        {
            var bannedList = wrapper.ConfigStore.GetConfigValue <string>("GlobalUserBanList")?.Split(";");

            if (bannedList == null)
            {
                GloballyBannedUsers = new List <string>();
            }
            else
            {
                GloballyBannedUsers = bannedList.ToList();
            }
        }
Пример #31
0
    public static async void Logout()
    {
        try
        {
            await ApiWrapper.AuthLogout();

            Instance.OnNext(null);
        }
        catch (Exception e)
        {
            Debug.Log(e); // TODO: Show error to player
        }
    }
Пример #32
0
    // Called by the Buy button
    public async void Buy()
    {
        try
        {
            await ApiWrapper.TransactionBuyCurrentProperty();

            Abandon();
        }
        catch (Exception e)
        {
            Debug.Log(e); // TODO: Show error to player
        }
    }