Exemplo n.º 1
0
        static async Task <List <DatafeedEvent> > GetEventAsync(SymConfig symConfig, Datafeed datafeed, DatafeedClient datafeedClient)
        {
            RestRequestHandler   restRequestHandler = new RestRequestHandler();
            HttpWebResponse      response           = datafeedClient.getEventsFromDatafeed(symConfig, datafeed);
            List <DatafeedEvent> events             = null;

            if (response.StatusCode.Equals(HttpStatusCode.OK) || response.StatusCode.Equals(HttpStatusCode.Accepted))
            {
                try
                {
                    string body = restRequestHandler.ReadResponse(response);
                    events = JsonConvert.DeserializeObject <List <DatafeedEvent> >(body);
                }
                catch (JsonSerializationException e)
                {
                    Console.WriteLine("The file could not be read:");
                    Console.WriteLine(e.Message);
                }
            }
            else if (response.StatusCode.Equals(HttpStatusCode.Forbidden) || response.StatusCode.Equals(HttpStatusCode.Unauthorized))
            {
                //Add reauth
                stopLoop = true;
            }
            else if (response.StatusCode.Equals(HttpStatusCode.BadRequest))
            {
                stopLoop = true;
            }
            response.Close();
            return(events);
        }
Exemplo n.º 2
0
        public bool RegisterNewClient(string publicToken, string clientId, string requestUrl)
        {
            var client  = new RestClient($"{_AuthUrl}/connect/token");
            var request = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("undefined", $"grant_type=authorization_code&client_id={_ClientId}&client_secret={_Secret}&redirect_uri={requestUrl}&code={publicToken}", ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                dynamic objContent   = JsonConvert.DeserializeObject(response.Content);
                string  accessKey    = objContent?.access_token;
                string  refreshToken = objContent?.refresh_token;
                //Gets info about the provider
                GetProviderInfo(accessKey, out string vendorName, out string vendorID);
                if (!string.IsNullOrEmpty(accessKey))
                {
                    Datafeed datafeed = new Datafeed(clientId, datafeedName, vendorID, vendorName, DateTime.Now, SecurityService.EncryptTripleDES(accessKey), SecurityService.EncryptTripleDES(refreshToken));
                    return(_datafeedDataService.AddUpdateClientDatafeed(datafeed));
                }
            }

            Serilog.Log.Logger?.Write(LogEventLevel.Error, $"Truelayer returned response: {response.Content}");

            return(false);
        }
        internal Datafeed GenerateDatafeed()
        {
            String   name     = String.Format("datafeed{0}", shoppingUtil.GetUniqueId());
            Datafeed datafeed = new Datafeed();

            datafeed.Name                 = name;
            datafeed.ContentType          = "products";
            datafeed.AttributeLanguage    = "en";
            datafeed.ContentLanguage      = "EN";
            datafeed.IntendedDestinations = new List <String>();
            datafeed.IntendedDestinations.Add("Shopping");
            datafeed.FileName               = name;
            datafeed.TargetCountry          = "US";
            datafeed.FetchSchedule          = new DatafeedFetchSchedule();
            datafeed.FetchSchedule.Weekday  = "monday";
            datafeed.FetchSchedule.Hour     = 6;
            datafeed.FetchSchedule.TimeZone = "America/Los_Angeles";
            datafeed.FetchSchedule.FetchUrl = "http://feeds.my-shop.com/" + name;
            datafeed.Format = new DatafeedFormat();
            datafeed.Format.FileEncoding    = "utf-8";
            datafeed.Format.ColumnDelimiter = "tab";
            datafeed.Format.QuotingMode     = "value quoting";

            return(datafeed);
        }
Exemplo n.º 4
0
        /// <summary>Runs multiple requests against the Content API for Shopping.</summary>
        internal void RunCalls(ulong merchantId)
        {
            // Datafeeds
            GetAllDatafeeds(merchantId);
            Datafeed newDatafeed = InsertDatafeed(merchantId);

            UpdateDatafeed(merchantId, (ulong)newDatafeed.Id);
            DeleteDatafeed(merchantId, (ulong)newDatafeed.Id);
        }
        public HttpWebResponse getEventsFromDatafeed(SymConfig symConfig, Datafeed datafeed)
        {
            RestRequestHandler restRequestHandler = new RestRequestHandler();
            DatafeedEvent      eventv4            = new DatafeedEvent();
            string             url      = "https://" + symConfig.agentHost + ":" + symConfig.agentPort + "/agent/v4/datafeed/" + datafeed.datafeedID + "/read";
            HttpWebResponse    response = restRequestHandler.executeRequest(null, url, false, WebRequestMethods.Http.Get, symConfig, true);

            return(response);
        }
