Beispiel #1
0
        private static async Task TestAllegroAsync()
        {
            const int    CountryId = 1; // Poland
            const string WebApiKey = "488f1691";

            var client = new servicePortClient();

            var stopWatch = new Stopwatch();

            stopWatch.Start();

            var sysStatus = await client.doQuerySysStatusAsync(new doQuerySysStatusRequest(1, CountryId, WebApiKey));

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
            stopWatch.Restart();

            var loginResponse = await client.doLoginAsync(
                new doLoginRequest(
                    "*****@*****.**",
                    "Paris777",
                    CountryId,
                    WebApiKey,
                    sysStatus.verKey));

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
            stopWatch.Restart();

            var sessionHandle = loginResponse.sessionHandlePart;
            var items         = await client.doGetItemsInfoAsync(
                new doGetItemsInfoRequest(
                    sessionHandle,
                    new[] { 7855602159 },
                    1, // description
                    1, 1, 1, 1, 1, 1, 1, 1));

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
            stopWatch.Restart();

            var shipmentData = await client.doGetShipmentDataAsync(new doGetShipmentDataRequest(CountryId, WebApiKey));

            var shipmentDataById = shipmentData.shipmentDataList.ToDictionary(x => x.shipmentId);

            Console.WriteLine(stopWatch.ElapsedMilliseconds);
            stopWatch.Restart();

            foreach (var p in items.arrayItemListInfo
                     .SelectMany(x => x.itemPostageOptions))
            {
                var shipmentInfo = shipmentDataById.GetValueOrDefault(p.postageId);

                Console.WriteLine($"{p.postageId} ({shipmentInfo?.shipmentType} {shipmentInfo?.shipmentName}) {p.postageAmount} {p.postageFulfillmentTime.fulfillmentTimeFrom}-{p.postageFulfillmentTime.fulfillmentTimeTo}");
            }
        }
        private async Task <VersionKeyInfo> GetVersionKeyAsync(CancellationToken cancellationToken)
        {
            lock (_versionKeyLocker)
            {
                // version key is obtained only once (but it's sometimes invalidated by Allegro - see GetItemsInfoAsync exception handling)
                if (_versionKeyInfo != null)
                {
                    return(_versionKeyInfo);
                }

                if (_versionRequestInProgress)
                {
                    // possible for parallel requests after app started
                    throw new AllegroPlRequestException("Version key is being obtained...");
                }

                _versionRequestInProgress = true;
            }

            try
            {
                var client    = new servicePortClient();
                var sysStatus = await client.doQuerySysStatusAsync(new doQuerySysStatusRequest(1, CountryId, _webApiKey));

                lock (_versionKeyLocker)
                {
                    _versionKeyInfo = new VersionKeyInfo(sysStatus.verKey, DateTime.Now);

                    cancellationToken.ThrowIfCancellationRequested();

                    return(_versionKeyInfo);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new AllegroPlRequestException($"Request {nameof(servicePortClient.doQuerySysStatusAsync)} failed.", ex);
            }
            finally
            {
                lock (_versionKeyLocker)
                {
                    _versionRequestInProgress = false;
                }
            }
        }
Beispiel #3
0
        private static void GetApiContext()
        {
            if (_apiContext == null)
            {
                var webApiKey = "640314ba49b245f7be0a4fce0b76a6e0";

                var siteId      = 1;
                var siteVersion = 1416396021;

                var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
                {
                    MaxReceivedMessageSize = 15000000
                };

                _apiContext =
                    new servicePortClient(binding, new EndpointAddress("https://webapi.allegro.pl/service.php"));
                long userId, serverTime;
                var  syst = _apiContext.doQueryAllSysStatus(1, webApiKey);
                _login = _apiContext.doLogin("mosze888", "KGZkRsY5ottgDuW", 1, webApiKey, syst[0].verKey, out userId,
                                             out serverTime);
            }
        }
 public MainPage()
 {
     this.InitializeComponent();
     service = new servicePortClient();
 }
Beispiel #5
0
        public IActionResult TestAllegroApi()
        {
            var webApiKey = "640314ba49b245f7be0a4fce0b76a6e0";

            // Dependending which allegro site you want to connect to you'll have to use different values
            var siteId      = 1;
            var siteVersion = 1416396021;

            var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
            {
                MaxReceivedMessageSize = 15000000 // You might have to adjust this depending on how much data the API calls return
            };

            var    client        = new servicePortClient(binding, new EndpointAddress("https://webapi.allegro.pl/service.php"));
            long   versionKey    = 1;
            string versionString = "";
            int    parOut1;

            ItemsListType[]    parOut2;
            CategoriesListType parOut3;

            FiltersListType[] parOut4;
            string[]          parOut5;
            SellItemStruct[]  itemStructs;
            SellItemStruct[]  itemStructs2;
            // List the tree of categories available on the allegro site
            var categories = client.doGetCatsData(siteId, 0, webApiKey, true, out versionKey, out versionString);

            _categories = categories;
            //var items = client.doGetItemsList(webApiKey, siteId, new FilterOptionsType[0], new SortOptionsType(),
            //    500, 0, 500, out parOut1, out parOut2,
            //    out parOut3, out parOut4, out parOut5);
            long userId, serverTime;
            var  syst   = client.doQueryAllSysStatus(1, webApiKey);
            var  numCat = categories.Where(x => x.catName.Equals("1587 - 1668"));
            //var countryId = client.doGetCountries(1, webApiKey);
            //var ukraine = countryId.Where(x => x.countryName.Equals("Ukraina"));
            var login = client.doLogin("mosze888", "KGZkRsY5ottgDuW", 1, webApiKey, syst[0].verKey, out userId,
                                       out serverTime);
            //var items = client.doGetMySellItems(login,
            //    null, null, null, 9333, null, 100, 0, out itemStructs);
            //var numCat2 = categories.Where(x => x.catName.Equals("Kolekcje"));
            //var numCat3 = categories.Where(x => x.catId.Equals(79201));
            var itemsCount = client.doGetMySellItems(login, null, null, null, 0, null, 0, 0, out itemStructs);

            for (int i = 1; i < Math.Ceiling(itemsCount / 100d) + 1; i++)
            {
                foreach (var sellItem in itemStructs)
                {
                    _cats.Add(sellItem);
                }
                client.doGetMySellItems(login, null, null, null, 0, null, 0, i, out itemStructs);
            }

            //var adsasd = categories.Where(x => x.catId.Equals(91098));

            //GetCategories(91098);

            //foreach (var catIndex in _catsIndexes)
            //{
            //    client.doGetMySellItems(login, null, null, null, 9333, null, 100, 0, out itemStructs);
            //    foreach (var sellItem in itemStructs)
            //    {
            //        _cats.Add(sellItem);
            //    }
            //}

            var hasInd      = _cats.Where(x => x.itemTitle.Contains("(") && x.itemTitle.Contains(")"));
            var dontHaveInd = _cats.Where(x => !x.itemTitle.Contains("(") && !x.itemTitle.Contains(")"));
            var indexes     = hasInd
                              //    .Where(x=>
                              //{
                              //    var ind = x.itemTitle.LastIndexOf("(", StringComparison.InvariantCulture);
                              //    var coinIndex = x.itemTitle.Substring(ind).Replace(")", "").Replace("(", "");
                              //    int result;
                              //    return int.TryParse(coinIndex, out result);
                              //})
                              .SelectMany(x =>
            {
                var ind       = x.itemTitle.LastIndexOf("(", StringComparison.InvariantCulture);
                var coinIndex = x.itemTitle.Substring(ind).Replace(")", "").Replace("(", "");
                int result;
                if (!int.TryParse(coinIndex, out result))
                {
                    return(new[] { new { Index = -1, Index2 = coinIndex, x } });
                }
                return(new[] { new { Index = result, Index2 = coinIndex, x } });
            }

                                          ).OrderBy(x => x.Index);

            var duplicates = indexes
                             .GroupBy(i => i.Index)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key);

            BidItemStruct[] bidItems;

            var adfadasd = client.doGetMyBidItems(login, null, null, 0, null, 0, 0, out bidItems);

            //var adfadasd2 = client.doGetBidItem2(login, null);


            return(View("AllegroPage"));
        }
