Beispiel #1
0
        private async void createSession_Click(object sender, RoutedEventArgs e)
        {
            bool status = await Amazon.OpenDriverAsync(isHeadless);

            if (status)
            {
                indicatorCircle.Fill = greenColor;
                if (string.IsNullOrWhiteSpace(code.Text))
                {
                    searchButton.IsEnabled = false;
                }
                else
                {
                    searchButton.IsEnabled = true;
                }
                closeSession.IsEnabled  = true;
                createSession.IsEnabled = false;
                condition = true;
                restartSession.IsEnabled = true;
            }
            else
            {
                indicatorCircle.Fill = redColor;
            }
        }
        private void ProcessCore(long betScreenshotId, Amazon.S3.AmazonS3 amazonS3Client, SynchronizationContext synchronizationContext)
        {
            using (var unitOfWorkScope = _unitOfWorkScopeFactory.Create())
            {
                BetScreenshot betScreenshot = null;
                try
                {
                    betScreenshot = _repositoryOfBetScreenshot.Get(EntitySpecifications.IdIsEqualTo<BetScreenshot>(betScreenshotId)).Single();
                    var battleBet = _repositoryOfBet.Get(BetSpecifications.BetScreenshotOwner(betScreenshot.Id)).Single();

                    betScreenshot.StartedProcessingDateTime = DateTime.UtcNow;

                    ImageFormat imageFormat;
                    var screenshotEncodedStream = GetScreenshot(battleBet.Url, betScreenshot, synchronizationContext, out imageFormat);

                    PutScreenshot(amazonS3Client, screenshotEncodedStream, betScreenshot, imageFormat);

                    betScreenshot.FinishedProcessingDateTime = DateTime.UtcNow;

                    betScreenshot.StatusEnum = BetScreenshotStatus.Succeeded;
                }
                catch (Exception ex)
                {
                    Logger.TraceException(String.Format("Failed to process betScreenshotId = {0}. Trying to save as failed", betScreenshotId), ex);
                    betScreenshot.StatusEnum = BetScreenshotStatus.Failed;
                }
                finally
                {
                    unitOfWorkScope.SaveChanges();
                }
            }
        }
Beispiel #3
0
 private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (condition)
     {
         await Amazon.CloseConnectionAsync();
     }
 }
Beispiel #4
0
 /// <summary>
 /// Enqueues the events for delivery. The event is stored in an instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>.
 /// </summary>
 /// <param name="eventObject">Event object.<see cref="Amazon.MobileAnalytics.Model.Event"/></param>
 public void EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event eventObject)
 {
     ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
     {
         EnqueueEventsHelper(eventObject);
     }));
 }
        private void RenderAWSMetricDatum(Amazon.CloudWatch.Model.MetricDatum metricDatum, TextWriter writer)
        {
            if (!String.IsNullOrEmpty(metricDatum.MetricName))
                writer.Write("MetricName: {0}, ", metricDatum.MetricName);
            if (!String.IsNullOrEmpty(metricDatum.Unit))
                writer.Write("Unit: {0}, ", metricDatum.Unit);

            if (metricDatum.StatisticValues == null)
                writer.Write("Value: {0}, ", metricDatum.Value.ToString(CultureInfo.InvariantCulture));

            if (metricDatum.Dimensions.Any())
            {
                writer.Write("Dimensions: {0}, ", String.Join(", ",
                                                              metricDatum.Dimensions.Select(
                                                                  x =>
                                                                  String.Format("{0}: {1}", x.Name, x.Value))));
            }

            if (metricDatum.Timestamp != default(DateTime))
                writer.Write("Timestamp: {0}, ", metricDatum.Timestamp.ToString(CultureInfo.CurrentCulture));

            if (metricDatum.StatisticValues != null)
            {
                if (metricDatum.StatisticValues.Maximum > 0)
                    writer.Write("Maximum: {0}, ", metricDatum.StatisticValues.Maximum.ToString(CultureInfo.InvariantCulture));

                writer.Write("Minimum: {0}, ", metricDatum.StatisticValues.Minimum.ToString(CultureInfo.InvariantCulture));

                if (metricDatum.StatisticValues.SampleCount > 1)
                    writer.Write("SampleCount: {0}, ", metricDatum.StatisticValues.SampleCount.ToString(CultureInfo.InvariantCulture));

                if (metricDatum.StatisticValues.Sum > 0)
                    writer.Write("Sum: {0}, ", metricDatum.StatisticValues.Sum.ToString(CultureInfo.InvariantCulture));
            }
        }
Beispiel #6
0
        /* the event for excel button clicks that update the merchant sku */
        private void excelButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            switch (loadingLabel.Text)
            {
            case "Sears":
            {
                // sears case
                sears = new Sears();
                new Thread(() => sears.Update(openFileDialog.FileName)).Start();

                shopCa     = null;
                amazon     = null;
                giantTiger = null;
            }
            break;

            case "Shop.ca":
            {
                // shop.ca case
                shopCa = new ShopCa();
                new Thread(() => shopCa.Update(openFileDialog.FileName)).Start();

                sears      = null;
                giantTiger = null;
                amazon     = null;
            }
            break;

            case "Amazon":
            {
                // amazon case
                amazon = new Amazon();
                new Thread(() => amazon.Update(openFileDialog.FileName)).Start();

                sears      = null;
                shopCa     = null;
                giantTiger = null;
            }
            break;

            case "Giant Tiger":
            {
                // giant tiger case
                giantTiger = new GiantTiger();
                new Thread(() => giantTiger.Update(openFileDialog.FileName)).Start();

                sears  = null;
                shopCa = null;
                amazon = null;
            }
            break;
            }

            timer.Start();
        }
Beispiel #7
0
        /// <summary>
        /// Prompt for the Amazon Keys
        /// </summary>
        /// <param name="callback">A callback if we got keys</param>
        /// <param name="cancel">A callback if the user didn't provide keys</param>
        public void AskForKeys(TurKit.startTaskDelegate callback, TurKit.noKeysDelegate cancel)
        {
            Amazon amazon       = new Amazon();
            Window amazonWindow = new Window
            {
                Title         = "Amazon Keys",
                Content       = amazon,
                SizeToContent = SizeToContent.WidthAndHeight,
                ResizeMode    = ResizeMode.NoResize
            };

            amazon.okButton.Click += (sender, e) => {
                AmazonKeys keys = new AmazonKeys();
                keys.amazonID  = amazon.accessKey.Text;
                keys.secretKey = amazon.secretKey.Text;

                if (callback != null)
                {
                    callback(keys);
                }
                amazonWindow.Close();
            };

            amazon.cancelButton.Click += (sender, e) =>
            {
                if (cancel != null)
                {
                    cancel();
                }
            };

            amazonWindow.ShowDialog();
        }
Beispiel #8
0
        public ZAwsElasticIp(ZAwsEc2Controller controller, Amazon.EC2.Model.Address res)
            : base(controller)
        {
            Update(res);

            //myController.HandleNewElasticIp(this);
        }
Beispiel #9
0
        public IActionResult BlackList(string Asin, string modifer, MarketPlace marketPlace)
        {
            Amazon currAsin = new Amazon();

            var amazon = _context.Amazon.Where(x => x.Asin == Asin && x.marketPlace == marketPlace.ToString());

            currAsin.id          = Convert.ToInt32(amazon.Select(x => x.id).FirstOrDefault());
            currAsin.Asin        = Convert.ToString(amazon.Select(x => x.Asin).FirstOrDefault());
            currAsin.sku         = Convert.ToString(amazon.Select(x => x.sku).FirstOrDefault());
            currAsin.wholesaler  = Convert.ToString(amazon.Select(x => x.wholesaler).FirstOrDefault());
            currAsin.price       = Convert.ToDouble(amazon.Select(x => x.price).FirstOrDefault());
            currAsin.marketPlace = marketPlace.ToString();

            try
            {
                if (currAsin != null)
                {
                    currAsin.blackList = Convert.ToBoolean(modifer);
                    _context.Amazon.Update(currAsin);
                    _context.SaveChanges();
                }
            }
            catch
            {
                ViewData["Error"] = "The ASIN and/or Market Place is NOT in the database.";
                return(View(_context.Amazon.ToList().Where(x => x.blackList == true)));
            }

            ViewData["Success"] = "ASIN added to the database successfully.";
            return(View(_context.Amazon.ToList().Where(x => x.blackList == true)));
        }
        /// <summary>
        /// Decodes the base64 encoded properties of the Attribute.
        /// The Name and/or Value properties of an Attribute can be base64 encoded.
        /// </summary>
        /// <param name="inputAttribute">The properties of this Attribute will be decoded</param>
        /// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.NameEncoding" />
        /// <seealso cref="P:Amazon.SimpleDB.Model.Attribute.ValueEncoding" />
        public static void DecodeAttribute(Amazon.SimpleDB.Model.Attribute inputAttribute)
        {
            if (null == inputAttribute)
            {
                throw new ArgumentNullException("inputAttribute", "The Attribute passed in was null");
            }

            string encoding = inputAttribute.NameEncoding;
            if (null != encoding)
            {
                if (String.Compare(encoding, base64Str, true) == 0)
                {
                    // The Name is base64 encoded
                    inputAttribute.Name = AmazonSimpleDBUtil.DecodeBase64String(inputAttribute.Name);
                    inputAttribute.NameEncoding = "";
                }
            }

            encoding = inputAttribute.ValueEncoding;
            if (null != encoding)
            {
                if (String.Compare(encoding, base64Str, true) == 0)
                {
                    // The Value is base64 encoded
                    inputAttribute.Value = AmazonSimpleDBUtil.DecodeBase64String(inputAttribute.Value);
                    inputAttribute.ValueEncoding = "";
                }
            }
        }
Beispiel #11
0
        public static bool Get_Msg_From_Req_Q(out Amazon.SQS.Model.Message msg, out bool msgFound)
        {
            msgFound = false;
            msg = null;
            try
            {
                ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest();
                receiveMessageRequest.MaxNumberOfMessages = 1;
                receiveMessageRequest.QueueUrl = requests_Q_url;
                ReceiveMessageResponse receiveMessageResponse = sqs.ReceiveMessage(receiveMessageRequest);
                if (receiveMessageResponse.IsSetReceiveMessageResult())
                {
                    ReceiveMessageResult receiveMessageResult = receiveMessageResponse.ReceiveMessageResult;
                    List<Amazon.SQS.Model.Message> receivedMsges = receiveMessageResponse.ReceiveMessageResult.Message;
                    if (receivedMsges.Count == 0)
                    {
                        return true;
                    }
                    msgFound = true;
                    msg = receivedMsges[0];
                }

            }
            catch (AmazonSQSException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
                Console.WriteLine("XML: " + ex.XML);
                return false;
            }
            return true;
        }
Beispiel #12
0
        public static bool Delete_Msg_From_Req_Q(Amazon.SQS.Model.Message msg)
        {
            try
            {
                String messageRecieptHandle = msg.ReceiptHandle;

                //Deleting a message
                Console.WriteLine("Deleting the message.\n");
                DeleteMessageRequest deleteRequest = new DeleteMessageRequest();
                deleteRequest.QueueUrl = requests_Q_url;
                deleteRequest.ReceiptHandle = messageRecieptHandle;
                Console.WriteLine("Before deleting incoming msg(" + messageRecieptHandle + ").");
                sqs.DeleteMessage(deleteRequest);
                Console.WriteLine("After deleting incoming msgs().");

            }
            catch (AmazonSQSException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
                Console.WriteLine("XML: " + ex.XML);
                return false;
            }
            return true;
        }
 public GlacierArchiveInfo(Amazon.Glacier.Model.DescribeJobResult result)
 {
     Id = result.ArchiveId;
     SizeInBytes = result.ArchiveSizeInBytes;
     CreationDate = result.CreationDate;
     Checksum = result.SHA256TreeHash;
 }