Exemplo n.º 6
0
 public DatafeedEventsService(SymBotClient client)
 {
     this.botClient      = client;
     roomListeners       = new List <RoomListener>();
     IMListeners         = new List <IMListener>();
     connectionListeners = new List <ConnectionListener>();
     datafeedClient      = new DatafeedClient();
     datafeed            = datafeedClient.createDatafeed(client.getConfig());
     datafeedId          = datafeed.datafeedID;
 }
        public Datafeed createDatafeed(SymConfig symConfig)
        {
            Datafeed           datafeed           = new Datafeed();
            RestRequestHandler restRequestHandler = new RestRequestHandler();
            string             url  = "https://" + symConfig.agentHost + ":" + symConfig.agentPort + "/agent/v4/datafeed/create";
            HttpWebResponse    resp = restRequestHandler.executeRequest(null, url, false, WebRequestMethods.Http.Post, symConfig, true);
            string             body = restRequestHandler.ReadResponse(resp);
            JObject            o    = JObject.Parse(body);

            datafeed.datafeedID = (string)o["id"];
            return(datafeed);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            string                filePath              = Path.GetFullPath("config.json");
            SymBotClient          symBotClient          = new SymBotClient();
            DatafeedEventsService datafeedEventsService = new DatafeedEventsService();
            SymConfig             symConfig             = symBotClient.initBot(filePath);
            RoomListener          botLogic              = new BotLogic();
            DatafeedClient        datafeedClient        = datafeedEventsService.init(symConfig);
            Datafeed              datafeed              = datafeedEventsService.createDatafeed(symConfig, datafeedClient);

            datafeedEventsService.addRoomListener(botLogic);
            datafeedEventsService.getEventsFromDatafeed(symConfig, datafeed, datafeedClient);
        }
Exemplo n.º 9
0
        /// <summary>Runs multiple requests against the Content API for Shopping.</summary>
        internal void RunCalls(ulong merchantId)
        {
            // Datafeeds
            GetAllDatafeeds(merchantId);
            Datafeed newDatafeed = InsertDatafeed(merchantId);

            UpdateDatafeed(merchantId, (ulong)newDatafeed.Id);
            try
            {
                DeleteDatafeed(merchantId, (ulong)newDatafeed.Id);
            }
            catch (Google.GoogleApiException e)
            {
                Console.WriteLine("Warning: Tried to delete a datafeed too soon after creation. " + e.Message);
            }
        }
Exemplo n.º 10
0
        static async Task <List <DatafeedEvent> > RunAsync(SymConfig symConfig, Datafeed datafeed, DatafeedClient datafeedClient)
        {
            List <DatafeedEvent> events = new List <DatafeedEvent>();

            try
            {
                events = await GetEventAsync(symConfig, datafeed, datafeedClient);

                return(events);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(events);
            }
        }
        /// <summary>
        /// Adds a datafeed to the specified account.
        /// </summary>
        /// <returns>The datafeed that was inserter</returns>
        private Datafeed InsertDatafeed(ulong merchantId)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Inserting a datafeed");
            Console.WriteLine("=================================================================");
            Datafeed datafeed = GenerateDatafeed();

            Datafeed response = service.Datafeeds.Insert(datafeed, merchantId).Execute();

            Console.WriteLine(
                "Datafeed inserted with ID \"{0}\" and name \"{1}\".",
                response.Id,
                response.Name);
            Console.WriteLine();
            return(response);
        }
