// GET api/values
        public IEnumerable <string> Get()
        {
            FindItemsAdvancedRequest request = new FindItemsAdvancedRequest();

            // request.keywords = keyword.Text;
            if (request.keywords == null)
            {
                request.keywords = "ipod";
            }
            PaginationInput pi = new PaginationInput();

            pi.entriesPerPage          = 10;
            pi.entriesPerPageSpecified = true;
            request.paginationInput    = pi;

            // Call the service
            FindingServicePortTypeClient client;
            string appID = System.Configuration.ConfigurationManager.AppSettings["AppID"];
            string findingServerAddress = System.Configuration.ConfigurationManager.AppSettings["FindingServerAddress"];

            APIManager.Core.Configuration.ClientConfig config = new APIManager.Core.Configuration.ClientConfig();
            // Initialize service end-point configration
            config.EndPointAddress = findingServerAddress;

            // set eBay developer account AppID
            config.ApplicationId = appID;

            // Create a service client
            client = FindingServiceClientFactory.getServiceClient(config);
            FindItemsAdvancedResponse response = client.findItemsAdvanced(request);

            return(new string[] { "value1", "value2" });
        }
        public static FindingServicePortTypeClient GetFindingClient()
        {
            ClientConfig config = new ClientConfig
            {
                EndPointAddress = EbaySettings.FindingServerAddress, // Initialize service end-point configration
                ApplicationId   = EbaySettings.AppID                 // set eBay developer account AppID
            };

            return(FindingServiceClientFactory.getServiceClient(config));
        }
        private void ProcessEbayLoad(ILogger logger, string userId)
        {
            logger.Write(String.Format("Starting the ebay load for user Id = {0}", userId),
                         LoggerCategories.Information, 0, 0,
                         TraceEventType.Information,
                         startEbayLoadMessage,
                         new Dictionary <string, object>());

            using (
                var stagingEbayLoadService =
                    UnityConfig.GetConfiguredContainer().Resolve <IStagingEbayLoadService>())
            {
                logger.Write(String.Format("ebay load service instantiated for user Id = {0}", userId),
                             LoggerCategories.Information, 0, 0,
                             TraceEventType.Information,
                             startEbayLoadMessage,
                             new Dictionary <string, object>());

                #region 'Check if an ebay load can run'
                //Check if a new ebay batch load can run (valid only where there is no ebay load currently running)
                if (!stagingEbayLoadService.CanExecuteEbayLoad())
                {
                    //Cannot execute a new ebay batch load
                    //Log the error
                    logger.Write(EbayLoadProcessingFault.FaultMessageBatchAlreadyRunning,
                                 LoggerCategories.Error, 0, 0,
                                 TraceEventType.Error,
                                 startEbayLoadMessage,
                                 new Dictionary <string, object>());
                    //User does not have an administrator role
                    throw new FaultException <EbayLoadProcessingFault>(
                              new EbayLoadProcessingFault {
                        ErrorDetails = EbayLoadProcessingFault.FaultCodeBatchAlreadyRunning, ErrorMessage = EbayLoadProcessingFault.FaultMessageBatchAlreadyRunning, Result = false
                    },
                              new FaultReason(new FaultReasonText(EbayLoadProcessingFault.FaultMessageBatchAlreadyRunning)), new FaultCode(EbayLoadProcessingFault.FaultCodeBatchAlreadyRunning));
                }
                #endregion 'Check if an ebay load can run'

                //Create a new ebay load batch record
                StagingEbayBatchImport stagingEbayBatchImport = stagingEbayLoadService.CreateStagingEbayLoadBatch(userId);
                //Check if a ebay load batch has been created
                if (stagingEbayBatchImport == null)
                {
                    logger.Write(EbayLoadProcessingFault.FaultMessageBatchWasNotCreated,
                                 LoggerCategories.Error, 0, 0,
                                 TraceEventType.Critical,
                                 startEbayLoadMessage,
                                 new Dictionary <string, object>());
                    //User does not have an administrator role
                    throw new FaultException <EbayLoadProcessingFault>(
                              new EbayLoadProcessingFault {
                        ErrorDetails = EbayLoadProcessingFault.FaultCodeBatchWasNotCreated, ErrorMessage = EbayLoadProcessingFault.FaultMessageBatchWasNotCreated, Result = false
                    },
                              new FaultReason(new FaultReasonText(EbayLoadProcessingFault.FaultMessageBatchWasNotCreated)), new FaultCode(EbayLoadProcessingFault.FaultCodeBatchWasNotCreated));
                }
                //Set ebay batch load records default values
                SetBatchDefaults(stagingEbayBatchImport);
                //Update the ebay batch load record with respective data
                stagingEbayLoadService.UpdateStagingEbayLoadBatch(stagingEbayBatchImport, true);

                //ebay Finding API client configuration
                var config = new ClientConfig
                {
                    // Finding API service end-point configuration
                    EndPointAddress = ConfigurationManager.AppSettings["EbayFindingAPIEndPointAddress"],
                    // eBay developer account AppID
                    ApplicationId = ConfigurationManager.AppSettings["EbayFindindAPIApplicationId"],
                    // timeout value for this call
                    HttpTimeout = 1500000 //25 minutes
                };

                //ebay Finding API client service
                FindingServicePortTypeClient findingServicePortTypeClient = FindingServiceClientFactory.getServiceClient(config);

                //ebay finding API request
                var request = new FindItemsByKeywordsRequest
                {
                    keywords = ConfigurationManager.AppSettings["EbayFindingApiKeywords"]
                };

                #region 'ebay Finding API Request Filters'

                var itemFilters = new List <ItemFilter>
                {
                    new ItemFilter
                    {
                        name  = ItemFilterType.AvailableTo,
                        value = new[] { ConfigurationManager.AppSettings["EbayAvailableToItemFilter"] }
                    }
                };

                //Get the ebay ISO8601 datetime format from web.config settings
                string iso8601DatetimeFormat = ConfigurationManager.AppSettings["EbayISO8601DateTimeFormat"];

                //Get the start time filter from database for when this ebay batch load was run last
                string ebayLoadStartTimeFromConfiguration = stagingEbayLoadService.GetEbayLoadStartTimeFrom();
                if (!String.IsNullOrWhiteSpace(ebayLoadStartTimeFromConfiguration))
                {
                    itemFilters.Add(new ItemFilter
                    {
                        name  = ItemFilterType.StartTimeFrom,
                        value =
                            new[]
                        {
                            //TODO: have to remove this filter below
                            (Convert.ToDateTime(ebayLoadStartTimeFromConfiguration)).AddMinutes(-20).ToString(iso8601DatetimeFormat)
                            //DateTime.Now.AddDays(-1).AddMinutes(-20).ToString(iso8601DatetimeFormat)
                        }
                    });
                }
                request.itemFilter = itemFilters.ToArray();

                #endregion 'ebay Finding API Request Filters'

                //Call the Finding service's Find Items By Keyword method
                FindItemsByKeywordsResponse check = findingServicePortTypeClient.findItemsByKeywords(request);
                DateTime ebayCheckTime            = DateTime.UtcNow;

                if (check == null)
                {
                    logger.Write(EbayLoadProcessingFault.FaultMessageFindItemBykeywordResposeIsNull,
                                 LoggerCategories.Error, 1, 0,
                                 TraceEventType.Critical,
                                 startEbayLoadMessage,
                                 new Dictionary <string, object>());
                    //Find item response is ready
                    throw new FaultException <EbayLoadProcessingFault>(
                              new EbayLoadProcessingFault {
                        ErrorDetails = EbayLoadProcessingFault.FaultCodeFindItemBykeywordResposeIsNull, ErrorMessage = EbayLoadProcessingFault.FaultMessageFindItemBykeywordResposeIsNull, Result = false
                    },
                              new FaultReason(new FaultReasonText(EbayLoadProcessingFault.FaultMessageFindItemBykeywordResposeIsNull)), new FaultCode(EbayLoadProcessingFault.FaultCodeFindItemBykeywordResposeIsNull));
                }

                if (check.ack == AckValue.Failure || check.ack == AckValue.PartialFailure)
                {
                    logger.Write(EbayLoadProcessingFault.FaultMessageFindItemBykeywordReturnedFailure + "Failure details: " + check.errorMessage,
                                 LoggerCategories.Error, 1, 0,
                                 TraceEventType.Critical,
                                 startEbayLoadMessage,
                                 new Dictionary <string, object>());

                    //Find item response has a failure
                    throw new FaultException <EbayLoadProcessingFault>(
                              new EbayLoadProcessingFault {
                        ErrorDetails = EbayLoadProcessingFault.FaultCodeFindItemBykeywordReturnedFailure, ErrorMessage = EbayLoadProcessingFault.FaultMessageFindItemBykeywordReturnedFailure, Result = false
                    },
                              new FaultReason(new FaultReasonText(EbayLoadProcessingFault.FaultMessageFindItemBykeywordReturnedFailure)), new FaultCode(EbayLoadProcessingFault.FaultCodeFindItemBykeywordReturnedFailure));
                }

                int totalKeywordMatchedItems = check.paginationOutput.totalEntries;
                var totalPages = (int)Math.Ceiling(totalKeywordMatchedItems / 100.00);
                stagingEbayBatchImport.TotalKeywordMatched = totalKeywordMatchedItems;
                stagingEbayBatchImport.EbayVersion         = findingServicePortTypeClient.getVersion(new GetVersionRequest()).version;

                logger.Write(
                    String.Format(
                        "ebay Finding Service - findItemsByKeywords call (user id = {0}, batch id = {1}) for selected filters has Total={2} items,  Total Pages (ebay default 100 items each)={3}",
                        userId, stagingEbayBatchImport.EbayBatchImportId, totalKeywordMatchedItems, totalPages),
                    LoggerCategories.Information, 0, 0,
                    TraceEventType.Information,
                    startEbayLoadMessage,
                    new Dictionary <string, object>());

                for (int curPage = 1; curPage <= totalPages; curPage++)
                {
                    request.paginationInput = new PaginationInput
                    {
                        entriesPerPageSpecified = true,
                        entriesPerPage          = 100,
                        pageNumberSpecified     = true,
                        pageNumber = curPage,
                    };

                    FindItemsByKeywordsResponse response =
                        findingServicePortTypeClient.findItemsByKeywords(request);
                    if (response != null &&
                        (response.searchResult.item != null && response.searchResult.item.Length > 0))
                    {
                        IEnumerable <SearchItem> searchItems =
                            response.searchResult.item.Where(EBayGlobalIdUsStore).DistinctBy(i => i.itemId);
                        foreach (SearchItem ebaySearchItem in searchItems)
                        {
                            stagingEbayBatchImport.ToBeProcessed++;
                            StagingEbayItem stagingEbayItem;
                            if (stagingEbayLoadService.EbayItemExists(ebaySearchItem.itemId, out stagingEbayItem))
                            {
                                stagingEbayBatchImport.Duplicates++;
                                stagingEbayBatchImport.Failed++;

                                logger.Write(
                                    String.Format(
                                        "ebay Finding Service - item (ebay item id = {2}) already exists (user id = {0}, batch id = {1})",
                                        userId, stagingEbayBatchImport.EbayBatchImportId, ebaySearchItem.itemId),
                                    LoggerCategories.Warning, 0, 0,
                                    TraceEventType.Warning,
                                    startEbayLoadMessage,
                                    new Dictionary <string, object>());
                                continue;
                            }
                            if ((ebaySearchItem.listingInfo == null ||
                                 String.IsNullOrWhiteSpace(ebaySearchItem.listingInfo.listingType)))
                            {
                                stagingEbayBatchImport.NoListingType++;
                                stagingEbayBatchImport.Failed++;

                                logger.Write(
                                    String.Format(
                                        "ebay Finding Service - item (ebay item id = {2}) has no listing type (user id = {0}, batch id = {1})",
                                        userId, stagingEbayBatchImport.EbayBatchImportId, ebaySearchItem.itemId),
                                    LoggerCategories.Error, 0, 0,
                                    TraceEventType.Error,
                                    startEbayLoadMessage,
                                    new Dictionary <string, object>());
                                continue;
                            }

                            stagingEbayItem = CreateStagingEbayItem(stagingEbayLoadService, ebaySearchItem,
                                                                    stagingEbayBatchImport.EbayBatchImportId, ebayCheckTime, userId);
                            UpdateCounts(stagingEbayItem, stagingEbayBatchImport);
                        }
                    }
                    //Page processed log entry
                    logger.Write(
                        String.Format("Items page {2} completed (user id = {0}, batch id = {1})", userId,
                                      stagingEbayBatchImport.EbayBatchImportId, curPage),
                        LoggerCategories.Information, 0, 0,
                        TraceEventType.Information,
                        startEbayLoadMessage,
                        new Dictionary <string, object>());
                }

                stagingEbayLoadService.UpsertEbayLoadStartTimeFromConfiguration(ebayCheckTime);

                //Set ebay batch completion data
                stagingEbayBatchImport.CompletedOn = DateTime.Now;
                stagingEbayBatchImport.InProcess   = false;
                stagingEbayLoadService.UpdateStagingEbayLoadBatch(stagingEbayBatchImport, true);

                //Page processed log entry
                logger.Write(String.Format("ebay batch load completed (user id = {0}, batch id = {1}), Summary: TotalKeywordMatched={2}, ToBeProcessed={3}, Failed={4}, Duplicated={11}, Imported={5}, " +
                                           "Auctions={6}, AuctionsWithBIN={7}, Classified={8}, FixedPrice={9}, StoreInventory={10}",
                                           userId, stagingEbayBatchImport.EbayBatchImportId, stagingEbayBatchImport.TotalKeywordMatched, stagingEbayBatchImport.ToBeProcessed,
                                           stagingEbayBatchImport.Failed, stagingEbayBatchImport.Imported, stagingEbayBatchImport.Auctions, stagingEbayBatchImport.AuctionsWithBIN,
                                           stagingEbayBatchImport.Classified, stagingEbayBatchImport.FixedPrice, stagingEbayBatchImport.StoreInventory, stagingEbayBatchImport.Duplicates),
                             LoggerCategories.Information, 0, 0,
                             TraceEventType.Information,
                             startEbayLoadMessage,
                             new Dictionary <string, object>());
            }
        }