Beispiel #14
0
        public void CountGoodSubArraysTest(int[] A, int B, int expected)
        {
            // Act
            int result = Amazon.CountGoodSubArrays(A, B);

            // Assert
            Assert.AreEqual(expected, result);
        }
        public string Identify(Amazon.IdentityManagement.Model.User user)
        {
            if (null == user)
            {
                throw new ArgumentNullException(AnchoringByIdentifierBehavior.ArgumentNameUser);
            }

            return user.UserId;
        }
Beispiel #16
0
 public override ActivityState Do(Amazon.SimpleWorkflow.Model.ActivityTask task)
 {            
     
     return new ActivityState() 
     {                
         Key = "output",
         Value = new string(task.Input.ToCharArray().Reverse().ToArray())
     };            
 }
Beispiel #17
0
        public void HandleSpan(MessageSink messageSink, MessageActionSpan actionSpan)
        {
            var amazon = new Amazon(actionSpan.Match.ToString());

            if (amazon.Success)
            {
                messageSink("Amazon: " + amazon.Title + "\n\t" + amazon.Price);
            }
        }
Beispiel #18
0
 protected override void Initialize()
 {
     // Instantiate constituents
     _amazon    = new Amazon(this);
     _customer  = new Customer(this);
     _dell      = new BarnesAndNoble(this);
     _ups       = new UPS(this);
     _upsDriver = new UPSDriver(this);
     _visa      = new Visa(this);
 }
        public void PutScreenshot(Amazon.S3.AmazonS3 amazonS3Client, string bucketName, string path, Stream stream)
        {
            var putObjectRequest = new PutObjectRequest();

            putObjectRequest.WithInputStream(stream);
            putObjectRequest.WithBucketName(bucketName);
            putObjectRequest.WithKey(path);

            amazonS3Client.PutObject(putObjectRequest);
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            #region FactoryMethod

            Console.WriteLine("\nDemonstrating \"Factory Method\":");

            Shop shop1 = new Amazon();
            Shop shop2 = new Wallmart();

            Console.WriteLine("\nBuying cookies.");
            Cookies cookies1 = shop1.BuyCookies();
            Cookies cookies2 = shop2.BuyCookies();

            Console.WriteLine("\nEating cookies.");
            cookies1.Eat();
            cookies2.Eat();

            #endregion

            #region AbstractFactory

            Console.WriteLine("\nDemonstrating \"Abstract Factory\"");

            Console.WriteLine("\nBorn gods");
            God zeus     = new God(new BornZeus());
            God poseidon = new God(new BornPoseidon());
            God aid      = new God(new BornAids());

            Console.WriteLine("\nZeus is here");
            zeus.Weapon.Attack();
            zeus.Ability.Use();

            Console.WriteLine("\nPoseidon is here");
            poseidon.Weapon.Attack();
            poseidon.Ability.Use();

            Console.WriteLine("\nAid is here");
            aid.Weapon.Attack();
            aid.Ability.Use();

            #endregion

            #region Singleton

            Console.WriteLine("\nDemonstrating \"Singleton\"");

            Console.WriteLine("\nResources of player:");
            Console.WriteLine($"Gold: {ResourcesCounter.GetInstance().Gold.ToString()}");
            Console.WriteLine($"Wood: {ResourcesCounter.GetInstance().Wood.ToString()}");

            #endregion

            Console.Write("\nPress key to continue...");
            Console.ReadLine();
        }
Beispiel #21
0
        public void IsCheeseReachableInMazeTest(string mazeString, bool expected)
        {
            // Arrange
            int[,] maze = ConvertMazeString(mazeString);

            // Act
            bool result = Amazon.IsCheeseReachableInMaze(maze);

            // Assert
            Assert.AreEqual(expected, result, mazeString);
        }
 /// <summary>
 /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.DeliveryClient"/> class.
 /// </summary>
 /// <param name="isDataAllowed">An instance of IDeliveryPolicyFactory <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
 /// <param name="clientContext">An instance of ClientContext <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.ClientContext"/></param>
 /// <param name="credentials">An instance of Credentials <see cref="Amazon.Runtime.AWSCredentials"/></param>
 /// <param name="regionEndPoint">Region end point <see cref="Amazon.RegionEndpoint"/></param>
 public DeliveryClient(IDeliveryPolicyFactory policyFactory, Amazon.Runtime.Internal.ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint)
 {
     _policyFactory = policyFactory;
     _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
     _clientContext = clientContext;
     _appId = clientContext.AppID;
     _eventStore = new SQLiteEventStore(AWSConfigsMobileAnalytics.MaxDBSize, AWSConfigsMobileAnalytics.DBWarningThreshold);
     _deliveryPolicies = new List<IDeliveryPolicy>();
     _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());
     _deliveryPolicies.Add(_policyFactory.NewBackgroundSubmissionPolicy());
 }
Beispiel #23
0
        ///// <summary>
        ///// Allows the use of a specific config in the creation of the client for a context
        ///// </summary>
        ///// <param name="context">The context the client should be used in</param>
        ///// <param name="config">The config object for the client</param>
        //public static void UseConfigForClient(DynamoDBContext context, AmazonS3Config config)
        //{
        //    var castedClient = ((AmazonDynamoDBClient)context.Client);
        //    var client = new AmazonS3Client(castedClient.GetCredentials(), config);
        //    S3ClientCache cache;
        //    if (!S3Link.Caches.TryGetValue(context, out cache))
        //    {                
        //        cache = new S3ClientCache(castedClient.GetCredentials(),castedClient.CloneConfig<AmazonS3Config>());
        //        S3Link.Caches.Add(context, cache);
        //    }            
        //    cache.UseClient(client, config.RegionEndpoint);
        //}

        /// <summary>
        /// Creates an S3Link that can be used to managed an S3 connection
        /// </summary>
        /// <param name="context">The context that is handling the S3Link</param>
        /// <param name="bucket">The bucket the S3Link should manage</param>
        /// <param name="key">The key that S3Link should store and download from</param>
        /// <param name="region">The region of the S3 resource</param>
        /// <returns>A new S3Link object that can upload and download to the target bucket</returns>
        public static S3Link Create(DynamoDBContext context, string bucket, string key, Amazon.RegionEndpoint region)
        {
            S3ClientCache cacheFromKey;
            if (S3Link.Caches.TryGetValue(context, out cacheFromKey))
            {
                return new S3Link(cacheFromKey, bucket, key, region.SystemName);
            }

            S3ClientCache cache = CreatClientCacheFromContext(context);
            return new S3Link(cache, bucket, key, region.SystemName);
        }
Beispiel #24
0
 public static void IncorrectAsinPromptOrThrow(string asin)
 {
     if (!Amazon.IsAsin(asin) &&
         DialogResult.No == MessageBox.Show($"Incorrect ASIN detected: {asin}!\n" +
                                            "Kindle may not display an X-Ray for this book.\n" +
                                            "Do you wish to continue?", "Incorrect ASIN", MessageBoxButtons.YesNo))
     {
         throw new Exception($"Incorrect ASIN detected: {asin}!\r\n" +
                             "Kindle may not display an X-Ray for this book.\r\n" +
                             "You must either use Calibre's Quality Check plugin (Fix ASIN for Kindle Fire) " +
                             "or a MOBI editor (exth 113 and optionally 504) to change this.");
     }
 }
Beispiel #25
0
        public AWSSubnet(Amazon.EC2.Model.Subnet subnet)
        {
            Name = "Unnamed";
            if (subnet != null)
            {
                foreach (var tag in subnet.Tags.Where(tag => tag.Key == "Name"))
                {
                    Name = tag.Value;
                }

                SubnetId = subnet.SubnetId;
                CidrBlock = subnet.CidrBlock;
            }
        }
Beispiel #26
0
        public void Amazon()
        {
            customUrl           = "https://www.amazon.com.tr/Lenovo-30BFS3W400-W-2135-GTX1080-512SSD/dp/B08BG6W56C?ref_=s9_apbd_orecs_hd_bw_bDkqJAl&pf_rd_r=7G8HYQ84V5WC1RQSETBV&pf_rd_p=f9a1563d-4e14-5798-a39a-e461d59b63a6&pf_rd_s=merchandised-search-11&pf_rd_t=BROWSE&pf_rd_i=12601905031";
            customExpectedName  = "Lenovo";
            customExpectedPrice = 16349.00; //normal price

            var amazon = new Amazon();

            amazon = amazon.Product(customUrl);

            Assert.Equal(customExpectedName, amazon.Name);
            Assert.Equal(customExpectedPrice, amazon.Price);
            Assert.Null(amazon.Error);
        }
Beispiel #27
0
        private void metroGrid1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex <= -1 || e.ColumnIndex == metroGrid1.Columns["DG3_CheckBox"].Index)
            {
                return;
            }
            string store     = _currentsearchstore;
            string asin_isbn = Convert.ToString(metroGrid1.Rows[e.RowIndex].Cells["DG3_ASIN_ISBN"].Value);

            if (String.IsNullOrEmpty(asin_isbn))
            {
                return;
            }
            Process.Start($"https://www.amazon.{Amazon.GetTld(store)}/dp/{asin_isbn}/&tag=" + AmazonApi.AssociateTag(store));
        }
        public void Process(long betScreenshotId, Amazon.S3.AmazonS3 amazonS3Client, SynchronizationContext synchronizationContext)
        {
            using (var transactionScope = _transactionScopeFactory.Create())
            {
                try
                {
                    ProcessCore(betScreenshotId, amazonS3Client, synchronizationContext);

                    transactionScope.Complete();
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(String.Format("Failed to process betScreenshotId = {0}. Was not saved", betScreenshotId), ex);
                }
            }
        }
Beispiel #29
0
        public ZAwsEc2(ZAwsEc2Controller controller, Amazon.EC2.Model.Reservation res)
            : base(controller)
        {
            StatisticsValid = false;

            LatestBootConsoleTimestamp = "";
            ConsoleOutput = "";

            Update(res);

            /*
            Trace.WriteLine("Now will see to configure new applications.");
            ConfigureAppsWhenBootingComplete = myController.HandleNewEc2Instance(this) ? 3 : 0;
            Trace.WriteLine("ConfigureAppsWhenBootingComplete = " + ConfigureAppsWhenBootingComplete.ToString());
             * */
        }