Exemplo n.º 12
0
        /// <summary>Runs multiple requests against the Content API for Shopping.</summary>
        internal void RunCalls(ulong merchantId, String emailAddress = "", ulong adWordsAccountId = 0)
        {
            // Products
            GetAllProducts(merchantId);
            Product newProduct = InsertProduct(merchantId);

            UpdateProduct(merchantId, newProduct.Id);
            UpdateProductUsingInventory(merchantId, newProduct.Id);
            DeleteProduct(merchantId, newProduct);

            // Products - batches
            Task <List <Product> > insertTask = InsertProductBatch(merchantId);

            insertTask.Wait();
            List <Product> insertedProduct = insertTask.Result;
            Task           deleteTask      = DeleteProductsBatch(merchantId, insertedProduct);

            deleteTask.Wait();

            // Datafeeds
            var      datafeed    = GetAllDatafeeds(merchantId);
            Datafeed newDatafeed = InsertDatafeed(merchantId);

            UpdateDatafeed(merchantId, (ulong)newDatafeed.Id);
            try
            {
                DeleteDatafeed(merchantId, (ulong)newDatafeed.Id);
            }
            catch (Google.GoogleApiException e)
            {
                Console.WriteLine("Warning: Tried to delete a datafeed too soon after creation. " + e.Message);
            }

            // Primary account, user management
            if (emailAddress != "")
            {
                AccountUser user = AddUser(merchantId, merchantId, emailAddress);
                RemoveUser(merchantId, merchantId, user.EmailAddress);
            }

            // Primary account, AdWords account link
            if (adWordsAccountId != 0)
            {
                LinkAdWordsAccount(merchantId, adWordsAccountId);
                UnlinkAdWordsAccount(merchantId, adWordsAccountId);
            }
        }
        /// <summary>
        /// Updates a datafeed using the Datafeeds.patch method.
        /// </summary>
        private void UpdateDatafeed(ulong merchantId, ulong datafeedId)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine(String.Format("Updating datafeed {0}", datafeedId));
            Console.WriteLine("=================================================================");

            Datafeed datafeed = new Datafeed();

            datafeed.FetchSchedule      = new DatafeedFetchSchedule();
            datafeed.FetchSchedule.Hour = 7;

            var      request  = service.Datafeeds.Patch(datafeed, merchantId, datafeedId);
            Datafeed response = shoppingUtil.ExecuteWithRetries(request, retryCodes);

            Console.WriteLine(
                "Datafeed updated with ID \"{0}\" and name \"{1}\".",
                response.Id,
                response.Name);
            Console.WriteLine();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Updates a datafeed using the Datafeeds.update method.
        /// </summary>
        private void UpdateDatafeed(ulong merchantId, ulong datafeedId)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine(String.Format("Updating datafeed {0}", datafeedId));
            Console.WriteLine("=================================================================");

            Datafeed datafeed = service.Datafeeds.Get(merchantId, datafeedId).Execute();

            datafeed.FetchSchedule.Hour = 7;

            // Set ETag to null as Update() will reject it otherwise.
            datafeed.ETag = null;

            var      request  = service.Datafeeds.Update(datafeed, merchantId, datafeedId);
            Datafeed response = shoppingUtil.ExecuteWithRetries(request, retryCodes);

            Console.WriteLine(
                "Datafeed updated with ID \"{0}\" and name \"{1}\".",
                response.Id,
                response.Name);
            Console.WriteLine();
        }
        /// <summary>
        /// Updates a datafeed using the datafeeds.insert method as there is no update method.
        /// <para>Inserting a datafeed with an ID that already exists means the same as doing an update.</para>
        /// </summary>
        private void UpdateDatafeed(ulong merchantId, ulong datafeedId)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine(String.Format("Updating datafeed {0}", datafeedId));
            Console.WriteLine("=================================================================");
            // First we need to retrieve the full object, since there are no partial updates for the
            // datafeeds collection in Content API v2.

            Datafeed datafeed = service.Datafeeds.Get(merchantId, datafeedId).Execute();

            // Set ETag to null as Patch() will reject it otherwise.
            datafeed.ETag = null;

            datafeed.FetchSchedule.Hour = 7;

            Datafeed response = service.Datafeeds.Patch(datafeed, merchantId, datafeedId).Execute();

            Console.WriteLine(
                "Datafeed updated with ID \"{0}\" and name \"{1}\".",
                response.Id,
                response.Name);
            Console.WriteLine();
        }
        internal Datafeed GenerateDatafeed()
        {
            String name = String.Format("datafeed{0}", GetUniqueId());
            Datafeed datafeed = new Datafeed();
            datafeed.Name = name;
            datafeed.ContentType = "products";
            datafeed.AttributeLanguage = "en";
            datafeed.ContentLanguage = "EN";
            datafeed.IntendedDestinations = new List<String>();
            datafeed.IntendedDestinations.Add("Shopping");
            datafeed.FileName = name;
            datafeed.TargetCountry = "US";
            datafeed.FetchSchedule = new DatafeedFetchSchedule();
            datafeed.FetchSchedule.Weekday = "monday";
            datafeed.FetchSchedule.Hour = 6;
            datafeed.FetchSchedule.TimeZone = "America/Los_Angeles";
            datafeed.FetchSchedule.FetchUrl = "http://feeds.my-shop.com/" + name;
            datafeed.Format = new DatafeedFormat();
            datafeed.Format.FileEncoding = "utf-8";
            datafeed.Format.ColumnDelimiter = "tab";
            datafeed.Format.QuotingMode = "value quoting";

            return datafeed;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Updates a datafeed configuration of your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/update
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="datafeedId">NA</param>
        /// <param name="body">A valid Shoppingcontent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedResponse</returns>
        public static Datafeed Update(ShoppingcontentService service, string merchantId, string datafeedId, Datafeed body, DatafeedsUpdateOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (merchantId == null)
                {
                    throw new ArgumentNullException(merchantId);
                }
                if (datafeedId == null)
                {
                    throw new ArgumentNullException(datafeedId);
                }

                // Building the initial request.
                var request = service.Datafeeds.Update(body, merchantId, datafeedId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.UpdateRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Update failed.", ex);
            }
        }
Exemplo n.º 18
0
        public Datafeed createDatafeed(SymConfig symConfig, DatafeedClient datafeedClient)
        {
            Datafeed datafeed = datafeedClient.createDatafeed(symConfig);

            return(datafeed);
        }
Exemplo n.º 19
0
        public bool AddUpdateClientDatafeed(Datafeed datafeed)
        {
            MongoDatabase database = new MongoDatabase(databaseName, connectionString);

            return(database.UpsertRecord(datafeedTableName, datafeed, datafeed._id));
        }