Beispiel #6
0
        public IActionResult SearchPage()
        {
            var webApiKey = "640314ba49b245f7be0a4fce0b76a6e0";

            // Dependending which allegro site you want to connect to you'll have to use different values
            var siteId      = 1;
            var siteVersion = 1416396021;

            var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
            {
                MaxReceivedMessageSize = 15000000 // You might have to adjust this depending on how much data the API calls return
            };

            var    client        = new servicePortClient(binding, new EndpointAddress("https://webapi.allegro.pl/service.php"));
            long   versionKey    = 1;
            string versionString = "";
            int    parOut1;

            ItemsListType[]    parOut2;
            CategoriesListType parOut3;

            FiltersListType[] parOut4;
            string[]          parOut5;
            SellItemStruct[]  itemStructs;
            // List the tree of categories available on the allegro site
            var categories = client.doGetCatsData(siteId, 0, webApiKey, true, out versionKey, out versionString);

            //var items = client.doGetItemsList(webApiKey, siteId, new FilterOptionsType[0], new SortOptionsType(),
            //    500, 0, 500, out parOut1, out parOut2,
            //    out parOut3, out parOut4, out parOut5);
            long userId, serverTime;
            var  syst   = client.doQueryAllSysStatus(1, webApiKey);
            var  numCat = categories.Where(x => x.catName.Equals("1587 - 1668"));
            //var countryId = client.doGetCountries(1, webApiKey);
            //var ukraine = countryId.Where(x => x.countryName.Equals("Ukraina"));
            var login = client.doLogin("mosze888", "KGZkRsY5ottgDuW", 1, webApiKey, syst[0].verKey, out userId,
                                       out serverTime);
            var items = client.doGetMySellItems(login,
                                                null, null, null, 9333, null, 100, 0, out itemStructs);

            //AllegroAPI.doGetItemsListRequest getlist = new AllegroAPI.doGetItemsListRequest();
            //getlist.webapiKey = "c7311ab6b61744c489171efa5d5367a4";
            //getlist.countryId = 1;

            //AllegroAPI.doGetItemsListResponse getlistresp = new AllegroAPI.doGetItemsListResponse();

            /*
             * DeleteAllCoins();
             *
             * string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
             * string ApplicationName = "Google Sheets API .NET Quickstart";
             *
             * UserCredential credential;
             *
             * using (var stream =
             * new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
             * {
             * string credPath = "token.json";
             * credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
             *  GoogleClientSecrets.Load(stream).Secrets,
             *  Scopes,
             *  "user",
             *  CancellationToken.None,
             *  new FileDataStore(credPath, true)).Result;
             * Console.WriteLine("Credential file saved to: " + credPath);
             * }
             *
             * // Create Google Sheets API service.
             * var service = new SheetsService(new BaseClientService.Initializer()
             * {
             * HttpClientInitializer = credential,
             * ApplicationName = ApplicationName,
             * });
             *
             * // Define request parameters.
             * String spreadsheetId = "13Hh_x_kU9BhBryuIwwGvB6r0PpztjZaVu8y5-5BbeTk";
             * String range = "New!A2:N1178";
             * SpreadsheetsResource.ValuesResource.GetRequest request =
             *  service.Spreadsheets.Values.Get(spreadsheetId, range);
             *
             * // Prints the names and majors of students in a sample spreadsheet:
             * // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
             * ValueRange response = request.Execute();
             * IList<IList<Object>> values = response.Values;
             * if (values != null && values.Count > 0)
             * {
             * //Console.WriteLine("Name, Major");
             * foreach (var row in values)
             * {
             *  CoinModel coin = new CoinModel();
             *
             *  if (row.Count == 14)
             *  {
             *      var index = int.Parse(row[0].ToString());
             *      var title = row[3].ToString();
             *      double price = 0d;
             *      if (row[4].ToString() != "")
             *      {
             *          price = double.Parse(row[4].ToString().Replace("грн.", "").Replace(",", ""));
             *      }
             *
             *      var link = row[5].ToString();
             *
             *      double allegroPrice = 0d;
             *      if (row[9].ToString() != "")
             *      {
             *          allegroPrice = double.Parse(row[9].ToString().Replace(" zł", "").Replace(",", ""));
             *      }
             *
             *      var allegroName = row[10].ToString();
             *      double dollarPrice = 0d;
             *      if (row[11].ToString() != "")
             *      {
             *          dollarPrice = double.Parse(row[11].ToString().Replace("$", "").Replace(",", ""));
             *      }
             *      var englishName = row[12].ToString();
             *
             *      bool isInStock = row[7].ToString() != "#N/A";
             *      var avers = row[1].ToString();
             *      var revers = row[2].ToString();
             *
             *      if (avers == "foto")
             *      {
             *          avers = string.Empty;
             *      }
             *
             *      if (revers == "foto")
             *      {
             *          revers = string.Empty;
             *      }
             *
             *      coin = new CoinModel
             *      {
             *          CoinId = index,
             *          Name = title,
             *          Cost = price,
             *          Link = link,
             *          //OrderForeignKey = index,
             *          ZlotyPrice = allegroPrice,
             *          PolishName = allegroName,
             *          DollarPrice = dollarPrice,
             *          EnglishName = englishName,
             *          IsInStock = isInStock,
             *          AversFotoLink = avers,
             *          ReversFotoLink = revers
             *      };
             *  }
             *  else
             *  {
             *
             *  }
             *  // Print columns A and E, which correspond to indices 0 and 4.
             *  //Console.WriteLine("{0}, {1}", row[0], row[4]);
             *  if (coin.Link == null)
             *  {
             *
             *  }
             *
             *
             *  using (var db = new BusinessLogic.BusinessLogic())
             *      db.AddCoin(Mapper.Map<CoinBL>(coin));
             * }
             * }
             */

            return(View());
        }
        public async Task <doGetItemsInfoResponse> GetItemsInfoAsync(
            long[] offerIds,
            bool includeAttributes,
            bool includeDeliveryOptions,
            bool includeDescription,
            CancellationToken cancellationToken)
        {
            Assure.ArgumentNotNull(offerIds, nameof(offerIds));
            const int MaxItemsPerRequest = 10;

            if (offerIds.Length > MaxItemsPerRequest)
            {
                throw new NotSupportedException($"Max '{MaxItemsPerRequest}' items per request is supported.");
            }

            var requestVersionKeyInfo = await GetVersionKeyAsync(cancellationToken);

            try
            {
                var client = new servicePortClient();

                // session id can't be cached in cloud since WebApi bind session id to IP
                // todo: refactor after static IP for all external requests
                var loginResponse = await client.doLoginAsync(
                    new doLoginRequest(
                        _webApiLogin,
                        _webApiPassword,
                        CountryId,
                        _webApiKey,
                        requestVersionKeyInfo.VersionKey));

                cancellationToken.ThrowIfCancellationRequested();

                var response = await client.doGetItemsInfoAsync(
                    new doGetItemsInfoRequest(
                        loginResponse.sessionHandlePart,
                        offerIds,
                        getDesc : includeDescription ? 1 : 0,               // description
                        getImageUrl : 0,
                        getAttribs : includeAttributes ? 1 : 0,             // attributes (including state)
                        getPostageOptions : includeDeliveryOptions ? 1 : 0, // delivery options
                        getCompanyInfo : 0,
                        getProductInfo : 0,
                        getAfterSalesServiceConditions : 0,
                        getEan : 0,
                        getAdditionalServicesGroup : 0));

                cancellationToken.ThrowIfCancellationRequested();

                return(response);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                if (ex.Message?.StartsWith("Niepoprawna wersja", StringComparison.OrdinalIgnoreCase) == true)
                {
                    // most likely version key is invalidated
                    lock (_versionKeyLocker)
                    {
                        // if it's first request with invalidated version key
                        if (_versionKeyInfo != null &&
                            _versionKeyInfo.IssuedOn == requestVersionKeyInfo.IssuedOn)
                        {
                            // cause version key refresh on the next request
                            _versionKeyInfo = null;
                        }
                    }
                }

                throw new AllegroPlRequestException("Request to WebApi failed.", ex);
            }
        }
Beispiel #8
0
 public AllegroApiWrapper(servicePortClient _sPC)
 {
     serviceClient = _sPC;
     GetLocalVersionKey();
     DoLogin();
 }