Beispiel #30
0
        public async Task Add(string store, Dictionary <string, string> entryList)
        {
            Main mf = Application.OpenForms["Main"] as Main;

            foreach (var item in entryList.ToList())
            {
                Database.OpenConnection();
                SQLiteCommand checkEntry = new SQLiteCommand(
                    "SELECT COUNT(*) FROM Products WHERE Store = @store AND [ASIN / ISBN] = @asin_isbn",
                    Database.Connection);
                checkEntry.Parameters.AddWithValue("@store", store);
                checkEntry.Parameters.AddWithValue("@asin_isbn", item.Key);
                int entryExist = Convert.ToInt32(checkEntry.ExecuteScalar());
                if (entryExist > 0)
                {
                    entryList.Remove(item.Key);
                }
            }
            if (!entryList.Any())
            {
                metroLabel1.Text = @"Alle ausgewählten Produkte bereits in der Datenbank vorhanden.";
                return;
            }
            foreach (var item in entryList)
            {
                string asin_isbn = item.Key;
                string name      = item.Value;
                var    shortUrl  = await URLShortener.Generate(Amazon.MakeReferralLink(store, asin_isbn), name, store);

                if (shortUrl == null)
                {
                    continue;
                }
                Database.OpenConnection();
                SQLiteCommand insertEntry =
                    new SQLiteCommand(
                        "INSERT INTO Products (Store, [ASIN / ISBN], Name, URL) Values (@store, @asin_isbn, @name, @shorturl)",
                        Database.Connection);
                insertEntry.Parameters.AddWithValue("@store", store);
                insertEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn);
                insertEntry.Parameters.AddWithValue("@name", name);
                insertEntry.Parameters.AddWithValue("@shorturl", shortUrl);
                insertEntry.ExecuteNonQuery();
            }
            ProductDatabase.Display(mf.metroComboBox2.SelectedIndex == -1 ? "ALLE" : mf.metroComboBox2.Text);
            metroLabel1.Text = @"Alle ausgewählten Produkte Erfolgreich Hinzugefügt.";
        }
Beispiel #31
0
        ///// <summary>
        ///// Allows the use of a specific config in the creation of the client for a context
        ///// </summary>
        ///// <param name="context">The context the client should be used in</param>
        ///// <param name="config">The config object for the client</param>
        //public static void UseConfigForClient(DynamoDBContext context, AmazonS3Config config)
        //{
        //    var castedClient = ((AmazonDynamoDBClient)context.Client);
        //    var client = new AmazonS3Client(castedClient.GetCredentials(), config);
        //    S3ClientCache cache;
        //    if (!S3Link.Caches.TryGetValue(context, out cache))
        //    {                
        //        cache = new S3ClientCache(castedClient.GetCredentials(),castedClient.CloneConfig<AmazonS3Config>());
        //        S3Link.Caches.Add(context, cache);
        //    }            
        //    cache.UseClient(client, config.RegionEndpoint);
        //}

        /// <summary>
        /// Creates an S3Link that can be used to managed an S3 connection
        /// </summary>
        /// <param name="context">The context that is handling the S3Link</param>
        /// <param name="bucket">The bucket the S3Link should manage</param>
        /// <param name="key">The key that S3Link should store and download from</param>
        /// <param name="region">The region of the S3 resource</param>
        /// <returns>A new S3Link object that can upload and download to the target bucket</returns>
        public static S3Link Create(DynamoDBContext context, string bucket, string key, Amazon.RegionEndpoint region)
        {
            S3ClientCache cacheFromKey;
            if (S3Link.Caches.TryGetValue(context, out cacheFromKey))
            {
                return new S3Link(cacheFromKey, bucket, key, region.SystemName);
            }
            var client = ((AmazonDynamoDBClient)context.Client);
            S3ClientCache cache = new S3ClientCache(client.GetCredentials(), client.CloneConfig<AmazonS3Config>());

            lock (S3Link.cacheLock)
            {
                S3Link.Caches.Add(context, cache);                
            }

            return new S3Link(cache, bucket, key, region.SystemName);
        }
Beispiel #32
0
 public async Task Run(SourceDefinition source, CancellationToken token)
 {
     if (source.Source == SourceType.Amazon)
     {
         var amazon = new Amazon(_client, _logger, _runner, source);
         await amazon.Run(token);
     }
     else if (source.Source == SourceType.NewEgg)
     {
         var newEgg = new NewEgg(_client, source);
         await newEgg.Run(token);
     }
     else
     {
         throw new Exception($"Unrecognized source type {source.Source}");
     }
 }
Beispiel #33
0
        private async void closeSession_Click(object sender, RoutedEventArgs e)
        {
            bool status = await Amazon.CloseConnectionAsync();

            if (status)
            {
                indicatorCircle.Fill     = redColor;
                restartSession.IsEnabled = false;
            }
            else
            {
                indicatorCircle.Fill = greenColor;
            }
            closeSession.IsEnabled  = false;
            searchButton.IsEnabled  = false;
            createSession.IsEnabled = true;
            condition = false;
        }
        private static Media BuildMediaModel(Amazon.AmazonService.Item amazonItem)
        {
            Media returnMedia = new Media();

            returnMedia.Title = amazonItem.ItemAttributes.Title;
            returnMedia.EAN = amazonItem.ItemAttributes.EAN;

            int mediaId = UpdateMediaTypes(amazonItem.ItemAttributes.ProductGroup);

            returnMedia.fkMediaTypeId = mediaId;

            if(amazonItem.LargeImage != null)
            {
                returnMedia.Image = amazonItem.LargeImage.URL;
            }

            return returnMedia;
        }
Beispiel #35
0
 public static void DecodeAttribute(Amazon.SimpleDB.Model.Attribute inputAttribute)
 {
     if (inputAttribute == null)
     {
         throw new ArgumentNullException("inputAttribute", "The Attribute passed in was null");
     }
     string nameEncoding = inputAttribute.NameEncoding;
     if ((nameEncoding != null) && (string.Compare(nameEncoding, base64Str, true) == 0))
     {
         inputAttribute.Name = DecodeBase64String(inputAttribute.Name);
         inputAttribute.NameEncoding = "";
     }
     nameEncoding = inputAttribute.ValueEncoding;
     if ((nameEncoding != null) && (string.Compare(nameEncoding, base64Str, true) == 0))
     {
         inputAttribute.Value = DecodeBase64String(inputAttribute.Value);
         inputAttribute.ValueEncoding = "";
     }
 }
Beispiel #36
0
        public PvcS3(
            string accessKey = null,
            string secretKey = null,
            string bucketName = null,
            Amazon.RegionEndpoint regionEndpoint = null)
        {
            this.accessKey = accessKey != null ? accessKey : PvcS3.AccessKey;
            this.secretKey = secretKey != null ? secretKey : PvcS3.SecretKey;
            this.bucketName = bucketName != null ? bucketName : PvcS3.BucketName;
            this.regionEndpoint = regionEndpoint != null ? regionEndpoint : PvcS3.RegionEndpoint;

            // Set up the API client for S3.
            AWSCredentials creds = new BasicAWSCredentials(this.accessKey, this.secretKey);
            this.s3client = new AmazonS3Client(creds, this.regionEndpoint);

            // Initialize some private stuff that we use to track md5 sums
            this.keyEtags = new Dictionary<string, string>();
            this.keyMD5Sums = new Dictionary<string, string>();
        }
Beispiel #37
0
        /// <summary>
        /// Enqueues the events for delivery. The event is stored in an instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>.
        /// </summary>
        /// <param name="eventObject">Event object.<see cref="Amazon.MobileAnalytics.Model.Event"/></param>
        public void EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event eventObject)
        {
#if BCL35            
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
            {
#elif PCL || BCL45
            Task.Run(() =>
            {
#endif
                string eventString = null;
                try
                {
                    eventString = JsonMapper.ToJson(eventObject);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "An exception occurred when converting low level client event to json string.");
                    List<Amazon.MobileAnalytics.Model.Event> eventList = new List<Amazon.MobileAnalytics.Model.Event>();
                    eventList.Add(eventObject);
                    MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when converting low level client event to json string.", e, eventList);
                    _maManager.OnRaiseErrorEvent(eventArgs);
                }

                if (null != eventString)
                {
                    try
                    {
                        _eventStore.PutEvent(eventString, _appID);
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, "Event {0} was not stored.", eventObject.EventType);
                        MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when storing event into event store.", e, new List<Amazon.MobileAnalytics.Model.Event>());
                        _maManager.OnRaiseErrorEvent(eventArgs);
                    }
                    _logger.DebugFormat("Event {0} is queued for delivery", eventObject.EventType);
                }
#if BCL35
            }));
#elif PCL || BCL45
            });
#endif
        }