Exemple #4
0
        public ActionResult Index(string Id)
        {
            // create a eBay client
            config.GlobalId = "EBAY-IE"; //use Irish eBay website (www.eBay.ie)
            FindingServicePortTypeClient client = FindingServiceClientFactory.getServiceClient(config);

            ViewBag.Message = Id;

            SearchItem[] items = null;
            try
            {
                // Create request object
                FindItemsAdvancedRequest request = new FindItemsAdvancedRequest();

                //filter items so just "buy it now" items appear
                ItemFilter itemFilter1 = new ItemFilter();
                itemFilter1.name  = ItemFilterType.ListingType;
                itemFilter1.value = new string[] { "FixedPrice" };

                ItemFilter[] itemFilterArray = new ItemFilter[1];
                itemFilterArray[0] = itemFilter1;

                // Set request parameters
                request.keywords   = Id;
                request.itemFilter = itemFilterArray;
                request.sortOrder  = SortOrderType.PricePlusShippingLowest;
                //request.sortOrderSpecified = true;
                OutputSelectorType[] outputs = { OutputSelectorType.SellerInfo };
                request.outputSelector = outputs;


                PaginationInput PaginationInput = new PaginationInput();
                //PaginationInput.totalNumberOfPages = 5;
                PaginationInput.entriesPerPageSpecified = true;
                PaginationInput.entriesPerPage          = 100;
                PaginationInput.pageNumberSpecified     = true;
                PaginationInput.pageNumber = 10;
                request.paginationInput    = PaginationInput;

                // Call the api
                FindItemsAdvancedResponse response = client.findItemsAdvanced(request);

                // Show output
                if (response.searchResult != null && response.searchResult.item != null)
                {
                    items = response.searchResult.item;
                    ViewBag.noResultsMsg = "";
                    return(View(items));
                }
                else if (Id.Length == 0)
                {
                    ViewBag.noResultsMsg = "No item entered. Please enter an item to search and try again";
                }
                else if (response.searchResult == null || response.searchResult.item == null)
                {
                    ViewBag.noResultsMsg = "No Results. Please try another search";
                }
            }
            catch (Exception ex)
            {
                var errorText = ex.Message;
            }

            return(View());
        }