Beispiel #38
0
        private async void searchButton_Click(object sender, RoutedEventArgs e)
        {
            var tempcolor = indicatorCircle.Fill;

            indicatorCircle.Fill   = yellowColor;
            searchButton.IsEnabled = false;
            try
            {
                data = await Amazon.GetProductInfoAsync(code.Text);

                title.Text       = data.Title;
                rating.Text      = data.Rating.ToString();
                totalreview.Text = data.TotalReviews.ToString();
                recent.Text      = data.RecentReviews.ToString();
                isdataavailable  = true;
                if (locationset)
                {
                    saveButton.IsEnabled = true;
                }
                if (!ViewedItem.Contains(code.Text))
                {
                    ViewedItem.Add(code.Text);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Please enter a valid product code or restart the session.",
                                "A small problem",
                                MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
            }
            if (string.IsNullOrWhiteSpace(code.Text) || condition == false)
            {
                searchButton.IsEnabled = false;
            }
            else
            {
                searchButton.IsEnabled = true;
            }

            indicatorCircle.Fill = tempcolor;
        }
Beispiel #39
0
        public IActionResult BlackList(string Asin, string modifer)
        {
            Amazon currAsin = new Amazon();

            var amazon = _context.Amazon.Where(x => x.Asin == Asin);

            currAsin.id         = Convert.ToInt32(amazon.Select(x => x.id).FirstOrDefault());
            currAsin.Asin       = Convert.ToString(amazon.Select(x => x.Asin).FirstOrDefault());
            currAsin.sku        = Convert.ToString(amazon.Select(x => x.sku).FirstOrDefault());
            currAsin.wholesaler = Convert.ToString(amazon.Select(x => x.wholesaler).FirstOrDefault());
            currAsin.price      = Convert.ToDouble(amazon.Select(x => x.price).FirstOrDefault());

            if (currAsin != null)
            {
                currAsin.blackList = Convert.ToBoolean(modifer);
                _context.Amazon.Update(currAsin);
                _context.SaveChanges();
            }

            return(Redirect("BlackList"));
        }
Beispiel #40
0
        public void GroupNumbersTest()
        {
            // Arrange
            var testInput = new List <KeyValuePair <int, char[]> >
            {
                new KeyValuePair <int, char[]>(8, new char[] { 'z', 'x', 'y' }),
                new KeyValuePair <int, char[]>(5, new char[] { 'y', 'u' }),
                new KeyValuePair <int, char[]>(3, new char[] { 'm' }),
                new KeyValuePair <int, char[]>(6, new char[] { 'u', 'd' }),
                new KeyValuePair <int, char[]>(9, new char[] { 'm', 'n' }),
                new KeyValuePair <int, char[]>(7, new char[] { 'a' })
            };

            // Act
            var result = Amazon.GroupNumbers(testInput);

            // Assert
            Assert.AreEqual(3, result.Count);
            foreach (List <int> group in result)
            {
                Console.WriteLine(string.Join(",", group));
            }
        }
        private void EditR53Record(Amazon.Route53.Model.ResourceRecordSet rrset)
        {

            var r53 = new Amazon.Route53.AmazonRoute53Client(
                    AccessKeyId, SecretAccessKey, RegionEndpoint);

            var rrRequ = new Amazon.Route53.Model.ChangeResourceRecordSetsRequest
            {
                HostedZoneId = HostedZoneId,
                ChangeBatch = new Amazon.Route53.Model.ChangeBatch
                {
                    Changes = new List<Amazon.Route53.Model.Change>
                    {
                        new Amazon.Route53.Model.Change
                        {
                            Action = Amazon.Route53.ChangeAction.UPSERT,
                            ResourceRecordSet = rrset
                        }
                    }
                }
            };
            var rrResp = r53.ChangeResourceRecordSets(rrRequ);
        }
 public GetPasswordDataResponse WithGetPasswordDataResult(Amazon.EC2.Model.GetPasswordDataResult getPasswordDataResult)
 {
     this.getPasswordDataResultField = getPasswordDataResult;
     return this;
 }
Beispiel #43
0
        private async Task btnKindleExtras_Run()
        {
            //Check current settings
            if (!File.Exists(txtMobi.Text))
            {
                MessageBox.Show("Specified book was not found.", "Book Not Found");
                return;
            }
            if (rdoGoodreads.Checked)
            {
                if (txtGoodreads.Text == "")
                {
                    MessageBox.Show($"No {_dataSource.Name} link was specified.", $"Missing {_dataSource.Name} Link");
                    return;
                }
                if (!txtGoodreads.Text.ToLower().Contains(_settings.dataSource.ToLower()))
                {
                    MessageBox.Show($"Invalid {_dataSource.Name} link was specified.\r\n"
                                    + $"If you do not want to use {_dataSource.Name}, you can change the data source in Settings."
                                    , $"Invalid {_dataSource.Name} Link");
                    return;
                }
            }
            if (_settings.realName.Trim().Length == 0 || _settings.penName.Trim().Length == 0)
            {
                MessageBox.Show(
                    "Both Real and Pen names are required for End Action\r\n" +
                    "file creation. This information allows you to rate this\r\n" +
                    "book on Amazon. Please review the settings page.",
                    "Amazon Customer Details Not found");
                return;
            }

            var metadata = await Task.Run(() => UIFunctions.GetAndValidateMetadata(txtMobi.Text, _settings.outDir, _settings.saverawml));

            if (metadata == null)
            {
                return;
            }

            SetDatasourceLabels(); // Reset the dataSource for the new build process
            Logger.Log($"Book's {_dataSource.Name} URL: {txtGoodreads.Text}");
            try
            {
                BookInfo bookInfo = new BookInfo(metadata, txtGoodreads.Text);

                string outputDir = OutputDirectory(bookInfo.author, bookInfo.sidecarName, true);

                Logger.Log("Attempting to build Author Profile...");
                AuthorProfile ap = new AuthorProfile(bookInfo, new AuthorProfile.Settings
                {
                    AmazonTld         = _settings.amazonTLD,
                    Android           = _settings.android,
                    OutDir            = _settings.outDir,
                    SaveBio           = _settings.saveBio,
                    UseNewVersion     = _settings.useNewVersion,
                    UseSubDirectories = _settings.useSubDirectories
                });
                if (!await ap.Generate())
                {
                    return;
                }
                SaPath = $@"{outputDir}\StartActions.data.{bookInfo.asin}.asc";
                ApPath = $@"{outputDir}\AuthorProfile.profile.{bookInfo.asin}.asc";
                Logger.Log("Attempting to build Start Actions and End Actions...");
                EndActions ea = new EndActions(ap, bookInfo, metadata.RawMlSize, _dataSource, new EndActions.Settings
                {
                    AmazonTld         = _settings.amazonTLD,
                    Android           = _settings.android,
                    OutDir            = _settings.outDir,
                    PenName           = _settings.penName,
                    RealName          = _settings.realName,
                    UseNewVersion     = _settings.useNewVersion,
                    UseSubDirectories = _settings.useSubDirectories
                });
                if (!await ea.Generate())
                {
                    return;
                }

                if (_settings.useNewVersion)
                {
                    await ea.GenerateNewFormatData(_progress, _cancelTokens.Token);

                    // TODO: Do the templates differently
                    Model.EndActions eaBase;
                    try
                    {
                        var template = File.ReadAllText(Environment.CurrentDirectory + @"\dist\BaseEndActions.json", Encoding.UTF8);
                        eaBase = JsonConvert.DeserializeObject <Model.EndActions>(template);
                    }
                    catch (FileNotFoundException)
                    {
                        Logger.Log(@"Unable to find dist\BaseEndActions.json, make sure it has been extracted!");
                        return;
                    }
                    catch (Exception e)
                    {
                        Logger.Log($@"An error occurred while loading dist\BaseEndActions.json (make sure any new versions have been extracted!)\r\n{e.Message}\r\n{e.StackTrace}");
                        return;
                    }

                    await ea.GenerateEndActionsFromBase(eaBase, _progress, _cancelTokens.Token);

                    StartActions sa;
                    try
                    {
                        var template = File.ReadAllText(Environment.CurrentDirectory + @"\dist\BaseStartActions.json", Encoding.UTF8);
                        sa = JsonConvert.DeserializeObject <StartActions>(template);
                    }
                    catch (FileNotFoundException)
                    {
                        Logger.Log(@"Unable to find dist\BaseStartActions.json, make sure it has been extracted!");
                        return;
                    }
                    catch (Exception e)
                    {
                        Logger.Log($@"An error occurred while loading dist\BaseStartActions.json (make sure any new versions have been extracted!)\r\n{e.Message}\r\n{e.StackTrace}");
                        return;
                    }

                    // TODO: Separate out SA logic
                    string saContent = null;
                    if (_settings.downloadSA)
                    {
                        Logger.Log("Attempting to download Start Actions...");
                        try
                        {
                            saContent = await Amazon.DownloadStartActions(metadata.ASIN);
                        }
                        catch
                        {
                            Logger.Log("No pre-made Start Actions available, building...");
                        }
                    }
                    if (string.IsNullOrEmpty(saContent))
                    {
                        saContent = ea.GenerateStartActionsFromBase(sa);
                    }
                    ea.WriteStartActions(saContent);

                    cmsPreview.Items[3].Enabled = true;
                    EaPath = $@"{outputDir}\EndActions.data.{bookInfo.asin}.asc";
                }
                else
                {
                    ea.GenerateOld();
                }

                cmsPreview.Items[1].Enabled = true;

                checkFiles(bookInfo.author, bookInfo.title, bookInfo.asin);
                if (_settings.playSound)
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(Environment.CurrentDirectory + @"\done.wav");
                    player.Play();
                }
            }
            catch (Exception ex)
            {
                Logger.Log("An error occurred while creating the new Author Profile, Start Actions, and/or End Actions files:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                metadata.Dispose();
            }
        }
Beispiel #44
0
        public static async Task Run(CancellationToken cancelToken, string store)
        {
            Timer.Tick    += new EventHandler(Timer_Tick);
            Timer.Interval = 1000;

            if (!Settings.Get <bool>("ScanNew") && !Settings.Get <bool>("ScanUsed"))
            {
                mf.textBox4.AppendText("Crawler wird gestoppt - Reason: Neu & Gebraucht sind Deaktiviert" + Environment.NewLine);
                mf.metroButton3.PerformClick();
                return;
            }

            mf.textBox4.AppendText("Übernehme Neu & Gebraucht Einstellungen" + Environment.NewLine);
            var sellerForNew = new List <string>();

            if (!String.IsNullOrWhiteSpace(Settings.Get <string>("SellerForNew")))
            {
                sellerForNew = Settings.Get <string>("SellerForNew").Split(',').Select(s => s.Trim()).ToList();
            }
            else
            {
                sellerForNew.Add("Amazon");
            }
            var sellerForUsed = new List <string>();

            if (!String.IsNullOrWhiteSpace(Settings.Get <string>("SellerForUsed")))
            {
                sellerForUsed = Settings.Get <string>("SellerForUsed").Split(',').Select(s => s.Trim()).ToList();
            }
            else
            {
                sellerForUsed.Add("Amazon");
            }


            TorSharpSettings torSettings = null;
            TorSharpProxy    torProxy    = null;

            if (Settings.Get <bool>("UseTorProxies"))
            {
                mf.textBox4.AppendText("Initialisiere TOR Proxy Funktion" + Environment.NewLine);
                try
                {
                    torSettings = new TorSharpSettings
                    {
                        ReloadTools             = true,
                        ZippedToolsDirectory    = Path.Combine(FoldersFilesAndPaths.Temp, "TorZipped"),
                        ExtractedToolsDirectory = Path.Combine(FoldersFilesAndPaths.Temp, "TorExtracted"),
                        PrivoxySettings         =
                        {
                            Port = 1337,
                        },
                        TorSettings =
                        {
                            SocksPort       =     1338,
                            ControlPort     =     1339,
                            ControlPassword = "******",
                        },
                    };
                    await new TorSharpToolFetcher(torSettings, new HttpClient()).FetchAsync();
                    torProxy = new TorSharpProxy(torSettings);
                    await torProxy.ConfigureAndStartAsync();
                }
                catch (Exception ex)
                {
                    mf.textBox4.AppendText("Fehler beim Initialisiere der TOR Proxy Funktion ;-(" + Environment.NewLine + "TOR Proxy Funktion wird deaktiviert!" + Environment.NewLine);
                    mf.textBox4.AppendText(ex.Message);
                    mf.metroToggle5.Checked = false;
                }

                if (Settings.IsPremium && Settings.Get <bool>("UseTorProxies") && Settings.Get <bool>("ProxyAlwaysActive"))
                {
                    mf.textBox4.AppendText("Set TOR Proxy - Reason: P. always Active" + Environment.NewLine);
                    mf.metroLabel45.Text   = Convert.ToString(await WebUtils.GetCurrentIpAddressAsync(torSettings));
                    Proxies.TorProxyActive = true;
                }
            }

            string sourcecode;
            int    sites, loops;

            while (true)
            {
                Database.OpenConnection();
                SQLiteCommand getEntry;
                switch (store)
                {
                case "ALLE":
                    getEntry = new SQLiteCommand("SELECT * FROM Products WHERE Status = '0' ORDER BY [Letzter Check] ASC LIMIT 0,1",
                                                 Database.Connection);
                    break;

                default:
                    getEntry =
                        new SQLiteCommand("SELECT * FROM Products WHERE Status = '0' AND Store = @store ORDER BY [Letzter Check] ASC LIMIT 0,1",
                                          Database.Connection);
                    getEntry.Parameters.AddWithValue("@store", store);
                    break;
                }
                SQLiteDataReader entry = getEntry.ExecuteReader();
                if (!entry.HasRows)
                {
                    mf.metroButton3.PerformClick();
                    Timer.Stop();
                    torProxy.Stop();
                    return;
                }
                while (entry.Read())
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        Timer.Stop();
                        torProxy.Stop();
                        return;
                    }
                    mf.metroLabel10.Text        = Convert.ToString(entry["Store"]);
                    mf.metroLabel11.Text        = Convert.ToString(entry["ASIN / ISBN"]);
                    mf.metroLabel12.Text        = Convert.ToString(entry["Name"]);
                    mf.metroLabel13.Text        = Convert.ToString(entry["Preis: Neu"]);
                    mf.metroLabel14.Text        = Convert.ToString(entry["Preis: Wie Neu"]);
                    mf.metroLabel15.Text        = Convert.ToString(entry["Preis: Sehr Gut"]);
                    mf.metroLabel16.Text        = Convert.ToString(entry["Preis: Gut"]);
                    mf.metroLabel17.Text        = Convert.ToString(entry["Preis: Akzeptabel"]);
                    mf.metroLabel18.Text        = Convert.ToString(entry["Letzter Check"]);
                    mf.metroLabel24.Text        = mf.metroLabel25.Text = mf.metroLabel26.Text = mf.metroLabel27.Text = mf.metroLabel28.Text = null;
                    mf.metroLabel41.Text        = null;
                    mf.webBrowser1.DocumentText = mf.webBrowser2.DocumentText = null;
                    await Task.Delay(Tools.RandomNumber(250, 500), cancelToken).ContinueWith(tsk => { });

                    string priceNew = null;
                    if (Settings.Get <bool>("ScanNew"))
                    {
                        List <string> priceNewList = new List <string>();
                        mf.tabControl2.SelectedTab = mf.TabPage4;
                        sites = 1;
                        loops = 0;
                        do
                        {
                            if (cancelToken.IsCancellationRequested)
                            {
                                Timer.Stop();
                                torProxy.Stop();
                                return;
                            }
                            try
                            {
                                string url = "https://www.amazon." + Amazon.GetTld(Convert.ToString(entry["Store"])) +
                                             "/gp/aw/ol/" + entry["ASIN / ISBN"] +
                                             "/ref=mw_dp_olp?ca=" + entry["ASIN / ISBN"] + "&o=New&op=" + (loops + 1) +
                                             "&vs=1";

                                var handler = new HttpClientHandler();
                                if (Settings.Get <bool>("UseTorProxies"))
                                {
                                    if (Settings.IsPremium && Settings.Get <bool>("ProxyAlwaysActive") ||
                                        Proxies.TorProxyActive && Proxies.RealIPnexttime > DateTime.Now)
                                    {
                                        Debug.WriteLine("Add TOR Proxy to HttpClientHandler...");
                                        handler.Proxy =
                                            new WebProxy(new Uri("http://*****:*****@"<title> (Tut uns Leid!|Toutes nos excuses)</title>");
                            Match errordetection1 = Regex.Match(sourcecode.RemoveLineEndings(),
                                                                @"<title>(503 - Service Unavailable Error)</title>");
                            if (errordetection.Success || errordetection1.Success)
                            {
                                Debug.WriteLine("Issue Found...");
                                continue;
                            }
                            //CAPTCHA Detection
                            Match captchadetection =
                                Regex.Match(sourcecode,
                                            "<title dir=\"ltr\">(Amazon CAPTCHA|Bot Check|Robot Check)</title>");
                            if (captchadetection.Success)
                            {
                                Debug.WriteLine("Captcha detected...");
                                if (Settings.Get <bool>("UseTorProxies"))
                                {
                                    await torProxy.GetNewIdentityAsync();

                                    mf.metroLabel45.Text =
                                        Convert.ToString(await WebUtils.GetCurrentIpAddressAsync(torSettings));
                                    Proxies.TorProxyActive = true;
                                    if (!Settings.Get <bool>("ProxyAlwaysActive") &&
                                        Proxies.RealIPnexttime < DateTime.Now)
                                    {
                                        Proxies.RealIPnexttime = DateTime.Now.AddMinutes(15);
                                    }
                                }
                                continue;
                            }

                            //How many Sites?
                            Match sitesNumber = Regex.Match(sourcecode, "<a name=\"New\">([^\"]*) / ([^\"]*)</a>");
                            if (sitesNumber.Success && loops == 0 && Settings.Get <int>("ScanMethod") == 0)
                            {
                                sites = Convert.ToInt32(
                                    Math.Ceiling(Convert.ToDecimal(sitesNumber.Groups[2].Value) / 10));
                            }
                            mf.metroLabel41.Text = $@"{loops + 1} / {sites} (NEU)";

                            //Get Price for NEW
                            if (sellerForNew.Contains("Amazon"))
                            {
                                Match newama = Regex.Match(sourcecode,
                                                           "<a href=(.*)ca=([a-zA-Z0-9_]*)&vs=1(.*)>(Neu|Nuovo|Neuf|Nuevo|New) - (EUR |£)(.*)</a>");
                                if (newama.Success)
                                {
                                    priceNewList.Add(await CurrencyConverter.ConvertToEuro(newama.Groups[6].Value,
                                                                                           Convert.ToString(entry["Store"])));
                                }
                            }
                            if (sellerForNew.Contains("Drittanbieter"))
                            {
                                if (sellerForNew.Contains("Versand per Amazon"))
                                {
                                    Regex new3rd =
                                        new Regex(
                                            "(Versand durch Amazon.de|Spedito da Amazon|EXPÉDIÉ PAR AMAZON|Distribuido por Amazon|Fulfilled by Amazon)(\r\n|\r|\n)</font>(\r\n|\r|\n)(\r\n|\r|\n)<br />(\r\n|\r|\n)(\r\n|\r|\n)(\r\n|\r|\n)" +
                                            "<a href=(.*)ca=([a-zA-Z0-9_]*)&eid=(.*)>(Neu|Nuovo|Neuf|Nuevo|New) - (EUR |£)(.*)</a>",
                                            RegexOptions.Compiled);
                                    foreach (Match itemMatch in new3rd.Matches(sourcecode))
                                    {
                                        priceNewList.Add(
                                            await CurrencyConverter.ConvertToEuro(itemMatch.Groups[13].Value,
                                                                                  Convert.ToString(entry["Store"])));
                                    }
                                }
                                else
                                {
                                    Regex new3rd =
                                        new Regex(
                                            @"<a href=(.*)ca=([a-zA-Z0-9_]*)&eid=(.*)>(Neu|Nuovo|Neuf|Nuevo|New) - (EUR |£)(.*)</a>",
                                            RegexOptions.Compiled);
                                    foreach (Match itemMatch in new3rd.Matches(sourcecode))
                                    {
                                        priceNewList.Add(
                                            await CurrencyConverter.ConvertToEuro(itemMatch.Groups[6].Value,
                                                                                  Convert.ToString(entry["Store"])));
                                    }
                                }
                            }
                            loops++;
                            if (sites > loops)
                            {
                                await Task.Delay(
                                    Tools.RandomNumber(Convert.ToInt32(mf.numericUpDown3.Value) * 1000 - 500,
                                                       Convert.ToInt32(mf.numericUpDown3.Value) * 1000 + 500), cancelToken)
                                .ContinueWith(tsk => { });
                            }
                        } while (sites > loops);

                        RemoveInvalidEntrys(priceNewList);
                        priceNew = priceNewList.OrderBy(price => price).FirstOrDefault();
                        if (!String.IsNullOrEmpty(priceNew))
                        {
                            mf.metroLabel24.Text = priceNew;
                            ComparePrice(entry["Preis: Neu"], priceNew, mf.metroLabel24);
                        }
                    }
                    await Task.Delay(Tools.RandomNumber(500, 1000), cancelToken).ContinueWith(tsk => { });

                    string priceLikeNew    = null;
                    string priceVeryGood   = null;
                    string priceGood       = null;
                    string priceAcceptable = null;
                    if (Settings.Get <bool>("ScanUsed"))
                    {
                        List <string> priceLikeNewList    = new List <string>();
                        List <string> priceVeryGoodList   = new List <string>();
                        List <string> priceGoodList       = new List <string>();
                        List <string> priceAcceptableList = new List <string>();
                        mf.tabControl2.SelectedTab = mf.TabPage5;
                        var conditionList = new List <Tuple <List <string>, string> >
                        {
                            new Tuple <List <string>, string>(priceLikeNewList,
                                                              "Wie neu|Condizioni pari al nuovo|Comme neuf|Como nuevo|Mint"),
                            new Tuple <List <string>, string>(priceVeryGoodList,
                                                              "Sehr gut|Ottimo|Très bon état|Muy bueno|Very good"),
                            new Tuple <List <string>, string>(priceGoodList,
                                                              "Gut|Buono|D'occasion - très bon état|Bueno|Good"),
                            new Tuple <List <string>, string>(priceAcceptableList,
                                                              "Akzeptabel|Accettabile|Acceptable|Aceptable|Acceptable")
                        };
                        sites = 1;
                        loops = 0;
                        do
                        {
                            if (cancelToken.IsCancellationRequested)
                            {
                                Timer.Stop();
                                torProxy.Stop();
                                return;
                            }
                            try
                            {
                                string url = "https://www.amazon." + Amazon.GetTld(Convert.ToString(entry["Store"])) +
                                             "/gp/aw/ol/" + entry["ASIN / ISBN"] +
                                             "/ref=mw_dp_olp?o=Used&op=" + (loops + 1);

                                var handler = new HttpClientHandler();
                                if (Settings.Get <bool>("UseTorProxies"))
                                {
                                    if (Settings.IsPremium && Settings.Get <bool>("ProxyAlwaysActive") || Proxies.TorProxyActive && Proxies.RealIPnexttime > DateTime.Now)
                                    {
                                        Debug.WriteLine("Add TOR Proxy to HttpClientHandler...");
                                        handler.Proxy = new WebProxy(new Uri("http://*****:*****@"<title> (Tut uns Leid!|Toutes nos excuses)</title>");
                            Match errordetection1 = Regex.Match(sourcecode.RemoveLineEndings(), @"<title>(503 - Service Unavailable Error)</title>");
                            if (errordetection.Success || errordetection1.Success)
                            {
                                Debug.WriteLine("Issue Found...");
                                continue;
                            }
                            //CAPTCHA Detection
                            Match captchadetection = Regex.Match(sourcecode, "<title dir=\"ltr\">(Amazon CAPTCHA|Bot Check|Robot Check)</title>");
                            if (captchadetection.Success)
                            {
                                Debug.WriteLine("Captcha detected...");
                                if (Settings.Get <bool>("UseTorProxies"))
                                {
                                    await torProxy.GetNewIdentityAsync();

                                    mf.metroLabel45.Text   = Convert.ToString(await WebUtils.GetCurrentIpAddressAsync(torSettings));
                                    Proxies.TorProxyActive = true;
                                    if (!Settings.Get <bool>("ProxyAlwaysActive") && Proxies.RealIPnexttime < DateTime.Now)
                                    {
                                        Proxies.RealIPnexttime = DateTime.Now.AddMinutes(15);
                                    }
                                }
                                continue;
                            }

                            //How many WHD Sites?
                            Match sitesNumber = Regex.Match(sourcecode, "<a name=\"Used\">([^\"]*) / ([^\"]*)</a>");
                            if (sitesNumber.Success && loops == 0 && Settings.Get <int>("ScanMethod") == 0)
                            {
                                sites = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(sitesNumber.Groups[2].Value) / 10));
                            }
                            mf.metroLabel41.Text = $@"{loops + 1} / {sites} (GEBRAUCHT)";

                            //Get Price for WHDs
                            //.de WHD Seller ID: A8KICS1PHF7ZO
                            //.it WHD Seller ID: A1HO9729ND375Y
                            //.fr WHD Seller ID: A2CVHYRTWLQO9T
                            //.es WHD Seller ID: A6T89FGPU3U0Q
                            //.co.uk WHD Seller ID: A2OAJ7377F756P

                            if (sellerForUsed.Contains("Amazon"))
                            {
                                foreach (var condition in conditionList)
                                {
                                    Regex search =
                                        new Regex(
                                            @"<a href=(.*)(A8KICS1PHF7ZO|A1HO9729ND375Y|A2CVHYRTWLQO9T|A6T89FGPU3U0Q|A2OAJ7377F756P)(.*)>(" + condition.Item2 + ") - (EUR |£)(.*)</a>",
                                            RegexOptions.Compiled);
                                    foreach (Match itemMatch in search.Matches(sourcecode))
                                    {
                                        condition.Item1.Add(await CurrencyConverter.ConvertToEuro(itemMatch.Groups[6].Value, Convert.ToString(entry["Store"])));
                                    }
                                }
                            }
                            if (sellerForUsed.Contains("Drittanbieter"))
                            {
                                if (sellerForUsed.Contains("Versand per Amazon"))
                                {
                                    foreach (var condition in conditionList)
                                    {
                                        Regex search =
                                            new Regex(
                                                "(Versand durch Amazon.de|Spedito da Amazon|EXPÉDIÉ PAR AMAZON|Distribuido por Amazon|Fulfilled by Amazon)(\r\n|\r|\n)</font>(\r\n|\r|\n)(\r\n|\r|\n)<br />(\r\n|\r|\n)(\r\n|\r|\n)(\r\n|\r|\n)" +
                                                "<a href=(.*)&me=(?!(A8KICS1PHF7ZO|A1HO9729ND375Y|A2CVHYRTWLQO9T|A6T89FGPU3U0Q|A2OAJ7377F756P).)(.*)>(" + condition.Item2 + ") - (EUR |£)(.*)</a>",
                                                RegexOptions.Compiled);
                                        foreach (Match itemMatch in search.Matches(sourcecode))
                                        {
                                            condition.Item1.Add(await CurrencyConverter.ConvertToEuro(itemMatch.Groups[13].Value, Convert.ToString(entry["Store"])));
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (var condition in conditionList)
                                    {
                                        Regex search =
                                            new Regex(
                                                @"<a href=(.*)&me=(?!(A8KICS1PHF7ZO|A1HO9729ND375Y|A2CVHYRTWLQO9T|A6T89FGPU3U0Q|A2OAJ7377F756P).)(.*)>(" + condition.Item2 + ") - (EUR |£)(.*)</a>",
                                                RegexOptions.Compiled);
                                        foreach (Match itemMatch in search.Matches(sourcecode))
                                        {
                                            condition.Item1.Add(await CurrencyConverter.ConvertToEuro(itemMatch.Groups[6].Value, Convert.ToString(entry["Store"])));
                                        }
                                    }
                                }
                            }
                            loops++;
                            if (sites > loops)
                            {
                                await Task.Delay(Tools.RandomNumber(Convert.ToInt32(mf.numericUpDown3.Value) * 1000 - 500, Convert.ToInt32(mf.numericUpDown3.Value) * 1000 + 500), cancelToken).ContinueWith(tsk => { });
                            }
                        } while (sites > loops);

                        foreach (var condition in conditionList)
                        {
                            RemoveInvalidEntrys(condition.Item1);
                        }
                        priceLikeNew = priceLikeNewList.OrderBy(price => price).FirstOrDefault();
                        if (!String.IsNullOrEmpty(priceLikeNew))
                        {
                            mf.metroLabel25.Text = priceLikeNew;
                            ComparePrice(entry["Preis: Wie Neu"], priceLikeNew, mf.metroLabel25);
                        }
                        priceVeryGood = priceVeryGoodList.OrderBy(price => price).FirstOrDefault();
                        if (!String.IsNullOrEmpty(priceVeryGood))
                        {
                            mf.metroLabel26.Text = priceVeryGood;
                            ComparePrice(entry["Preis: Sehr Gut"], priceVeryGood, mf.metroLabel26);
                        }
                        priceGood = priceGoodList.OrderBy(price => price).FirstOrDefault();
                        if (!String.IsNullOrEmpty(priceGood))
                        {
                            mf.metroLabel27.Text = priceGood;
                            ComparePrice(entry["Preis: Gut"], priceGood, mf.metroLabel27);
                        }
                        priceAcceptable = priceAcceptableList.OrderBy(price => price).FirstOrDefault();
                        if (!String.IsNullOrEmpty(priceAcceptable))
                        {
                            mf.metroLabel28.Text = priceAcceptable;
                            ComparePrice(entry["Preis: Akzeptabel"], priceAcceptable, mf.metroLabel28);
                        }
                    }
                    await Task.Delay(Tools.RandomNumber(500, 1000), cancelToken).ContinueWith(tsk => { });

                    Database.OpenConnection();
                    SQLiteCommand updateEntry =
                        new SQLiteCommand(
                            "UPDATE Products SET [Preis: Neu] = @priceNew, [Preis: Wie Neu] = @priceLikenew, [Preis: Sehr Gut] = @priceVerygood, [Preis: Gut] = @priceGood, [Preis: Akzeptabel] = @priceAcceptable, [Letzter Check] = @lastcheck WHERE ID = @id",
                            Database.Connection);
                    updateEntry.Parameters.AddWithValue("@id", entry["ID"]);
                    updateEntry.Parameters.AddWithValue("@priceNew", !String.IsNullOrEmpty(priceNew) ? priceNew : null);
                    updateEntry.Parameters.AddWithValue("@priceLikenew", !String.IsNullOrEmpty(priceLikeNew) ? priceLikeNew : null);
                    updateEntry.Parameters.AddWithValue("@priceVerygood", !String.IsNullOrEmpty(priceVeryGood) ? priceVeryGood : null);
                    updateEntry.Parameters.AddWithValue("@priceGood", !String.IsNullOrEmpty(priceGood) ? priceGood : null);
                    updateEntry.Parameters.AddWithValue("@priceAcceptable", !String.IsNullOrEmpty(priceAcceptable) ? priceAcceptable : null);
                    updateEntry.Parameters.AddWithValue("@lastcheck", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateEntry.ExecuteNonQuery();

                    await Task.Delay(250, cancelToken).ContinueWith(tsk => { });

                    if (mf.metroComboBox2.SelectedIndex == -1 || mf.metroComboBox2.Text == "ALLE" || store == mf.metroComboBox2.Text)
                    {
                        ProductDatabase.Display(mf.metroComboBox2.SelectedIndex == -1 ? "ALLE" : mf.metroComboBox2.Text);
                    }


                    await MyReminder.DoRemindWhenPossible(Convert.ToString(entry["ID"]));


                    _randomWait = Tools.RandomNumber(Convert.ToInt32(mf.numericUpDown2.Value) - 1, Convert.ToInt32(mf.numericUpDown2.Value) + 1);
                    mf.metroProgressBar1.Value   = 0;
                    mf.metroProgressBar1.Maximum = _randomWait * 1000;
                    Timer.Start();
                    mf.metroLabel29.Text = _dt.AddSeconds(_randomWait).ToString("mm:ss");

                    await Task.Delay((_randomWait + 1) * 1000, cancelToken).ContinueWith(tsk => { });
                }
            }
        }
Beispiel #45
0
 public int minimumDistance(int numRows, int numColumns, int[,] area)
 {
     return(Amazon.minimumDistance(numColumns, numColumns, area));
 }
 /// <summary>
 /// Converts to mobile analytics model event. <see cref="Amazon.MobileAnalytics.Model.Event"/>
 /// </summary>
 /// <returns>The to mobile analytics model event.</returns>
 /// <param name="session">Session.</param>
 public override Amazon.MobileAnalytics.Model.Event ConvertToMobileAnalyticsModelEvent(Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session session)
 {
     if(Quantity != null)
     {
         this.AddMetric(PURCHASE_EVENT_QUANTITY_METRIC,Convert.ToDouble(Quantity));
     }
     
     if(ItemPrice != null)
     {
         this.AddMetric(PURCHASE_EVENT_ITEM_PRICE_METRIC,Convert.ToDouble(ItemPrice));
     }
     
     if(!string.IsNullOrEmpty(ProductId))
     {
         this.AddAttribute(PURCHASE_EVENT_PRODUCT_ID_ATTR,ProductId);
     }
     
     if(!string.IsNullOrEmpty(ItemPriceFormatted))
     {
         this.AddAttribute(PURCHASE_EVENT_ITEM_PRICE_FORMATTED_ATTR,ItemPriceFormatted);
     }
     
     if(!string.IsNullOrEmpty(Store))
     {
         this.AddAttribute(PURCHASE_EVENT_STORE_ATTR,Store);
     }
     
     if(!string.IsNullOrEmpty(TransactionId))
     {
         this.AddAttribute(PURCHASE_EVENT_TRANSACTION_ID_ATTR,TransactionId);
     }
     
     if(!string.IsNullOrEmpty(Currency))
     {
         this.AddAttribute(PURCHASE_EVENT_CURRENCY_ATTR,Currency);
     }
     
     return base.ConvertToMobileAnalyticsModelEvent(session);
 }
 public RestoreDBInstanceToPointInTimeResponse WithResponseMetadata(Amazon.RDS.Model.ResponseMetadata responseMetadata)
 {
     this.responseMetadataField = responseMetadata;
     return this;
 }
 public CreateCustomerGatewayResponse WithCreateCustomerGatewayResult(Amazon.EC2.Model.CreateCustomerGatewayResult createCustomerGatewayResult)
 {
     this.createCustomerGatewayResultField = createCustomerGatewayResult;
     return this;
 }
 public GetPasswordDataResponse WithResponseMetadata(Amazon.EC2.Model.ResponseMetadata responseMetadata)
 {
     this.responseMetadataField = responseMetadata;
     return this;
 }
        public async Task <IActionResult> AddItem(string itemLink, Guid needId)
        {
            var AuthenticatedUserId = Guid.Parse(User.Identity.GetUserId());

            var Need = await Context.Need.Where(x => x.Id == needId &&
                                                x.UserId == AuthenticatedUserId &&
                                                !x.IsRemoved &&
                                                x.NeedItem.Count() < maxItemCount).FirstOrDefaultAsync();

            if (Need != null)
            {
                if (Need.Stage == 1)
                {
                    if (itemLink.Contains("udemy.com"))
                    {
                        Udemy Udemy = new Udemy();
                        Udemy = Udemy.Product(itemLink);
                        if (Udemy.Error == null)
                        {
                            await AddNeedItem(Need.Id, Udemy.Link, Udemy.Name, Udemy.Price, "/image/udemy.png", "Udemy").ConfigureAwait(false);

                            return(Succes(null, Udemy, 201));
                        }
                        else
                        {
                            Logger.LogError("Udemy Error:{error}, Link:{link}", Udemy.Error, itemLink);
                            return(Error(Udemy.Error));
                        }
                    }
                    else if (itemLink.Contains("amazon.com.tr"))
                    {
                        Amazon Amazon = new Amazon();
                        Amazon = Amazon.Product(itemLink);
                        if (Amazon.Error == null)
                        {
                            await AddNeedItem(Need.Id, Amazon.Link, Amazon.Name, Amazon.Price, "/image/amazon.png", "Amazon").ConfigureAwait(false);

                            return(Succes(null, Amazon, 201));
                        }
                        else
                        {
                            Logger.LogError("Amazon Error:{error}, Link:{link}", Amazon.Error, itemLink);
                            return(Error(Amazon.Error));
                        }
                    }
                    else if (itemLink.Contains("pandora.com.tr"))
                    {
                        if (itemLink.ToLower().Contains("/kitap/"))
                        {
                            Pandora Pandora = new Pandora();
                            Pandora = Pandora.Product(itemLink);
                            if (Pandora.Error == null)
                            {
                                await AddNeedItem(Need.Id, Pandora.Link, Pandora.Name, Pandora.Price, Pandora.Picture, "Pandora").ConfigureAwait(false);

                                return(Succes(null, Pandora, 201));
                            }
                            else
                            {
                                Logger.LogError("Pandora Error:{error}, Link:{link}", Pandora.Error, itemLink);
                                return(Error(Pandora.Error));
                            }
                        }

                        return(Error("Pandora.com.tr'den sadece kitap seçebilirsiniz"));
                    }

                    return(Error("İhtiyaç duyduğunuz ürünü seçerken desteklenen platformları kullanın"));
                }

                return(Error("Bu kampanyada değişiklik yapamazsın", "Stage must be 1"));
            }

            return(Error("Kampanyanıza ulaşamadık, tekrar deneyin", "There is no campaign to add new item", null, 404));
        }
Beispiel #51
0
        public async Task GenerateNewFormatData(IProgressBar progress, CancellationToken token)
        {
            try
            {
                await _dataSource.GetExtras(curBook, token, progress);

                curBook.nextInSeries = await _dataSource.GetNextInSeries(curBook, _authorProfile, _settings.AmazonTld);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404)"))
                {
                    Logger.Log("An error occurred finding next book in series: Goodreads URL not found.\r\n" +
                               "If reading from a file, you can switch the source to Goodreads to specify a URL, then switch back to File.");
                }
                else
                {
                    Logger.Log("An error occurred finding next book in series: " + ex.Message + "\r\n" + ex.StackTrace);
                }
                throw;
            }

            // TODO: Refactor next/previous series stuff
            if (curBook.nextInSeries == null)
            {
                try
                {
                    var seriesResult = await Amazon.DownloadNextInSeries(curBook.asin);

                    switch (seriesResult?.Error?.ErrorCode)
                    {
                    case "ERR004":
                        Logger.Log("According to Amazon, this book is not part of a series.");
                        break;

                    case "ERR000":
                        curBook.nextInSeries =
                            new BookInfo(seriesResult.NextBook.Title.TitleName,
                                         Functions.FixAuthor(seriesResult.NextBook.Authors.FirstOrDefault()?.AuthorName),
                                         seriesResult.NextBook.Asin);
                        // TODO: AmazonURL should be a property on the book itself, not passed in like this, and probably generated
                        curBook.nextInSeries.amazonUrl = $"https://www.amazon.com/dp/{curBook.nextInSeries.asin}";
                        await curBook.nextInSeries.GetAmazonInfo(curBook.nextInSeries.amazonUrl);

                        break;
                    }
                }
                catch
                {
                    // Ignore
                }
            }

            try
            {
                if (!(await _dataSource.GetPageCount(curBook)))
                {
                    if (!Properties.Settings.Default.pageCount)
                    {
                        Logger.Log("No page count found on Goodreads");
                    }
                    Logger.Log("Attempting to estimate page count...");
                    Logger.Log(Functions.GetPageCount(curBook.rawmlPath, curBook));
                }
            }
            catch (Exception ex)
            {
                Logger.Log("An error occurred while searching for or estimating the page count: " + ex.Message + "\r\n" + ex.StackTrace);
                throw;
            }
        }
Beispiel #52
0
        public void ExcelGenerator()
        {
            FileInfo file = new FileInfo(path);
            long?    skuID;
            int      execption = 0;

            try
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];

                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                    int row      = 0;

                    for (row = 1; row <= rowCount + 1; row++)
                    {
                        execption++;

                        if (row == 1)
                        {
                            worksheet.Cells[row, 1].Value  = "sku";
                            worksheet.Cells[row, 2].Value  = "product-id";
                            worksheet.Cells[row, 3].Value  = "product-id-type";
                            worksheet.Cells[row, 4].Value  = "price";
                            worksheet.Cells[row, 5].Value  = "minimum-seller-allowed-price";
                            worksheet.Cells[row, 6].Value  = "maximum-seller-allowed-price";
                            worksheet.Cells[row, 7].Value  = "item-condition";
                            worksheet.Cells[row, 8].Value  = "quantity";
                            worksheet.Cells[row, 9].Value  = "add-delete";
                            worksheet.Cells[row, 10].Value = "will-ship-internationally";
                            worksheet.Cells[row, 11].Value = "expedited-shipping";
                            worksheet.Cells[row, 12].Value = "standard-plus";
                            worksheet.Cells[row, 13].Value = "item-note";
                            worksheet.Cells[row, 14].Value = "binding";
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(worksheet.Cells[row, 1].Value?.ToString()))
                            {
                                // if the first row is a perfume/Cologne
                                string rowSku   = worksheet.Cells[row, 1].Value.ToString();
                                long?  digitSku = DigitGetter(rowSku);
                                //double rowPrice = Convert.ToDouble(worksheet.Cells[row, price].Value);
                                string asin = worksheet.Cells[row, 2].Value.ToString();

                                if (isInDB(asin))
                                {
                                    amazonPrintList.RemoveAll(x => x.Asin == asin);
                                }
                                else
                                {
                                    double sellingPrice = 0.0;
                                    // Add to the dictionary
                                    if (isFragrancex(digitSku))
                                    {
                                        if (!isInDB(asin))
                                        {
                                            Amazon amazon = new Amazon();
                                            amazon.id   = ++AmazonCount;
                                            amazon.Asin = asin;
                                            skuID       = DigitGetter(rowSku);
                                            //if(skuID == 0)
                                            amazon.sku         = skuID.ToString();
                                            amazon.price       = Convert.ToDouble(worksheet.Cells[row, 3].Value);
                                            amazon.wholesaler  = Wholesalers.Fragrancex.ToString();
                                            amazon.blackList   = false;
                                            amazon.marketPlace = marketPlace.ToString();
                                            amazonList.Add(amazon);
                                        }
                                    }
                                    else if (isAzImporter(rowSku))
                                    {
                                        if (!isInDB(asin))
                                        {
                                            Amazon amazon = new Amazon();

                                            amazon.id          = ++AmazonCount;
                                            amazon.Asin        = asin;
                                            sellingPrice       = getSellingPrice();
                                            amazon.sku         = azImporter.Sku.ToUpper();
                                            amazon.price       = Convert.ToDouble(worksheet.Cells[row, 3].Value);
                                            amazon.wholesaler  = Wholesalers.AzImporter.ToString();
                                            amazon.blackList   = false;
                                            amazon.marketPlace = marketPlace.ToString();
                                            amazonList.Add(amazon);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    worksheet.DeleteRow(2, rowCount);

                    row = 2;

                    foreach (Amazon list in amazonPrintList.Where(x => x.blackList == false).OrderBy(x => x.wholesaler))
                    {
                        Random rnd   = new Random();
                        Random rnd2  = new Random();
                        double rand3 = Convert.ToDouble(rnd2.Next(1, 99)) / 100;
                        worksheet.Cells[row, 1].Value  = list.sku + " " + rnd.Next(1, 49999);
                        worksheet.Cells[row, 2].Value  = list.Asin;
                        worksheet.Cells[row, 3].Value  = 1;
                        worksheet.Cells[row, 4].Value  = list.price + rand3;
                        worksheet.Cells[row, 5].Value  = "delete";
                        worksheet.Cells[row, 6].Value  = "delete";
                        worksheet.Cells[row, 7].Value  = 11;
                        worksheet.Cells[row, 8].Value  = 0;
                        worksheet.Cells[row, 9].Value  = "a";
                        worksheet.Cells[row, 10].Value = "n";
                        worksheet.Cells[row, 14].Value = "unknown_binding";
                        row++;
                    }

                    package.Save();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public RebootDBInstanceResult WithDBInstance(Amazon.RDS.Model.DBInstance DBInstance)
 {
     this.DBInstanceField = DBInstance;
     return this;
 }
Beispiel #54
0
        public async Task <JsonResult> NeedItemsPriceAndStatus(Guid needId) //checking and correcting needitem status, price.
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            var Need = await Context.Need.Include(need => need.NeedItem).FirstOrDefaultAsync(x => x.Id == needId && !x.IsRemoved);

            bool IsPageNeedRefresh = false;

            if (Need != null && Need.ShouldBeCheck)
            {
                Need.IsWrong = false; //need önceden hatalı olarak işaretlenmiş olabilir her ihtimale karşı hatasının gitmiş olabileceğini var sayarak,
                                      //false'lıyoruz eğer ki hala hatalıysa zaten tekrar hatalı olarak işaretlenecektir.
                var NeedItems = Need.NeedItem.Where(x => !x.IsRemoved).ToList();

                decimal TotalCharge = 0;
                foreach (var item in NeedItems)
                {
                    item.IsWrong = false;   //item önceden hatalı olarak işaretlenmiş olabilir her ihtimale karşı hatasının gitmiş olabileceğini var sayarak,
                                            //false'lıyoruz eğer ki hala hatalıysa zaten tekrar hatalı olarak işaretlenecektir.
                    if (item.PlatformName == "Amazon")
                    {
                        var Amazon = new Amazon();
                        Amazon = Amazon.Product(item.Link);

                        if (Amazon.Error == null)                    // herhangi bir hata yoksa
                        {
                            if (item.Price != (decimal)Amazon.Price) //ürünün amazon sisteminde ki fiyatı ile veritabanında ki fiyatı eşleşmiyorsa
                            {
                                IsPageNeedRefresh = true;
                                item.Price        = (decimal)Amazon.Price; //item'a yeni fiyatını al.
                            }
                        }
                        else // hatalı ise ürünü ve kampanyayı hatalı olarak işaretliyoruz, hatalı işaretlenen durumlar kontrol edilmesi için panelde görüntülenecek.
                        {
                            item.IsWrong = true;
                            Need.IsWrong = true;
                        }
                    }
                    else if (item.PlatformName == "Pandora")
                    {
                        var Pandora = new Pandora();
                        Pandora = Pandora.Product(item.Link);

                        if (Pandora.Error == null)
                        {
                            if (item.Price != (decimal)Pandora.Price)
                            {
                                IsPageNeedRefresh = true;
                                item.Price        = (decimal)Pandora.Price;
                            }
                        }
                        else
                        {
                            item.IsWrong = true;
                            Need.IsWrong = true;
                        }
                    }
                    else
                    {
                        var Udemy = new Udemy();
                        Udemy = Udemy.Product(item.Link);
                        //udemy fiyatı ile ilgili sorun var. sabit bir değer atılıyor, fiyat değişikliğini kontrol etmeye gerek yok.
                        if (Udemy.Error != null)
                        {
                            item.IsWrong = true;
                            Need.IsWrong = true;
                        }
                    }

                    TotalCharge += item.Price; //fiyat değişikliği kontrol edilip güncellenmesi gerekiyorsa güncellendikten sonra ki fiyatını almalıyız ki totalcharge'i da güncelleyebilelim.
                }

                if (!Need.IsWrong && Need.TotalCharge != TotalCharge) //kampanya hatalı olarak işaretlendiyse totalcharge güncellemesi yaptırmıyoruz.
                {
                    IsPageNeedRefresh = true;
                    Need.TotalCharge  = TotalCharge;
                }
                Need.LastCheckOn = DateTime.Now;

                await Context.SaveChangesAsync(); //değiştirilen bütün verileri sadece bir kere kaydediyoruz.
            }
            return(Json(new { IsPageNeedRefresh }));
        }
 public CreateCustomerGatewayResponse WithResponseMetadata(Amazon.EC2.Model.ResponseMetadata responseMetadata)
 {
     this.responseMetadataField = responseMetadata;
     return this;
 }
Beispiel #56
0
        public static void Main(string[] args)
        {
#if singleton
            //Singleton Pattern
            Player p1 = Player.Instance;
            Console.WriteLine($"Name = {p1.Name}, Lvl = {p1.Level}");
#endif

#if factory
            //Factory Pattern
            Gameboard gb = new Gameboard();
            gb.PlayArea(1);
#endif

#if strategy
            //Strategy Pattern
            ShoppingCart cart1 = new ShoppingCart(new TenPercentDiscountStrategy());
            cart1.CustomerName = "John Doe";
            cart1.BillAmount   = 100;
            Console.WriteLine($"Customer = {cart1.CustomerName}, Bal = ${cart1.GetFinalBill()}");

            ShoppingCart cart2 = new ShoppingCart(new FiftyPercentDiscountStrategy());
            cart2.CustomerName = "Jack Wilson";
            cart2.BillAmount   = 200;
            Console.WriteLine($"Customer = {cart2.CustomerName}, Bal = ${cart2.GetFinalBill()}");
#endif

#if chainofresponsibility
            //Chain of responsibility
            Material material = new Material
            {
                MaterialID    = Guid.NewGuid(),
                Name          = "Pebbles",
                PartNumber    = "234",
                DrawingNumber = "345",
                Budget        = 100000
            };

            Approver engineer   = new EngineeringApprover();
            Approver purchasing = new PurchasingApprover();
            Approver finance    = new FinanceApprover();

            engineer.SetNextApprover(purchasing);
            purchasing.SetNextApprover(finance);

            string reason = "";
            if (engineer.ApproveMaterial(material, ref reason))
            {
                Console.WriteLine($"Approved. {reason}");
            }
            else
            {
                Console.WriteLine($"Disapproved. Reason: {reason}");
            }
#endif

#if observer
            Amazon   amzn = new Amazon(1752.12);
            Investor joe  = new Investor("Joe");
            joe.BuyStock(amzn);

            amzn.PriceChanged(1800.12);
#endif

#if adapter
            CustomerDTO customerDTO = new CustomerDTO
            {
                ID         = 1,
                FirstName  = "John",
                LastName   = "Doe",
                Address    = "123 Main St",
                City       = "Portland",
                State      = "OR",
                PostalCode = "12345"
            };

            ICustomerList customerList = new CustomerAdapter();
            customerList.AddCustomer(customerDTO);

            List <Customer> c = customerList.GetCustomers();
#endif

#if COI
#endif
            //Do not delete
            Console.ReadKey();
        }
 public RestoreDBInstanceToPointInTimeResponse WithRestoreDBInstanceToPointInTimeResult(Amazon.RDS.Model.RestoreDBInstanceToPointInTimeResult restoreDBInstanceToPointInTimeResult)
 {
     this.restoreDBInstanceToPointInTimeResultField = restoreDBInstanceToPointInTimeResult;
     return this;
 }
        private async Task Import(string store, string wishlist, int status = 2)
        {
            Main mf = Application.OpenForms["Main"] as Main;

            string reveal = null;

            switch (status)
            {
            case 0:
                reveal = "all";
                break;

            case 1:
                reveal = "purchased";
                break;

            case 2:
                reveal = "unpurchased";
                break;
            }
            string result = await new BetterWebClient {
                Timeout = 15000
            }.DownloadStringTaskAsync(new Uri(
                                          "https://tools.dealreminder.de/wish-lister/wishlist.php?tld=" +
                                          Amazon.GetTld(store) + "&id=" + wishlist + "&reveal=" + reveal +
                                          "&format=json"));
            dynamic jsonObj = JsonConvert.DeserializeObject(result);

            if (jsonObj == null)
            {
                metroLabel1.Text = @"Fehler beim Abrufen der Wunschliste. Falsche ID? Nicht Öffentlicht?";
                return;
            }
            Dictionary <string, string> resultList = new Dictionary <string, string>();

            foreach (var obj in jsonObj)
            {
                resultList.Add(Convert.ToString(obj.ASIN), Convert.ToString(obj.name));
            }
            foreach (var item in resultList.ToList())
            {
                Database.OpenConnection();
                SQLiteCommand checkEntry = new SQLiteCommand(
                    "SELECT COUNT(*) FROM Products WHERE Store = @store AND [ASIN / ISBN] = @asin_isbn",
                    Database.Connection);
                checkEntry.Parameters.AddWithValue("@store", store);
                checkEntry.Parameters.AddWithValue("@asin_isbn", item.Key);
                int entryExist = Convert.ToInt32(checkEntry.ExecuteScalar());
                if (entryExist > 0)
                {
                    resultList.Remove(item.Key);
                }
            }
            if (!resultList.Any())
            {
                metroLabel1.Text = @"Alle Produkte dieser Wunschliste bereits in der Datenbank vorhanden.";
                return;
            }
            foreach (var item in resultList)
            {
                string asin_isbn = item.Key;
                string name      = item.Value;
                var    shortUrl  = await URLShortener.Generate(Amazon.MakeReferralLink(store, asin_isbn), name, store);

                if (shortUrl == null)
                {
                    continue;
                }
                Database.OpenConnection();
                SQLiteCommand insertEntry =
                    new SQLiteCommand(
                        "INSERT INTO Products (Store, [ASIN / ISBN], Name, URL) Values (@store, @asin_isbn, @name, @shorturl)",
                        Database.Connection);
                insertEntry.Parameters.AddWithValue("@store", store);
                insertEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn);
                insertEntry.Parameters.AddWithValue("@name", name);
                insertEntry.Parameters.AddWithValue("@shorturl", shortUrl);
                insertEntry.ExecuteNonQuery();
            }
            ProductDatabase.Display(mf.metroComboBox2.SelectedIndex == -1 ? "ALLE" : mf.metroComboBox2.Text);
            this.Close();
        }
        public async Task AddItem(string ItemLink, long NeedId)
        {
            var Need = await Context.Need.Where(x => x.Id == NeedId &&
                                                !x.IsRemoved &&
                                                !x.IsSentForConfirmation &&
                                                x.NeedItem.Where(a => a.IsRemoved != true).Count() < 3) // en fazla 3 tane item(ihtiyaç) ekleyebilir.
                       .FirstOrDefaultAsync();

            // Kampanya(need) onaylanma için yollandıysa bir item ekleyemecek: onaylanma için gönderdiyse
            //(completed ve confirmed kontrol etmeye gerek yok çünkü onaylandıysa veya bittiyse de isSentForConfirmation hep true kalacak.)
            if (Need != null)
            {
                AuthUser = await GetAuthenticatedUserFromDatabaseAsync();

                if (Need.UserId == AuthUser.Id) //item(ihtiyaç) eklemeye çalıştığı kampanya Authenticated olmuş üzere aitse..
                {
                    if (ItemLink.ToLower().Contains("udemy.com"))
                    {
                        Udemy Udemy = new Udemy();
                        Udemy = Udemy.Product(ItemLink);
                        if (Udemy.Error == null)
                        {
                            await AddItemOnDBAndFixTotalCharge(Need.Id, Udemy.Link, Udemy.Name, (decimal)Udemy.Price, "/image/udemy.png", "Udemy");
                        }
                        else
                        {
                            Logger.LogError("Udemy Error:{error}, Link:{link}", Udemy.Error, ItemLink);
                            TempData["NeedMessage"] = Udemy.Error;
                        }
                    }
                    else if (ItemLink.ToLower().Contains("pandora.com.tr"))
                    {
                        if (ItemLink.ToLower().Contains("/kitap/"))
                        {
                            Pandora Pandora = new Pandora();
                            Pandora = Pandora.Product(ItemLink);
                            if (Pandora.Error == null)
                            {
                                await AddItemOnDBAndFixTotalCharge(Need.Id, Pandora.Link, Pandora.Name, (decimal)Pandora.Price, Pandora.Picture, "Pandora");
                            }
                            else
                            {
                                Logger.LogError("Pandora Error:{error}, Link:{link}", Pandora.Error, ItemLink);
                                TempData["NeedMessage"] = Pandora.Error;
                            }
                        }
                        else
                        {
                            TempData["MesajHata"] = "Pandora.com.tr'den sadece kitap seçebilirsiniz";
                        }
                    }
                    else if (ItemLink.ToLower().Contains("amazon.com.tr"))
                    {
                        Amazon Amazon = new Amazon();
                        Amazon = Amazon.Product(ItemLink);
                        if (Amazon.Error == null)
                        {
                            await AddItemOnDBAndFixTotalCharge(Need.Id, Amazon.Link, Amazon.Name, (decimal)Amazon.Price, "/image/amazon.png", "Amazon");
                        }
                        else
                        {
                            Logger.LogError("Amazon Error:{error}, Link:{link}", Amazon.Error, ItemLink);
                            TempData["NeedMessage"] = Amazon.Error;
                        }
                    }
                    else
                    {
                        TempData["MesajHata"] = "İhtiyacınızın linkini verirken desteklenen platformları kullanın";
                    }
                    Response.Redirect("/" + Need.User.Username.ToLower() + "/ihtiyac/" + Need.FriendlyTitle + "/" + Need.Id);
                }
            }
        }
Beispiel #60
0
        public static async Task Add(string[] stores, string asin_isbn)
        {
            if (Tools.ArrayIsNullOrEmpty(stores))
            {
                MetroMessageBox.Show(mf,
                                     "Eintrag konnte nicht hinzugefügt werden!" + Environment.NewLine +
                                     "Bitte wähle mind. 1 Store für dieses Produkt aus!", "Eintrag Hinzufügen Fehlgeschlagen",
                                     MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (String.IsNullOrWhiteSpace(asin_isbn))
            {
                MetroMessageBox.Show(mf,
                                     "Eintrag konnte nicht hinzugefügt werden!" + Environment.NewLine +
                                     "Bitte gebe die Produkt ASIN / ISBN ein.!", "Eintrag Hinzufügen Fehlgeschlagen",
                                     MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            foreach (string store in stores)
            {
                Database.OpenConnection();
                SQLiteCommand checkEntry = new SQLiteCommand(
                    "SELECT COUNT(*) FROM Products WHERE Store = @store AND [ASIN / ISBN] = @asin_isbn", Database.Connection);
                checkEntry.Parameters.AddWithValue("@store", store);
                checkEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn);
                int entryExist = Convert.ToInt32(checkEntry.ExecuteScalar());
                if (entryExist > 0)
                {
                    continue;
                }
                AmazonItemResponse itemInfo;
                try
                {
                    itemInfo = await Task.Run(() => AmazonApi.ItemLookup(store, asin_isbn));

                    if (itemInfo.Items == null)
                    {
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Abfrage Fehler: " + ex.Message, LogLevel.Debug);
                    continue;
                }
                if (itemInfo.Items.Request.Errors != null && itemInfo.Items.Request.Errors.Any())
                {
                    foreach (var error in itemInfo.Items.Request.Errors)
                    {
                        Logger.Write("AmazonAPI Abfrage Fehlgeschlagen - Grund: " + error.Message, LogLevel.Debug);
                    }
                    continue;
                }
                string name     = itemInfo.Items.Item[0].ItemAttributes.Title;
                var    shortUrl = await URLShortener.Generate(Amazon.MakeReferralLink(store, asin_isbn), name, store);

                if (shortUrl == null)
                {
                    continue;
                }
                Database.OpenConnection();
                SQLiteCommand insertEntry =
                    new SQLiteCommand(
                        "INSERT INTO Products (Store, [ASIN / ISBN], Name, URL) Values (@store, @asin_isbn, @name, @shorturl)",
                        Database.Connection);
                insertEntry.Parameters.AddWithValue("@store", store);
                insertEntry.Parameters.AddWithValue("@asin_isbn", asin_isbn);
                insertEntry.Parameters.AddWithValue("@name", name);
                insertEntry.Parameters.AddWithValue("@shorturl", shortUrl);
                insertEntry.ExecuteNonQuery();
            }
            mf.metroTextBox1.Clear();
            Display(mf.metroComboBox2.SelectedIndex == -1 ? "ALLE" : mf.metroComboBox2.Text);
        }