private static void FindProductsWithNegativePriceWithConfig(Table productCatalogTable)
        {
            // Assume there is a price error. So we scan to find items priced < 0.
            ScanFilter scanFilter = new ScanFilter();
            scanFilter.AddCondition("Price", ScanOperator.LessThan, 0);

            ScanOperationConfig config = new ScanOperationConfig()
            {
                Filter = scanFilter,
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string> { "Title", "Id" }
            };

            Search search = productCatalogTable.Scan(config);

            List<Document> documentList = new List<Document>();
            do
            {
                documentList = search.GetNextSet();
                Console.WriteLine("\nFindProductsWithNegativePriceWithConfig: printing ............");
                foreach (var document in documentList)
                    PrintDocument(document);
            } while (!search.IsDone);
        }
Esempio n. 2
0
        public async Task <List <Product> > FindAsync(ProductFilterRequest filters, CancellationToken cancellationToken)
        {
            var includedInactive = filters.IncludedInactive ? "" : Status.Active.ToString();

            // Create a filter base a scan condition
            var opConfig = new DynamoDBOperationConfig {
                QueryFilter = new List <ScanCondition>()
            };

            if (!string.IsNullOrWhiteSpace(filters.Description))
            {
                opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.Description), ScanOperator.Contains,
                                                           filters.Description));
            }

            if (filters.ProductType != ProductType.None)
            {
                opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.ProductType), ScanOperator.Contains,
                                                           filters.ProductType));
            }


            if (!filters.IncludedInactive)
            {
                opConfig.QueryFilter.Add(new ScanCondition(nameof(Product.Status), ScanOperator.Equal, Status.Active));
            }


            var sortKey = new List <string>();

            if (filters.ValidityStart.HasValue)
            {
                sortKey.Add(filters.ValidityStart.Value.ToShortDateString());
            }

            if (filters.ValidityEnd.HasValue)
            {
                sortKey.Add(filters.ValidityEnd.Value.ToShortDateString());
            }


            // When partition key exists !
            if (!string.IsNullOrWhiteSpace(filters.Manufacturer))
            {
                // query filters use in a filter by composite key
                var queryFilter = new QueryFilter();

                queryFilter.AddCondition(nameof(Product.PartitionKey), QueryOperator.Equal, filters.Manufacturer);

                if (sortKey.Any())
                {
                    queryFilter.AddCondition(nameof(Product.SortKey), QueryOperator.BeginsWith,
                                             string.Join("#", sortKey));
                }

                // Use scan condition and query filter (filter by primary key)
                return(await Context.FromQueryAsync <Product>(new QueryOperationConfig
                {
                    Filter = queryFilter,
                    Limit = filters.Take
                }, opConfig).GetRemainingAsync(cancellationToken));
            }

            // Table scan !! scan condition shouldn't contain a primary key
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition(nameof(Product.SortKey), ScanOperator.BeginsWith, string.Join("#", sortKey));

            return(await Context.FromScanAsync <Product>(new ScanOperationConfig
            {
                Limit = 10
            }, opConfig).GetRemainingAsync(cancellationToken));
        }
        public async Task <ResponseModel <List <UserServicesItem> > > GetAsync(SearchParam fipso, SecurityModel securityModel)
        {
            ResponseModel <List <UserServicesItem> > response = new ResponseModel <List <UserServicesItem> >();

            try
            {
                PagingInfo paging = new PagingInfo();
                paging.CurrentPage    = fipso.CurrentPage;
                paging.PageSize       = fipso.PageSize;
                paging.SortDirection  = fipso.SortDirection;
                paging.SortExpression = fipso.SortExpression;

                ScanFilter filter = new ScanFilter();
                switch (fipso.Status)
                {
                case "Rejected":
                    filter.AddCondition("RequestStatus", ScanOperator.Equal, "Rejected");
                    break;

                case "Approved":
                    filter.AddCondition("RequestStatus", ScanOperator.Equal, "Approved");
                    break;

                default:
                    filter.AddCondition("RequestStatus", ScanOperator.Equal, "Requested");
                    break;
                }

                if (string.IsNullOrEmpty(fipso.SortExpression))
                {
                    fipso.SortExpression = "SubmittedOn";
                }
                if (paging.SortDirection != string.Empty)
                {
                    fipso.SortExpression = fipso.SortExpression + " " + paging.SortDirection;
                }
                int rows = 0;
                IEnumerable <UserServicesItem> requestedItem = await _dynamodbContext.GetAsync(filter);

                var filterData = new List <UserServicesItem>();
                if (!string.IsNullOrEmpty(fipso.SearchText))
                {
                    filterData = requestedItem.Where(x => x.BookName.ToLower().Contains(fipso.SearchText.ToLower()) ||
                                                     x.BookAuthor.ToLower().Contains(fipso.SearchText) ||
                                                     x.UserName.ToLower().Contains(fipso.SearchText)
                                                     ).ToList();
                }
                else
                {
                    filterData = requestedItem.ToList();
                }
                var resultList = from p in filterData.AsQueryable() select p;
                rows = resultList.Count();

                var requestedBookList = resultList.OrderBy(fipso.SortExpression).Skip((paging.CurrentPage - 1) * paging.PageSize).Take(paging.PageSize).ToList();
                paging.TotalRows  = rows;
                paging.TotalPages = Functions.CalculateTotalPages(rows, paging.PageSize);

                response.Entity     = requestedBookList;
                response.TotalRows  = paging.TotalRows;
                response.TotalPages = paging.TotalPages;
                response.Status     = true;
            }
            catch (AmazonServiceException amazonEx)
            {
                response.Status = false;
                response.ReturnMessage.Add($"Amazon error in table operation! Error: {amazonEx.Message}");
            }
            catch (System.Exception ex)
            {
                response.Status = false;
                response.ReturnMessage.Add(ex.Message);
            }
            return(response);
        }
Esempio n. 4
0
        private void TestHashTable(Table hashTable, DynamoDBEntryConversion conversion)
        {
            // Put an item
            Document doc = new Document();

            doc["Id"]       = 1;
            doc["Product"]  = "CloudSpotter";
            doc["Company"]  = "CloudsAreGrate";
            doc["IsPublic"] = true;
            doc["Price"]    = 1200;
            doc["Tags"]     = new HashSet <string> {
                "Prod", "1.0"
            };
            doc["Aliases"] = new List <string> {
                "CS", "Magic"
            };
            doc["Developers"] = new List <Document>
            {
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Alan" },
                    { "Age", 29 }
                }),
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Franco" },
                    { "Age", 32 }
                })
            };
            doc["Garbage"] = "asdf";
            Assert.AreEqual("asdf", doc["Garbage"].AsString());
            hashTable.PutItem(doc);

            // Get the item by hash key
            Document retrieved = hashTable.GetItem(1);

            Assert.IsFalse(AreValuesEqual(doc, retrieved));
            var convertedDoc = doc.ForceConversion(conversion);

            Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved));

            // Get the item by document
            retrieved = hashTable.GetItem(doc);
            // Verify retrieved document
            Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved, conversion));
            var tagsRetrieved = retrieved["Tags"];

            Assert.IsTrue(tagsRetrieved is PrimitiveList);
            Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count);
            // Test bool storage for different conversions
            var isPublicRetrieved = retrieved["IsPublic"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual("1", isPublicRetrieved.AsPrimitive().Value as string);
            }
            else
            {
                Assert.IsTrue(isPublicRetrieved is DynamoDBBool);
            }
            // Test HashSet<string> storage for different conversions
            var aliasesRetrieved = retrieved["Aliases"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual(2, aliasesRetrieved.AsPrimitiveList().Entries.Count);
            }
            else
            {
                Assert.AreEqual(2, aliasesRetrieved.AsDynamoDBList().Entries.Count);
            }
            List <Document> developers = retrieved["Developers"].AsListOfDocument();

            Assert.AreEqual(2, developers.Count);
            AssertExtensions.ExpectException(() => aliasesRetrieved.AsListOfDocument(), typeof(InvalidCastException));

            // Update the item
            doc["Tags"] = new List <string> {
                "Prod", "1.0", "2.0"
            };
            doc["Developers"] = new DynamoDBList(new List <DynamoDBEntry>
            {
                new Document(new Dictionary <string, DynamoDBEntry>
                {
                    { "Name", "Alan" },
                    { "Age", 29 }
                })
            });
            // Delete the Garbage attribute
            doc["Garbage"] = null;
            Assert.IsNull(doc["Garbage"].AsString());
            hashTable.UpdateItem(doc);
            retrieved = hashTable.GetItem(1);
            Assert.IsFalse(AreValuesEqual(doc, retrieved, conversion));
            doc.Remove("Garbage");
            Assert.IsTrue(AreValuesEqual(doc, retrieved, conversion));
            developers = retrieved["Developers"].AsListOfDocument();
            Assert.AreEqual(1, developers.Count);

            // Create new, circularly-referencing item
            Document doc2 = doc.ForceConversion(conversion);

            doc2["Id"]       = doc2["Id"].AsInt() + 1;
            doc2["Price"]    = 94;
            doc2["Tags"]     = null;
            doc2["IsPublic"] = false;
            doc2["Parent"]   = doc2;
            AssertExtensions.ExpectException(() => hashTable.UpdateItem(doc2));
            // Remove circular reference and save new item
            doc2.Remove("Parent");
            hashTable.UpdateItem(doc2);

            // Scan the hash-key table
            var items = hashTable.Scan(new ScanFilter()).GetRemaining();

            Assert.AreEqual(2, items.Count);

            // Scan by pages
            var search = hashTable.Scan(new ScanOperationConfig {
                Limit = 1
            });

            items.Clear();
            while (!search.IsDone)
            {
                var set = search.GetNextSet();
                items.AddRange(set);
            }
            Assert.AreEqual(2, items.Count);

            // Query against GlobalIndex
            var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate");

            queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100);
            search = hashTable.Query(new QueryOperationConfig
            {
                IndexName = "GlobalIndex",
                Filter    = queryFilter
            });
            items = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Scan for specific tag
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0");
            search = hashTable.Scan(scanFilter);
            items  = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Delete the item by hash key
            hashTable.DeleteItem(1);
            Assert.IsNull(hashTable.GetItem(1));

            // Delete the item by document
            hashTable.DeleteItem(doc2);
            Assert.IsNull(hashTable.GetItem(doc2));

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);

            // Batch-put items
            var batchWrite = hashTable.CreateBatchWrite();

            batchWrite.AddDocumentToPut(doc);
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();

            // Batch-get items
            var batchGet = hashTable.CreateBatchGet();

            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(2, batchGet.Results.Count);

            // Batch-delete items
            batchWrite = hashTable.CreateBatchWrite();
            batchWrite.AddItemToDelete(doc);
            batchWrite.AddKeyToDelete(2);
            batchWrite.Execute();

            // Batch-get non-existent items
            batchGet = hashTable.CreateBatchGet();
            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(0, batchGet.Results.Count);

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);
        }
Esempio n. 5
0
        public async Task <IActionResult> getbook([FromHeader] string Authorization, [FromBody] OrderBook book)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Document searchdetails = new Document();

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (!string.IsNullOrWhiteSpace(doc["DefaultId"]))
                            {
                                if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id)
                                {
                                    Console.WriteLine("successful auth");
                                    searchdetails = doc;
                                    break;
                                }
                            }
                            else
                            {
                                continue;
                            }

                            return(BadRequest("Id not found"));
                        }
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }
                }
                catch
                {
                    return(BadRequest("authorizaion failed"));
                }

                Table orderbooktable;
                if (book.symbol == "SPYUSD")
                {
                    orderbooktable = Table.LoadTable(amazonDynamoDBClient, "OrderBook");
                }
                else
                {
                    return(BadRequest("bad symbol"));
                }
                ScanOperationConfig config = new ScanOperationConfig();
                ScanFilter          filter = new ScanFilter();
                filter.AddCondition("Price", ScanOperator.IsNotNull);
                config.Filter = filter;
                config.AttributesToGet.Add("Price");
                config.AttributesToGet.Add("Volume");
                config.AttributesToGet.Add("Type");

                Search          searchs   = orderbooktable.Scan(config);
                List <Document> orderbook = await searchs.GetRemainingAsync();

                List <ReturnOrderBook> rob = new List <ReturnOrderBook>();

                foreach (Document d in orderbook)
                {
                    rob.Add(new ReturnOrderBook()
                    {
                        Price = d["Price"].ToString(), Volume = d["Volume"].ToString(), Type = d["Type"].ToString()
                    });
                }

                string json = JsonConvert.SerializeObject(rob);
                return(Content(json, "application/json"));
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }
Esempio n. 6
0
        string BuildSnsTopicString(TimeSpan timeTaken)
        {
            AWSXRayRecorder.Instance.BeginSubsegment("Build SNS Topic String");

            StringBuilder sbText = new StringBuilder();



            var strDDBTableName = System.Environment.GetEnvironmentVariable("BatTable");

            Table usageTypeTable = Table.LoadTable(dynamoDBClient.Value, strDDBTableName);

            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("Processed", ScanOperator.Equal, DynamoDBBool.True);
            scanFilter.AddCondition("Triggered", ScanOperator.Equal, DynamoDBBool.True);

            Search search = usageTypeTable.Scan(scanFilter);

            List <Document> documentList = new List <Document>();


            do
            {
                documentList = search.GetRemainingAsync().GetAwaiter().GetResult();

                if (documentList.Count > 0 && sbText.Length == 0)
                {
                    sbText.AppendLine("Billing Anomaly Tracker" + Environment.NewLine);
                }

                foreach (var document in documentList)
                {
                    var usageType        = document["id"].AsString();
                    var averageDaily     = document["AverageDaily"].AsDouble();
                    var previousDay      = document["PreviousDay"].AsDouble();
                    var increaseBy       = document["IncreaseBy"].AsDouble();
                    var strYesterdayDate = document["YesterdayDate"].AsString();
                    var dtYesterdayDate  = DateTime.ParseExact(strYesterdayDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);

                    sbText.AppendLine($"{usageType} - increase by {increaseBy.ToString("P")} - Cost for {dtYesterdayDate.ToString("d MMM yyyy")}: {previousDay.ToString("C")} - Average Daily Cost: {averageDaily.ToString("C")}");

                    foreach (var attribute in document.GetAttributeNames())
                    {
                        string stringValue = null;
                        var    value       = document[attribute];
                        if (value is Primitive)
                        {
                            stringValue = value.AsPrimitive().Value.ToString();
                        }
                        else if (value is PrimitiveList)
                        {
                            stringValue = string.Join(",", (from primitive
                                                            in value.AsPrimitiveList().Entries
                                                            select primitive.Value).ToArray());
                        }
                        LambdaLogger.Log($"{attribute} - {stringValue}");
                    }
                }
            } while (!search.IsDone);

            if (sbText.Length > 0)
            {
                sbText.AppendLine($"Time taken for processing: {timeTaken.ToString(@"d\.hh\:mm\:ss")}");
            }

            AWSXRayRecorder.Instance.EndSubsegment();

            return(sbText.ToString());
        }
Esempio n. 7
0
        public async Task ScanItems()
        {
            try
            {
                #region All items
                var rawDocList = await _table.Scan(new ScanOperationConfig()).GetRemainingAsync();

                var profileList = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile) : new List <Profile>();
                foreach (var item in profileList)
                {
                    Console.WriteLine(item.ToString());
                }
                #endregion

                ScanFilter scanFilter = new ScanFilter();

                #region People lived in ID
                Console.WriteLine("\n#People lived in ID: ");
                scanFilter.AddCondition(nameof(Profile.CountryId), ScanOperator.Equal, "ID");
                rawDocList = await _table.Scan(scanFilter).GetRemainingAsync();

                profileList = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile) : new List <Profile>();
                foreach (var item in profileList)
                {
                    Console.WriteLine(item.ToString());
                }
                #endregion



                #region People which the names start with 'Mi'
                Console.WriteLine("\n#People which the names start with 'Mi': ");
                scanFilter.AddCondition(nameof(Profile.Name), ScanOperator.BeginsWith, "Mi");
                rawDocList = await _table.Scan(scanFilter).GetRemainingAsync();

                profileList = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile) : new List <Profile>();
                foreach (var item in profileList)
                {
                    Console.WriteLine(item.ToString());
                }
                #endregion

                #region People which the names start with 'Mi' and CountryId is 'ID'
                Console.WriteLine("\n#People which the names start with 'Mi' and CountryId is 'ID': ");
                scanFilter.AddCondition(nameof(Profile.CountryId), ScanOperator.Equal, "ID");
                scanFilter.AddCondition(nameof(Profile.Name), ScanOperator.BeginsWith, "Mi");
                rawDocList = await _table.Scan(scanFilter).GetRemainingAsync();

                profileList = rawDocList != null && rawDocList.Count > 0 ? rawDocList.Select(ConvertToProfile) : new List <Profile>();
                foreach (var item in profileList)
                {
                    Console.WriteLine(item.ToString());
                }
                #endregion
            }
            catch (AmazonDynamoDBException ex)
            {
                Console.WriteLine(ex);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// A utility method for cleaning up expired sessions that IIS failed to delete.  The method performs a scan on the table
        /// with a condition that the expiration date is in the past and calls delete on all the keys returned.  Scans can be costly on performance
        /// so use this method sparingly like a nightly or weekly clean job.
        /// </summary>
        /// <param name="dbClient">The AmazonDynamoDB client used to find a delete expired sessions.</param>
        /// <param name="tableName">The table to search.</param>
        public static void DeleteExpiredSessions(AmazonDynamoDB dbClient, string tableName)
        {
            Table table = Table.LoadTable(dbClient, tableName, Table.DynamoDBConsumer.SessionStateProvider);


            ScanFilter filter = new ScanFilter();
            filter.AddCondition(ATTRIBUTE_EXPIRES, ScanOperator.LessThan, DateTime.Now);

            ScanOperationConfig config = new ScanOperationConfig();
            config.AttributesToGet = new List<string>();
            config.AttributesToGet.Add(ATTRIBUTE_SESSION_ID);
            config.Filter = filter;

            Search search = table.Scan(config);

            do
            {
                List<Document> page = search.GetNextSet();
                foreach (var document in page)
                {
                    table.DeleteItem(document);
                }
            } while (!search.IsDone);
        }
Esempio n. 9
0
        public async static Task <bool> DeleteQbyClientGuid(string KeyItem)
        {
            //  The requestQ for the ESP8266 may have more than one unhandled request.  When we get a requestQ object to present to the
            //  8266 we only retrieve the latest.  This procedure is called when the 8266 responds after a requestQ item is processed successfully.
            //  We then delete any unhandled request in the queue.

            string tableName = requestQTableName;

            try
            {
                Table QTable = Table.LoadTable(dbClient, tableName);
                //get the RequestQ items for the ClientGuid
                ScanFilter scanFilter = new ScanFilter();
                scanFilter.AddCondition("ClientGuid", ScanOperator.Equal, KeyItem);
                ScanOperationConfig config = new ScanOperationConfig()
                {
                    Filter    = scanFilter,
                    IndexName = "ClientGuid-index"
                };

                Search          search   = QTable.Scan(scanFilter);
                List <Document> allItems = await search.GetRemainingAsync();

                foreach (Document doc in allItems)
                {
                    string KeytoDelete  = "";
                    string TimetoDelete = "";
                    foreach (string itemkey in doc.Keys)
                    {
                        DynamoDBEntry dbEntry = doc[itemkey];
                        string        val     = dbEntry.ToString();
                        if (itemkey == "ClientGuid")
                        {
                            KeytoDelete = val;
                        }
                        if (itemkey == "time")
                        {
                            TimetoDelete = val;
                        }
                    } // end foreach key

                    Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
                    {
                        { "ClientGuid", new AttributeValue {
                              S = KeytoDelete
                          } },
                        { "time", new AttributeValue {
                              S = TimetoDelete
                          } }
                    };

                    // Create DeleteItem request
                    DeleteItemRequest request = new DeleteItemRequest
                    {
                        TableName = tableName,
                        Key       = key
                    };

                    // Issue request
                    var response = await dbClient.DeleteItemAsync(request);
                } //end foreach document

                return(true);
            }

            catch { return(false); }
        }
Esempio n. 10
0
        public async static Task <List <RequestQ> > FetchQItem(string Key)
        {
            // Functions returns all requestQ items
            string tableName   = requestQTableName;
            Table  ThreadTable = Table.LoadTable(dbClient, tableName);

            List <RequestQ> requests = new List <RequestQ>();

            //get the RequestQ items for the ClientGuid
            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("ClientGuid", ScanOperator.Equal, Key);
            Search search = ThreadTable.Scan(scanFilter);

            try
            {
                //get the request. MobilitySkillsRequestQ has a sort key so we may get more than one
                List <Document> allItems = await search.GetRemainingAsync();

                Document doc = allItems.Last();
                //create a RequestQ object for this request
                RequestQ request = new RequestQ();
                foreach (string key in doc.Keys)
                {
                    DynamoDBEntry dbEntry = doc[key];
                    string        val     = dbEntry.ToString();
                    if (key == "ClientGuid")
                    {
                        request.ClientGuid = val;
                    }
                    if (key == "MessageId")
                    {
                        request.MessageId = val;
                    }
                    if (key == "corelationToken")
                    {
                        request.corelationToken = val;
                    }
                    if (key == "directive")
                    {
                        request.directive = val;
                    }
                    if (key == "endpointId")
                    {
                        request.endpointId = val;
                    }
                    if (key == "time")
                    {
                        request.time = val;
                    }
                    if (key == "secret")
                    {
                        request.secret = val;
                    }
                } //end for loop
                requests.Add(request);

                return(requests);
            } //end try
            catch
            {
                Globals.logger.LogCritical("Exception reading: " + requestQTableName);
                return(requests);
            } //end catch
        }
Esempio n. 11
0
        private void TestHashTable(Table hashTable)
        {
            // Put an item
            Document doc = new Document();

            doc["Id"]      = 1;
            doc["Product"] = "CloudSpotter";
            doc["Company"] = "CloudsAreGrate";
            doc["Price"]   = 1200;
            doc["Tags"]    = new List <string> {
                "Prod", "1.0"
            };
            hashTable.PutItem(doc);

            // Get the item by hash key
            Document retrieved = hashTable.GetItem(1);

            Assert.IsTrue(AreValuesEqual(doc, retrieved));
            // Get the item by document
            retrieved = hashTable.GetItem(doc);
            Assert.IsTrue(AreValuesEqual(doc, retrieved));

            // Update the item
            doc["Tags"] = new List <string> {
                "Prod", "1.0", "2.0"
            };
            hashTable.UpdateItem(doc);
            retrieved = hashTable.GetItem(1);
            Assert.IsTrue(AreValuesEqual(doc, retrieved));

            // Create new item
            Document doc2 = Document.FromAttributeMap(doc.ToAttributeMap());

            doc2["Id"]    = doc2["Id"].AsInt() + 1;
            doc2["Price"] = 94;
            doc2["Tags"]  = null;
            hashTable.UpdateItem(doc2);

            // Scan the hash-key table
            var items = hashTable.Scan(new ScanFilter()).GetRemaining();

            Assert.AreEqual(2, items.Count);

            // Scan by pages
            var search = hashTable.Scan(new ScanOperationConfig {
                Limit = 1
            });

            items.Clear();
            while (!search.IsDone)
            {
                var set = search.GetNextSet();
                items.AddRange(set);
            }
            Assert.AreEqual(2, items.Count);

            // Query against GlobalIndex
            var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate");

            queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100);
            search = hashTable.Query(new QueryOperationConfig
            {
                IndexName = "GlobalIndex",
                Filter    = queryFilter
            });
            items = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Scan for specific tag
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0");
            search = hashTable.Scan(scanFilter);
            items  = search.GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Delete the item by hash key
            hashTable.DeleteItem(1);
            Assert.IsNull(hashTable.GetItem(1));

            // Delete the item by document
            hashTable.DeleteItem(doc2);
            Assert.IsNull(hashTable.GetItem(doc2));

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);

            // Batch-put items
            var batchWrite = hashTable.CreateBatchWrite();

            batchWrite.AddDocumentToPut(doc);
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();

            // Batch-get items
            var batchGet = hashTable.CreateBatchGet();

            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(2, batchGet.Results.Count);

            // Batch-delete items
            batchWrite = hashTable.CreateBatchWrite();
            batchWrite.AddItemToDelete(doc);
            batchWrite.AddKeyToDelete(2);
            batchWrite.Execute();

            // Batch-get non-existent items
            batchGet = hashTable.CreateBatchGet();
            batchGet.AddKey(1);
            batchGet.AddKey(doc2);
            batchGet.Execute();
            Assert.AreEqual(0, batchGet.Results.Count);

            // Scan the hash-key table to confirm it is empty
            items = hashTable.Scan(new ScanFilter()).GetRemaining();
            Assert.AreEqual(0, items.Count);
        }
Esempio n. 12
0
        public void TestStoreAsEpoch(Table hashRangeTable, Table numericHashRangeTable)
        {
            // verify conversions
            var e1 = DateTimeToEpochSeconds((Primitive)EpochDate, "test") as Primitive;

            Assert.IsNotNull(e1);
            Assert.AreEqual(DynamoDBEntryType.Numeric, e1.Type);
            Assert.AreEqual(EpochSeconds, e1.AsInt());

            var e2 = EpochSecondsToDateTime((Primitive)EpochSeconds, "test") as Primitive;

            Assert.IsNotNull(e2);
            Assert.AreEqual(DynamoDBEntryType.String, e2.Type);
            ApproximatelyEqual(EpochDate, e2.AsDateTime());

            // construct tables with StoreAsEpoch
            var config = new TableConfig(hashRangeTable.TableName)
            {
                AttributesToStoreAsEpoch = new List <string> {
                    "CreationTime", "EpochDate2"
                }
            };
            var epochTable = Table.LoadTable(Client, config);

            CollectionAssert.AreEqual(config.AttributesToStoreAsEpoch, epochTable.GetStoreAsEpoch().ToList());

            config = new TableConfig(numericHashRangeTable.TableName)
            {
                AttributesToStoreAsEpoch = new List <string> {
                    "CreationTime", "EpochDate2"
                }
            };
            var numericEpochTable = Table.LoadTable(Client, config);

            CollectionAssert.AreEqual(config.AttributesToStoreAsEpoch, epochTable.GetStoreAsEpoch().ToList());

            // verify ToAttributeMap calls
            var map = hashRangeTable.ToAttributeMap(CreateTestDocument());

            Assert.IsNotNull(map["CreationTime"].S);
            Assert.IsNotNull(map["EpochDate2"].S);
            Assert.IsNotNull(map["NonEpochDate"].S);

            var epochMap = epochTable.ToAttributeMap(CreateTestDocument());

            Assert.IsNotNull(epochMap["CreationTime"].N);
            Assert.IsNotNull(epochMap["EpochDate2"].N);
            Assert.IsNotNull(epochMap["NonEpochDate"].S);

            // put
            epochTable.PutItem(CreateTestDocument());
            TestWrittenData("Bob", 42, hashRangeTable, epochTable);
            numericEpochTable.PutItem(CreateTestDocument());
            // accessing this item with non-epoch table will throw an exception
            TestWrittenData(EpochDate, "Bob", null, numericEpochTable);
            var exception = AssertExtensions.ExpectException <InvalidOperationException>(() => numericHashRangeTable.GetItem(EpochDate, "Bob"));

            Assert.IsTrue(exception.Message.Contains("hash key CreationTime, is inconsistent with specified hash key value."));

            // conditional put
            epochTable.PutItem(CreateTestDocument());
            var newDoc = CreateTestDocument();

            newDoc["ConditionalUpdate"] = "yes";
            var expectedState = new ExpectedState();

            expectedState.AddExpected("CreationTime", ScanOperator.Equal, EpochDate);
            epochTable.PutItem(newDoc, new PutItemOperationConfig {
                ExpectedState = expectedState
            });
            TestWrittenData("Bob", 42, hashRangeTable, epochTable, checkForConditionalUpdate: true);

            // update
            epochTable.UpdateItem(CreateTestDocument());
            TestWrittenData("Bob", 42, hashRangeTable, epochTable);

            // conditional update
            epochTable.UpdateItem(CreateTestDocument());
            newDoc = CreateTestDocument();
            newDoc["ConditionalUpdate"] = "yes";
            expectedState = new ExpectedState();
            expectedState.AddExpected("CreationTime", ScanOperator.Equal, EpochDate);
            epochTable.UpdateItem(newDoc, new UpdateItemOperationConfig {
                ExpectedState = expectedState
            });
            TestWrittenData("Bob", 42, hashRangeTable, epochTable, checkForConditionalUpdate: true);

            // second item for batch operations
            var doc2 = new Document();

            doc2["Name"]         = "Bob";
            doc2["Age"]          = 43;
            doc2["CreationTime"] = EpochDate;
            doc2["EpochDate2"]   = EpochDate;
            doc2["NonEpochDate"] = EpochDate;

            // batchWrite epoch seconds
            var batchWrite = epochTable.CreateBatchWrite();

            batchWrite.AddDocumentToPut(CreateTestDocument());
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();
            TestWrittenData("Bob", 42, hashRangeTable, epochTable);
            TestWrittenData("Bob", 43, hashRangeTable, epochTable);
            // execute again, since TestWrittenData deletes the items
            batchWrite.Execute();

            // batchGet epoch seconds as DateTime
            var epochBatchGet = epochTable.CreateBatchGet();

            epochBatchGet.ConsistentRead = true;
            epochBatchGet.AddKey("Bob", 42);
            epochBatchGet.AddKey("Bob", 43);
            epochBatchGet.Execute();
            TestForDateTime(epochBatchGet.Results);

            // batchGet epoch seconds as int
            var batchGet = hashRangeTable.CreateBatchGet();

            batchGet.ConsistentRead = true;
            batchGet.AddKey("Bob", 42);
            batchGet.AddKey("Bob", 43);
            batchGet.Execute();
            TestForInts(batchGet.Results);

            // batchWrite ISO-8601
            batchWrite = hashRangeTable.CreateBatchWrite();
            batchWrite.AddDocumentToPut(CreateTestDocument());
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();

            // batchGet ISO-8601 as DateTime
            epochBatchGet = epochTable.CreateBatchGet();
            epochBatchGet.ConsistentRead = true;
            epochBatchGet.AddKey("Bob", 42);
            epochBatchGet.AddKey("Bob", 43);
            epochBatchGet.Execute();
            TestForDateTime(epochBatchGet.Results);

            // batchGet ISO-8601 as DateTime with non-epoch table
            batchGet = hashRangeTable.CreateBatchGet();
            batchGet.ConsistentRead = true;
            batchGet.AddKey("Bob", 42);
            batchGet.AddKey("Bob", 43);
            batchGet.Execute();
            TestForDateTime(batchGet.Results);

            // write epoch seconds data data for Scan and Query
            batchWrite = epochTable.CreateBatchWrite();
            batchWrite.AddDocumentToPut(CreateTestDocument());
            batchWrite.AddDocumentToPut(doc2);
            batchWrite.Execute();

            // query
            var toTest = hashRangeTable.Query("Bob", new QueryFilter()).GetRemaining();

            TestForInts(toTest);
            toTest = epochTable.Query("Bob", new QueryFilter()).GetRemaining();
            TestForDateTime(toTest);

            //// query, filter is epoch seconds attribute
            //var queryFilter = new QueryFilter("CreationTime", QueryOperator.Equal, EpochDate);
            //toTest = numericHashRangeTable.Query(queryFilter).GetRemaining();
            //TestForDateTime(toTest);

            // scan, condition is epoch seconds attribute
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition("CreationTime", ScanOperator.Equal, EpochDate);
            toTest = hashRangeTable.Scan(scanFilter).GetRemaining();
            Assert.AreEqual(0, toTest.Count);
            toTest = epochTable.Scan(scanFilter).GetRemaining();
            TestForDateTime(toTest);

            // scan, condition is Name
            scanFilter = new ScanFilter();
            scanFilter.AddCondition("Name", ScanOperator.Equal, "Bob");
            toTest = hashRangeTable.Scan(scanFilter).GetRemaining();
            TestForInts(toTest);
            toTest = epochTable.Scan(scanFilter).GetRemaining();
            TestForDateTime(toTest);
        }
Esempio n. 13
0
        public async Task <string> FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        {
            try
            {
                List <RsMappings> rsMappings    = new List <RsMappings>();
                Task <string>     Response      = null;
                string            DataModified  = string.Empty;
                string            ResponseData  = string.Empty;
                Table             Catolog       = Table.LoadTable(client, tableName);
                ScanFilter        scan          = new ScanFilter();
                string            RSMapped      = RSMappedData;
                string[]          RSMappedSplit = RSMapped.Split(',').ToArray();//for sector
                //List<string> GetRSData = new List<string>();
                Dictionary <string, string> GetRSData = new Dictionary <string, string>();
                scan.AddCondition("guid", ScanOperator.IsNotNull);
                Search          search       = Catolog.Scan(scan);
                bool            isNumeric    = false;
                string[]        RSMappdata   = null;
                int             RSMapCount   = 0;
                List <Document> documentList = new List <Document>();
                //documentList = documentList.OrderBy(x=>x["ID"]).ToList();
                do
                {
                    try
                    {
                        documentList = await search.GetRemainingAsync();//.GetNextSetAsync();

                        foreach (Document doc in documentList)
                        {
                            RSMapCount = 0;
                            if (!string.IsNullOrEmpty(doc["RSMappedValues"].ToString()))
                            {
                                RSMappdata = doc["RSMappedValues"].ToString().Split('#').ToArray();
                                foreach (string str in RSMappdata)
                                {
                                    isNumeric = int.TryParse(str, out int i);
                                    if (!GetRSData.ContainsKey(str) && isNumeric == false && !str.Equals("--"))
                                    {
                                        GetRSData.Add(str, RSMappedSplit.ElementAt(RSMapCount));
                                    }
                                    RSMapCount++;
                                }
                            }
                            //context.Logger.LogLine("test 4");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                } while (!search.IsDone);
                context.Logger.LogLine("Data read from dynamo DB");
                for (int i = 0; i < RSMappedSplit.Count(); i++)
                {
                    List <string> RSMappedDataAfterSplit = GetRSData.Where(x => x.Value.Equals(RSMappedSplit.ElementAt(i))).Select(y => y.Key).ToList();
                    var           whereClause            = GetallRecordsWhereClause(RSMappedDataAfterSplit);
                    Catolog = Table.LoadTable(client, DestinationtableName);
                    context.Logger.LogLine(whereClause.ToString());
                    if (GetRSData != null && GetRSData.Count > 0)
                    {
                        string RSmapquery = string.Format(RSMappedQuery, whereClause, RSMapTableValue.Split(',')[i]);

                        var ODataRsponse1 = ExecuteODataGetQuery(RSmapquery, context);
                        if (ODataRsponse1 != null && ODataRsponse1.HasValues)
                        {
                            rsMappings.AddRange(ODataRsponse1.ToObject <List <RsMappings> >());
                        }
                        context.Logger.Log(rsMappings.Count.ToString());
                    }
                }

                foreach (Document doc in documentList)
                {
                    context.Logger.Log("heree");
                    int     rsmapped    = 0;
                    JObject jsonData    = JObject.Parse(doc["Data"]);
                    string  guidValue   = doc["guid"].ToString();
                    dynamic dynamoClass = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(doc["Data"].ToString());
                    for (int j = 0; j < RSMappedSplit.Count(); j++)
                    {
                        isNumeric = int.TryParse(doc["RSMappedValues"].ToString().Split('#')[j], out int i);
                        if (isNumeric == false)
                        {
                            var RSData = rsMappings != null?rsMappings.FirstOrDefault(mapping => mapping.OIDCIQ == jsonData.SelectToken(RSMappedSplit.ElementAt(j)).ToString()) : null;

                            if (RSData != null)
                            {
                                dynamoClass[RSMappedSplit.ElementAt(j)].Value = RSData.OID;
                                rsmapped++;
                            }
                        }
                        else
                        {
                            rsmapped++;
                        }
                    }
                    if (rsmapped == RSMappedSplit.Count())
                    {
                        ResponseData = await CreateTableItem(Catolog, doc, context, dynamoClass.ToString());

                        context.Logger.LogLine(ResponseData);
                        if (ResponseData.Equals("Success"))
                        {
                            DeleteItemRequest request = new DeleteItemRequest();
                            request.TableName = tableName;
                            request.Key       = new Dictionary <string, AttributeValue>()
                            {
                                { "guid", new AttributeValue {
                                      S = guidValue
                                  } }
                            };

                            context.Logger.LogLine("Del setup");
                            var response = await client.DeleteItemAsync(request);
                        }
                    }
                }

                context.Logger.LogLine("Data Loaded Successfully");
                return("Success");
            }

            catch (Exception ex)
            {
                context.Logger.LogLine("Error" + ex.ToString());
                return(null);
            }
        }
Esempio n. 14
0
        public async Task <IActionResult> PutOrder([FromHeader] string Authorization, [FromBody] OrderPut orderPut)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                if (orderPut.OrderId == null || orderPut.NewPrice == null || orderPut.NewQuantity == null)
                {
                    return(BadRequest("missing variables"));
                }

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Document searchdetails = new Document();

                string socket;

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id)
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }
                }
                catch
                {
                    return(BadRequest("authorizaion failed"));
                }

                Table ordertable = Table.LoadTable(amazonDynamoDBClient, "OrderRegistry");

                try
                {
                    Document putdoc = await ordertable.GetItemAsync(orderPut.OrderId);

                    if (putdoc["Email"].ToString() != searchdetails["Email"].ToString())
                    {
                        return(BadRequest("order not found"));
                    }

                    putdoc["Modify"] = "true";
                    await ordertable.UpdateItemAsync(putdoc);
                }
                catch
                {
                    return(BadRequest("order not found"));
                }

                // send tcp message to engine
                try
                {
                    TcpClient tcpclnt = new TcpClient();
                    Console.WriteLine("Connecting.....");

                    tcpclnt.Connect("52.213.34.99", port);
                    // use the ipaddress as in the server program

                    Console.WriteLine("Connected");
                    Console.Write("Enter the string to be transmitted : ");


                    var enginepayload = new
                    {
                        Method           = "Put",
                        Id               = orderPut.OrderId,
                        NewPrice         = orderPut.NewPrice,
                        NewQuantity      = orderPut.NewQuantity,
                        User             = searchdetails["Email"].ToString(),
                        Secret           = "secret",
                        AvailableBalance = searchdetails["AvailableBalance"].ToString()
                    };
                    using (SslStream sslStream = new SslStream(tcpclnt.GetStream(), false,
                                                               new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                    {
                        sslStream.AuthenticateAsClient("52.213.34.99");
                        // This is where you read and send data

                        String str = "enginekey" + JsonConvert.SerializeObject(enginepayload);
                        //Stream stm = tcpclnt.GetStream();

                        ASCIIEncoding asen = new ASCIIEncoding();
                        byte[]        ba   = asen.GetBytes(str);
                        Console.WriteLine("Transmitting.....");

                        sslStream.Write(ba, 0, ba.Length);
                        sslStream.Close();

                        /*byte[] bb = new byte[1000];
                         * int k = await sslStream.ReadAsync(bb, 0, 1000);
                         *
                         * var socketresult = Encoding.UTF8.GetString(bb).TrimEnd('\0');
                         * Console.WriteLine(socketresult);
                         * socket = socketresult;*/
                    }
                    tcpclnt.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                    return(BadRequest("error with engine"));
                }

                var    returnobj  = new { Result = "sucess" };
                string returnjson = JsonConvert.SerializeObject(returnobj);
                return(Content(returnjson, "application/json"));
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }
Esempio n. 15
0
        public async Task <string> FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        {
            try
            {
                ScanFilter scan       = new ScanFilter();
                DateTime   ParsedDate = new DateTime();
                Table      Catolog    = null;
                //string NullableData = Environment.GetEnvironmentVariable("NullableData");
                RetryHelper.RetryOnException(maxRetryAttempts, pauseBetweenFailures, () =>
                {
                    Catolog = Table.LoadTable(client, tableName);
                }, context);
                scan.AddCondition("GUID", ScanOperator.IsNotNull);
                Search search = Catolog.Scan(scan);
                //////////
                //context.Logger.LogLine("1");
                List <string> ColumnDestination = new List <string>();
                List <JArray> jArray            = new List <JArray>();
                int           j = 0;

                int    count = 0;
                string OldValue;
                string ResponseData  = string.Empty;
                string jsonSerialize = string.Empty;
                string KeyValue      = string.Empty;
                string action        = "Insert";
                List <Tuple <string, string, string, string> > DestinationTuple = new List <Tuple <string, string, string, string> >();
                Dictionary <string, dynamic> ChunkData = new Dictionary <string, dynamic>();
                StringBuilder wherequery = new StringBuilder();
                List <string> resValues  = new List <string>();
                // context.Logger.LogLine("2");
                string[] ColValues = DestinationQuery.Split(',').ToArray();
                Dictionary <string, string> Typesdata = new Dictionary <string, string>();
                foreach (string str in ColValues)
                {
                    Typesdata.Add(str.Split(':')[0], str.Split(':')[1]);
                }

                string[] DestinationColumns = DestinationTableData.Split(',').ToArray();
                Dictionary <string, string> DestinationTypesdata = new Dictionary <string, string>();
                string EnvironmentVarChild = string.Empty;
                foreach (string str in DestinationColumns)
                {
                    DestinationTypesdata.Add(str.Split(':')[0], str.Split(':')[1]);
                }
                Dictionary <string, DateTime> DynamoDBDate = new Dictionary <string, DateTime>();

                List <Document> documentList = new List <Document>();
                do
                {
                    documentList = await search.GetNextSetAsync();

                    foreach (Document doc in documentList)
                    {
                        DestinationTuple.Add(new Tuple <string, string, string, string>(doc["UniqueRow"].ToString(), doc["Data"].ToString(), doc["GUID"].ToString(), doc["timestamp"].ToString()));
                    }
                } while (!search.IsDone);

                int loops = DestinationTuple.Count;
                if (loops > 0)
                {
                    string secretData = await GetSecret(context);

                    if (!string.IsNullOrEmpty(secretData))
                    {
                        context.Logger.LogLine(secretData);
                        JObject joBj = JObject.Parse(secretData);
                        UserName = joBj.SelectToken(UserName).ToString();
                        Password = joBj.SelectToken(Password).ToString();
                        context.Logger.LogLine(Password);
                    }
                }
                context.Logger.LogLine(loops.ToString());
                string value = string.Empty;
                DestinationTuple = DestinationTuple.OrderBy(x => x.Item4).ToList();
                foreach (var kvp in DestinationTuple)
                {
                    context.Logger.LogLine(kvp.Item4);
                    j++;
                    dynamic myclass = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(kvp.Item2);
                    JObject json    = JObject.Parse(myclass.ToString());

                    if (j > 25)
                    {
                        loops      = loops - 25;
                        wherequery = new StringBuilder();
                        j          = 1;
                    }
                    EnvironmentVarChild = EnvironmentVar;
                    resValues           = new List <string>();


                    foreach (var x in Typesdata)
                    {
                        if (string.IsNullOrEmpty(json.SelectToken(x.Key).ToString()) || json.SelectToken(x.Key).ToString().Equals("--"))
                        {
                            break;
                        }
                        if (x.Value.Equals("DateTime"))
                        {
                            try
                            {
                                ParsedDate = DateTime.ParseExact(json.SelectToken(x.Key).ToString(), "yyyyMMdd",
                                                                 CultureInfo.InvariantCulture);
                                resValues.Add(ParsedDate.ToString("yyyy-MM-dd"));
                            }
                            catch (Exception ex)
                            {
                                context.Logger.Log(ex.ToString());
                                break;
                            }
                        }
                        else if (x.Value.Equals("int") || x.Value.Equals("Float"))
                        {
                            resValues.Add(json.SelectToken(x.Key).ToString());
                        }
                        else
                        {
                            resValues.Add("'" + json.SelectToken(x.Key).ToString() + "'");
                        }
                    }
                    if (!resValues.Count.Equals(Typesdata.Count))
                    {
                        context.Logger.Log("Invalid Data ignored.Please provide valid data" + value.ToString());
                    }
                    else
                    {
                        ChunkData.Add(kvp.Item3, myclass);

                        if (wherequery.Length > 1)
                        {
                            wherequery.Append("or");
                        }
                        int i = 0;
                        foreach (string x in resValues)
                        {
                            OldValue            = "{" + i + "}";
                            EnvironmentVarChild = EnvironmentVarChild.Replace(OldValue, x);
                            i++;
                        }
                        wherequery.Append(EnvironmentVarChild);
                    }
                    if (loops == j || j % 25 == 0)
                    {
                        var queryToCheckMDSCDSInDB = string.Format(envrVariable + wherequery + ")&editable=true");
                        queryToCheckMDSCDSInDB = queryToCheckMDSCDSInDB.Replace("+", "%2B");
                        var    ODataRsponse  = ExecuteODataGetQuery(queryToCheckMDSCDSInDB, context);
                        JArray ResponseArray = ODataRsponse != null?JArray.Parse(ODataRsponse.ToString()) : null;

                        //jArray.Add(ResponseArray);
                        foreach (KeyValuePair <string, dynamic> obj in ChunkData)
                        {
                            JObject jsonData = JObject.Parse(obj.Value.ToString());
                            action = "Insert";
                            if (ResponseArray != null)
                            {
                                foreach (JObject jobject in ResponseArray)
                                {
                                    count = 0;
                                    foreach (KeyValuePair <string, string> x in Typesdata)
                                    {
                                        switch (x.Value)
                                        {
                                        case "Double":
                                        case "string":
                                        case "int":
                                            if (jsonData.SelectToken(x.Key).ToString().Equals(jobject.SelectToken(x.Key).ToString()))
                                            {
                                                count++;
                                            }
                                            break;

                                        case "DateTime":
                                            if (Convert.ToDateTime(jobject.SelectToken(x.Key).ToString()).ToString("yyyyMMdd").Equals(jsonData.SelectToken(x.Key).ToString()))
                                            {
                                                count++;
                                            }
                                            break;
                                        }
                                    }
                                    if (Typesdata.Count == count)
                                    {
                                        action   = "Update";
                                        KeyValue = jobject.SelectToken(EntityKey).ToString();
                                        break;
                                    }
                                    else
                                    {
                                        action = "Insert";
                                    }
                                }
                            }
                            context.Logger.LogLine(obj.Value.ToString());
                            Dictionary <string, object> EntityFields = GenerateODataObject(context, obj.Value, KeyValue, DestinationTypesdata, action, Typesdata);
                            if (EntityFields != null)
                            {
                                context.Logger.LogLine(EntityFields.ElementAt(0).Value.ToString());
                                if (action == "Update")
                                {
                                    jsonSerialize = JsonConvert.SerializeObject(EntityFields);
                                    ResponseData  = UpdateOdateResponse(jsonSerialize, context, KeyValue);
                                }
                                else
                                {
                                    jsonSerialize = JsonConvert.SerializeObject(EntityFields);
                                    ResponseData  = InsertOdateResponse(jsonSerialize, context);
                                }

                                if (ResponseData == "Success")
                                {
                                    //Delete data from Dynamo DB
                                    DeleteItemRequest request = new DeleteItemRequest();
                                    request.TableName = tableName;
                                    request.Key       = new Dictionary <string, AttributeValue>()
                                    {
                                        { "GUID", new AttributeValue {
                                              S = obj.Key
                                          } }
                                    };
                                    var response = await client.DeleteItemAsync(request);
                                }
                            }
                            context.Logger.Log(ResponseData);
                        }
                        ChunkData = new Dictionary <string, dynamic>();
                    }
                }
                context.Logger.Log("Success");
                return("Success");
            }
            catch (Exception ex)
            {
                context.Logger.Log("Error" + ex.ToString());
                return(null);
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> reg([FromHeader] string Authorization, [FromHeader] string User, [FromHeader] string Password)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Table    PosTable      = Table.LoadTable(amazonDynamoDBClient, "PositionRegistry");
                Document searchdetails = new Document();

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"].ToString() == "test" && doc["DefaultId"].ToString() == "hello")
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }
                }
                catch
                {
                    return(BadRequest("authorizaion failed"));
                }

                Document userexist = await UserTable.GetItemAsync(User);

                try
                { userexist["User"].ToString(); return(BadRequest("user already exists")); }
                catch
                { }

                Document newuser = new Document();
                newuser["User"]     = User;
                newuser["Password"] = Password;
                Table userreg = Table.LoadTable(amazonDynamoDBClient, "UserRegistry");
                await userreg.PutItemAsync(newuser);

                string guid = Guid.NewGuid().ToString(); Console.WriteLine(guid);
                Thread.Sleep(3);
                string   gusecret   = Guid.NewGuid().ToString(); Console.WriteLine(gusecret);
                Document userregdoc = new Document();
                userregdoc["Email"]            = User;
                userregdoc["DefaultId"]        = guid;
                userregdoc["DefaultSecret"]    = gusecret;
                userregdoc["AvailableBalance"] = "1";
                await UserTable.PutItemAsync(userregdoc);

                Document posdoc = new Document();
                posdoc["Email"]            = User;
                posdoc["AvailableBalance"] = "1";
                posdoc["POSSPXUSD"]        = "na";
                await PosTable.PutItemAsync(posdoc);

                return(Ok("user added"));
            }
            catch
            {
                return(BadRequest());
            }
        }
Esempio n. 17
0
        public List <Queue> Enqueue()
        {
            string tableName = Constants.QueueTableName;
            Table  table     = Table.LoadTable(_client, tableName);

            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition(Constants.QueueActive, ScanOperator.Equal, "True");

            Search search = table.Scan(scanFilter);

            List <Queue> list = new List <Queue>();

            string  queueID              = null;
            JObject businessLogicJson    = null;
            string  workflowTypeName     = null;
            Guid    workflowID           = Guid.Empty;
            JObject customPropertiesJson = null;
            JObject messageBodyJson      = null;

            string stepIdentifier = null;
            bool   stepSucceeded  = true;

            int retries = 0;

            DateTime timeStamp         = DateTime.UtcNow;
            string   runStepIdentifier = null;
            string   splitID           = null;

            do
            {
                Task <List <Document> > documentListTask = search.GetNextSetAsync();
                documentListTask.Wait();

                List <Document> documentList = documentListTask.Result;

                foreach (Document document in documentList)
                {
                    queueID           = document[Constants.QueueId].AsString();
                    businessLogicJson = JObject.Parse(document[Constants.BusinessLogic].AsDocument().ToJson());
                    workflowTypeName  = document[Constants.WorkflowType].AsString();
                    workflowID        = document[Constants.HistoryWorkflowId].AsGuid();

                    if (document.ContainsKey(Constants.QueueCustomProperties))
                    {
                        customPropertiesJson = JObject.Parse(document[Constants.QueueCustomProperties].AsDocument().ToJson());
                    }

                    if (document.ContainsKey(Constants.QueueMessageBody))
                    {
                        messageBodyJson = JObject.Parse(document[Constants.QueueMessageBody].AsDocument().ToJson());
                    }

                    if (document.ContainsKey(Constants.QueueStepIdentifier))
                    {
                        stepIdentifier = document[Constants.QueueStepIdentifier].AsString();
                    }

                    if (document.ContainsKey(Constants.QueueRunStepIdentifier))
                    {
                        runStepIdentifier = document[Constants.QueueRunStepIdentifier].AsString();
                    }

                    if (document.ContainsKey(Constants.QueueSlitID))
                    {
                        splitID = document[Constants.QueueSlitID].AsString();
                    }

                    if (document.ContainsKey(Constants.QueueRetries))
                    {
                        retries = document[Constants.QueueRetries].AsInt();
                    }

                    if (document.ContainsKey(Constants.QueueStepSucceeded))
                    {
                        stepSucceeded = document[Constants.QueueStepSucceeded].AsBoolean();
                    }

                    if (document.ContainsKey(Constants.Timestamp))
                    {
                        timeStamp = Convert.ToDateTime(document[Constants.Timestamp].AsString());
                    }

                    QueueMetadata metadata = new QueueMetadata()
                    {
                        CustomPropertiesJson = customPropertiesJson,
                        ID = Guid.Parse(queueID),
                        MessageBodyJson = messageBodyJson,
                        SplitID         = splitID,
                        StepIdentifier  = stepIdentifier,
                        Success         = stepSucceeded,
                        Retries         = retries,
                        Timestamp       = timeStamp
                    };

                    Queue queue = GetQueueByWorkflowID(list, workflowID.ToString());

                    if (queue == null)
                    {
                        queue = new Queue()
                        {
                            Type = new WorkfowType()
                            {
                                BusinessLogicJson = businessLogicJson,
                                Name = workflowTypeName
                            },
                            WorkflowID = workflowID,
                            Metadata   = new List <QueueMetadata>()
                        }
                    }
                    ;

                    queue.Metadata.Add(metadata);

                    list.Add(queue);
                    DeleteFromQueue(queueID, true);
                }
            } while (!search.IsDone);

            return(list);
        }
Esempio n. 18
0
        static void Main()
        {
            //  1.  Create a DynamoDB client connected to a DynamoDB-Local instance
            Console.WriteLine(StepString, 1,
                              "Create a DynamoDB client connected to a DynamoDB-Local instance");
            if (!CreateClient(true) || !Pause())
            {
                return;
            }

            //  2.  Create a table for movie data asynchronously
            Console.WriteLine(StepString, 2,
                              "Create a table for movie data");

            CreatingTable_async(MoviesTableName,
                                MovieItemsAttributes,
                                MoviesKeySchema,
                                MoviesTableProvisionedThroughput).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            try
            {
                MoviesTable = Table.LoadTable(DdbIntro.Client, MoviesTableName);
            }
            catch (Exception ex)
            {
                OperationFailed = true;
                Console.WriteLine(
                    " Error: Could not access the new '{0}' table after creating it;\n" +
                    "        Reason: {1}.", MoviesTableName, ex.Message);
                Pause();
                return;
            }

            //  3.  Load movie data into the Movies table asynchronously
            if ((MoviesTableDescription != null) &&
                (MoviesTableDescription.ItemCount == 0))
            {
                Console.WriteLine(StepString, 3,
                                  "Load movie data into the Movies table");
                LoadingData_async(MoviesTable, MovieDataPath).Wait();

                if (!Pause() || OperationFailed)
                {
                    return;
                }
            }
            else
            {
                Console.WriteLine(StepString, 3,
                                  "Skipped: Movie data is already loaded in the Movies table");

                if (!Pause())
                {
                    return;
                }
            }

            //  4.  Add a new movie to the Movies table
            Console.WriteLine(StepString, 4,
                              "Add a new movie to the Movies table");
            Document newItemDocument = new Document();

            newItemDocument["year"]  = 2018;
            newItemDocument["title"] = "The Big New Movie";
            newItemDocument["info"]  = Document.FromJson(
                "{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}");

            WritingNewMovie_async(newItemDocument).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  5.  Read and display the new movie record that was just added
            Console.WriteLine(StepString, 5,
                              "Read and display the new movie record that was just added");

            ReadingMovie_async(2018, "The Big New Movie", true).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  6.  Update the new movie record in various ways
            //-------------------------------------------------
            //  6a.  Create an UpdateItemRequest to:
            //       -- modify the plot and rating of the new movie, and
            //       -- add a list of actors to it
            Console.WriteLine(StepString, "6a",
                              "Change the plot and rating for the new movie and add a list of actors");

            UpdateItemRequest updateRequest = new UpdateItemRequest()
            {
                TableName = MoviesTableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { PartitionKeyName, new AttributeValue {
                          N = "2018"
                      } },
                    { SortKeyName, new AttributeValue {
                          S = "The Big New Movie"
                      } }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":r", new AttributeValue {
                          N = "5.5"
                      } },
                    { ":p", new AttributeValue {
                          S = "Everything happens all at once!"
                      } },
                    { ":a", new AttributeValue {
                          L = new List <AttributeValue>
                          {
                              new AttributeValue {
                                  S = "Larry"
                              },
                              new AttributeValue {
                                  S = "Moe"
                              },
                              new AttributeValue {
                                  S = "Curly"
                              }
                          }
                      } }
                },
                UpdateExpression = "SET info.rating = :r, info.plot = :p, info.actors = :a",
                ReturnValues     = "NONE"
            };

            UpdatingMovie_async(updateRequest, true).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  6b  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(StepString, "6b",
                              "Increment the new movie's rating atomically");
            Console.WriteLine("  -- Incrementing the rating of the new movie by 1...");

            updateRequest.ExpressionAttributeValues = new Dictionary <string, AttributeValue>
            {
                { ":inc", new AttributeValue {
                      N = "1"
                  } }
            };

            updateRequest.UpdateExpression = "SET info.rating = info.rating + :inc";
            UpdatingMovie_async(updateRequest, true).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  6c  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(StepString, "6c",
                              "Now try the same increment again with a condition that fails... ");
            Console.WriteLine("  -- Now trying to increment the new movie's rating, but this time\n" +
                              "     ONLY ON THE CONDITION THAT the movie has more than 3 actors...");
            updateRequest.ExpressionAttributeValues.Add(":n", new AttributeValue {
                N = "3"
            });
            updateRequest.ConditionExpression = "size(info.actors) > :n";

            UpdatingMovie_async(updateRequest, true).Wait();

            if (!Pause() || OperationSucceeded)
            {
                return;
            }


            //  7.  Try conditionally deleting the movie that we added

            //  7a.  Try conditionally deleting the movie that we added
            Console.WriteLine(StepString, "7a",
                              "Try deleting the new movie record with a condition that fails");
            Console.WriteLine("  -- Trying to delete the new movie,\n" +
                              "     -- but ONLY ON THE CONDITION THAT its rating is 5.0 or less...");
            Expression condition = new Expression();

            condition.ExpressionAttributeValues[":val"] = 5.0;
            condition.ExpressionStatement = "info.rating <= :val";

            DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition).Wait();

            if (!Pause() || OperationSucceeded)
            {
                return;
            }

            //  7b.  Now increase the cutoff to 7.0 and try to delete again...
            Console.WriteLine(StepString, "7b",
                              "Now increase the cutoff to 7.0 and try to delete the movie again...");
            Console.WriteLine("  -- Now trying to delete the new movie again,\n" +
                              "     -- but this time on the condition that its rating is 7.0 or less...");
            condition.ExpressionAttributeValues[":val"] = 7.0;

            DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  8.  Query the Movies table in 3 different ways
            Search search;

            //  8a. Just query on the year
            Console.WriteLine(StepString, "8a",
                              "Query the Movies table using a Search object for all movies from 1985");
            Console.WriteLine("  -- First, create a Search object...");

            try
            {
                search = MoviesTable.Query(1985, new Expression());
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                Pause();
                return;
            }

            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query:");

            if ((search == null) || !Pause())
            {
                return;
            }

            SearchListing_async(search).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  8b. SearchListing_async
            Console.WriteLine(StepString, "8b",
                              "Query for 1992 movies with titles from B... to Hzz... using Table.Query");
            Console.WriteLine("  -- Now setting up a QueryOperationConfig for the 'Search'...");

            QueryOperationConfig config = new QueryOperationConfig();

            config.Filter = new QueryFilter();
            config.Filter.AddCondition("year", QueryOperator.Equal, new DynamoDBEntry[] { 1992 });
            config.Filter.AddCondition("title", QueryOperator.Between, new DynamoDBEntry[] { "B", "Hzz" });
            config.AttributesToGet = new List <string> {
                "year", "title", "info"
            };
            config.Select = SelectValues.SpecificAttributes;

            Console.WriteLine("     -- Creating the Search object based on the QueryOperationConfig");

            try
            {
                search = MoviesTable.Query(config);
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);

                if (!Pause() || OperationFailed)
                {
                    return;
                }
            }

            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query.");

            if ((search == null) || !Pause())
            {
                return;
            }

            SearchListing_async(search).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  8c. Query using a QueryRequest
            Console.WriteLine(StepString, "8c",
                              "Query the Movies table for 1992 movies with titles from M... to Tzz...");
            Console.WriteLine("  -- Next use a low-level query to retrieve a selection of movie attributes");

            QueryRequest qRequest = new QueryRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":qYr", new AttributeValue {
                          N = "1992"
                      } },
                    { ":tSt", new AttributeValue {
                          S = "M"
                      } },
                    { ":tEn", new AttributeValue {
                          S = "Tzz"
                      } }
                },
                KeyConditionExpression = "#yr = :qYr and title between :tSt and :tEn",
                ProjectionExpression   = "#yr, title, info.actors[0], info.genres, info.running_time_secs"
            };

            Console.WriteLine("     -- Using a QueryRequest to get the lead actor and genres of\n" +
                              "        1992 movies with titles between 'M...' and 'Tzz...'.");

            ClientQuerying_async(qRequest).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  9.  Try scanning the movies table to retrieve movies from several decades
            //  9a. Use Table.Scan with a Search object and a ScanFilter to retrieve movies from the 1950s
            Console.WriteLine(StepString, "9a",
                              "Scan the Movies table to retrieve all movies from the 1950's");
            ScanFilter filter = new ScanFilter();

            filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 });

            ScanOperationConfig scanConfig = new ScanOperationConfig
            {
                Filter = filter
            };

            Console.WriteLine("     -- Creating a Search object based on a ScanFilter");

            try
            {
                search = MoviesTable.Scan(scanConfig);
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                Pause();
                return;
            }

            Console.WriteLine("     -- Successfully created the Search object");

            if ((search == null) || !Pause())
            {
                return;
            }

            SearchListing_async(search).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  9b. Use AmazonDynamoDBClient.Scan to retrieve movies from the 1960s
            Console.WriteLine(StepString, "9b",
                              "Use a low-level scan to retrieve all movies from the 1960's");
            Console.WriteLine("     -- Using a ScanRequest to get movies from between 1960 and 1969");

            ScanRequest sRequest = new ScanRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":y_a", new AttributeValue {
                          N = "1960"
                      } },
                    { ":y_z", new AttributeValue {
                          N = "1969"
                      } },
                },
                FilterExpression     = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs"
            };

            ClientScanning_async(sRequest).Wait();

            if (!Pause() || OperationFailed)
            {
                return;
            }

            //  10.  Delete the Movies table and all its contents
            Console.WriteLine(StepString, 10,
                              "Finally, delete the Movies table and all its contents");

            DeletingTable_async(MoviesTableName).Wait();

            Console.WriteLine(
                "\n=================================================================================" +
                "\n            This concludes the DynamoDB Getting-Started demo program" +
                "\n=================================================================================" +
                "\n                      ...Press any key to exit");

            Console.ReadKey();
        }
Esempio n. 19
0
        /*--------------------------------------------------------------------------
         *                Main
         *--------------------------------------------------------------------------*/
        static void Main(string[] args)
        {
            //  1.  Create a DynamoDB client connected to a DynamoDB-Local instance
            Console.WriteLine(stepString, 1,
                              "Create a DynamoDB client connected to a DynamoDB-Local instance");
            if (!CreateClient(true) || !Pause())
            {
                return;
            }

            //  1a.  Create a CosmosDB client connected to a DynamoDB-Local instance
            if (!CreateClient_CosmosDB(true) || !Pause())
            {
                return;
            }

            //  2.  Create a DynamoDB table for movie data asynchronously
            Console.WriteLine(stepString, 2,
                              "Create a table for movie data");
            CreatingTable_async(movies_table_name,
                                movie_items_attributes,
                                movies_key_schema,
                                movies_table_provisioned_throughput).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            try { moviesTable = Table.LoadTable(CosmosDBvDynamoDB.client, movies_table_name); }
            catch (Exception ex)
            {
                operationFailed = true;
                Console.WriteLine(
                    " Error: Could not access the new '{0}' table after creating it;\n" +
                    "        Reason: {1}.", movies_table_name, ex.Message);
                Pause();
                return;
            }

            //  2a.  Create a Cosmosdb database and collection for movie data asynchronously
            CreatingTable_async_CosmosDB(
                movies_table_name,
                partition_key_name,
                movie_collection_provisioned_throughput).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }


            //  3.  Load movie data into the Movies table asynchronously into DynamoDB
            if ((moviesTableDescription != null) &&
                (moviesTableDescription.ItemCount == 0))
            {
                Console.WriteLine(stepString, 3,
                                  "Load movie data into the Movies table");
                LoadingData_async(moviesTable, movieDataPath).Wait();
                if (!Pause() || operationFailed)
                {
                    return;
                }

                //  3a.  Load movie data into the Movies table asynchronously into CosmosDB
                LoadingData_async_CosmosDB(movieDataPath).Wait();
                if (!Pause() || operationFailed)
                {
                    return;
                }
            }
            else
            {
                Console.WriteLine(stepString, 3,
                                  "Skipped: Movie data is already loaded in the Movies table");
                if (!Pause())
                {
                    return;
                }
            }



            Console.WriteLine(stepString, 4,
                              "Add a new movie to the Movies table");
            //  4.  Add a new movie to the Movies table - DynamoDB
            Amazon.DynamoDBv2.DocumentModel.Document newItemDocument = new Amazon.DynamoDBv2.DocumentModel.Document
            {
                ["year"]  = 2018,
                ["title"] = "The Big New Movie",
                ["info"]  = Amazon.DynamoDBv2.DocumentModel.Document.FromJson(
                    "{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}")
            };
            WritingNewMovie_async(newItemDocument).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //  4a.  Add a new movie to the Movies table - CosmosDB
            MovieModel mv = new MovieModel()
            {
                Id        = Guid.NewGuid().ToString(),
                Title     = "The Big New Movie",
                Year      = 2018,
                MovieInfo = new MovieInfo()
                {
                    Plot = "Nothing happens at all.", Rating = 0
                }
            };

            WritingNewMovie_async_cosmosDB(mv).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }


            Console.WriteLine(stepString, 5,
                              "Read and display the new movie record that was just added");
            //  5.  Read and display the new movie record that was just added - DynamoDB
            ReadingMovie_async(2018, "The Big New Movie", true).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //  5a.  Read and display the new movie record that was just added - CosmosDB
            ReadingMovie_async_CosmosDB(2018, "The Big New Movie", true);
            if (!Pause() || operationFailed)
            {
                return;
            }

            //  6.  Update the new movie record in various ways
            //-------------------------------------------------
            //  6a.  Create an UpdateItemRequest to:
            //       -- modify the plot and rating of the new movie, and
            //       -- add a list of actors to it
            Console.WriteLine(stepString, "6a",
                              "Change the plot and rating for the new movie and add a list of actors");

            //DynamoDB
            UpdateItemRequest updateRequest = new UpdateItemRequest()
            {
                TableName = movies_table_name,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { partition_key_name, new AttributeValue {
                          N = "2018"
                      } },
                    { sort_key_name, new AttributeValue {
                          S = "The Big New Movie"
                      } }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":r", new AttributeValue {
                          N = "5.5"
                      } },
                    { ":p", new AttributeValue {
                          S = "Everything happens all at once!"
                      } },
                    { ":a", new AttributeValue {
                          L = new List <AttributeValue>
                          {
                              new AttributeValue {
                                  S = "Larry"
                              },
                              new AttributeValue {
                                  S = "Moe"
                              },
                              new AttributeValue {
                                  S = "Curly"
                              }
                          }
                      } }
                },
                UpdateExpression = "SET info.rating = :r, info.plot = :p, info.actors = :a",
                ReturnValues     = "NONE"
            };

            UpdatingMovie_async(updateRequest, true).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            var       doc  = ReadingMovieItem_async_CosmosDB(2018, "The Big New Movie");
            MovieInfo info = new MovieInfo
            {
                Rating = 5.5,
                Plot   = "Everything happens all at once!",
                Actors = new string[] { "Larry", "Moe", "Curly" }
            };

            doc.MovieInfo = info;
            UpdatingMovie_async_CosmosDB(doc, true).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //  6b  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(stepString, "6b",
                              "Increment the new movie's rating atomically");

            Console.WriteLine("  -- Incrementing the rating of the new movie by 1...");

            //DynamoDB
            updateRequest.ExpressionAttributeValues = new Dictionary <string, AttributeValue>
            {
                { ":inc", new AttributeValue {
                      N = "1"
                  } }
            };
            updateRequest.UpdateExpression = "SET info.rating = info.rating + :inc";
            UpdatingMovie_async(updateRequest, true).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            var docList = ReadingMovieItem_async_List_CosmosDB(2018, "The Big New Movie");

            foreach (var docObject in docList)
            {
                info = docObject.MovieInfo;
                if (info != null)
                {
                    info.Rating++;
                    UpdatingMovie_async_CosmosDB(doc, true).Wait();
                    if (!Pause() || operationFailed)
                    {
                        return;
                    }
                }
            }

            //  6c  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(stepString, "6c",
                              "Now try the same increment again with a condition that fails... ");
            Console.WriteLine("  -- Now trying to increment the new movie's rating, but this time\n" +
                              "     ONLY ON THE CONDITION THAT the movie has more than 3 actors...");

            //DynamoDB
            updateRequest.ExpressionAttributeValues.Add(":n", new AttributeValue {
                N = "0"
            });

            updateRequest.ConditionExpression = "size(info.actors) > :n";
            UpdatingMovie_async(updateRequest, true).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            FeedIterator <MovieModel> result = ReadingMovieItem_async_List_CosmosDB("select * from Movies c where c.year=2018 and c.title=\"The Big New Movie\" and ARRAY_LENGTH(c.info.actors)>1");
            List <Task> tasks = new List <Task>();

            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync();
                resultModel.Wait();
                foreach (var movie in resultModel.Result.ToList <MovieModel>())
                {
                    movie.MovieInfo.Rating++;

                    tasks.Add(UpdatingMovie_async_CosmosDB(doc, true));
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }
            Task.WhenAll(tasks).Wait();

            //  7.  Try conditionally deleting the movie that we added

            //  7a.  Try conditionally deleting the movie that we added
            Console.WriteLine(stepString, "7a",
                              "Try deleting the new movie record with a condition that fails");
            Console.WriteLine("  -- Trying to delete the new movie,\n" +
                              "     -- but ONLY ON THE CONDITION THAT its rating is 8.0 or less...");

            //DynamoDB
            Expression condition = new Expression();

            condition.ExpressionAttributeValues[":val"] = 8.0;
            condition.ExpressionStatement = "info.rating <= :val";
            DeletingItem_async(moviesTable, 2018, "The Big New Movie", condition).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //ComosDB
            DeletingItem_async_CosmosDB("select c from c join d in c.info where d.rating<8 AND c.year=2018 AND c.title='The Big New Movie'").GetAwaiter();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //  7b.  Now increase the cutoff to 7.0 and try to delete again...
            Console.WriteLine(stepString, "7b",
                              "Now increase the cutoff to 7.0 and try to delete the movie again...");
            Console.WriteLine("  -- Now trying to delete the new movie again,\n" +
                              "     -- but this time on the condition that its rating is 7.0 or less...");
            //DynamoDB
            condition.ExpressionAttributeValues[":val"] = 8.0;

            DeletingItem_async(moviesTable, 2018, "The Big New Movie", condition).Wait();
            if (!Pause()) //|| operationFailed)
            {
                return;
            }

            //CosmosDB
            DeletingItem_async_CosmosDB("select * from c where c.info.rating>7 AND c.year=2018 AND c.title='The Big New Movie'").GetAwaiter();

            //  8.  Query the Movies table in 3 different ways
            Search search;

            //  8a. Just query on the year
            Console.WriteLine(stepString, "8a",
                              "Query the Movies table using a Search object for all movies from 1985");
            Console.WriteLine("  -- First, create a Search object...");

            //DynamoDB
            try { search = moviesTable.Query(1985, new Expression()); }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                Pause();
                return;
            }
            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query:");
            if ((search == null) || !Pause())
            {
                return;
            }
            SearchListing_async(search).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            result = ReadingMovieItem_async_List_CosmosDB("select * from c where c.year=1985");
            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync();
                resultModel.Wait();
                foreach (var movie in resultModel.Result.ToList <MovieModel>())
                {
                    Console.WriteLine(movie.PrintInfo());
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }



            //  8b. SearchListing_async
            Console.WriteLine(stepString, "8b",
                              "Query for 1992 movies with titles from B... to Hzz... using Table.Query");
            Console.WriteLine("  -- Now setting up a QueryOperationConfig for the 'Search'...");

            //DynamoDB
            QueryOperationConfig config = new QueryOperationConfig
            {
                Filter = new QueryFilter()
            };

            config.Filter.AddCondition("year", QueryOperator.Equal, new DynamoDBEntry[] { 1992 });
            config.Filter.AddCondition("title", QueryOperator.Between, new DynamoDBEntry[] { "B", "Hzz" });
            config.AttributesToGet = new List <string> {
                "year", "title", "info"
            };
            config.Select = SelectValues.SpecificAttributes;
            Console.WriteLine("     -- Creating the Search object based on the QueryOperationConfig");
            try { search = moviesTable.Query(config); }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                if (!Pause() || operationFailed)
                {
                    return;
                }
            }
            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query.");
            if ((search == null) || !Pause())
            {
                return;
            }

            SearchListing_async(search).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            result = ReadingMovieItem_async_List_CosmosDB("select c.year, c.title, c.info from c where c.year=1998 AND (CONTAINS(c.title,'B') OR CONTAINS(c.title,'Hzz'))");
            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync();
                resultModel.Wait();
                foreach (var movie in resultModel.Result.ToList <MovieModel>())
                {
                    Console.WriteLine(movie.PrintInfo());
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }


            //  8c. Query using a QueryRequest
            Console.WriteLine(stepString, "8c",
                              "Query the Movies table for 1992 movies with titles from M... to Tzz...");
            Console.WriteLine("  -- Next use a low-level query to retrieve a selection of movie attributes");

            //DynamoDB
            QueryRequest qRequest = new QueryRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":qYr", new AttributeValue {
                          N = "1992"
                      } },
                    { ":tSt", new AttributeValue {
                          S = "M"
                      } },
                    { ":tEn", new AttributeValue {
                          S = "Tzz"
                      } }
                },
                KeyConditionExpression = "#yr = :qYr and title between :tSt and :tEn",
                ProjectionExpression   = "#yr, title, info.actors[0], info.genres, info.running_time_secs"
            };

            Console.WriteLine("     -- Using a QueryRequest to get the lead actor and genres of\n" +
                              "        1992 movies with titles between 'M...' and 'Tzz...'.");
            ClientQuerying_async(qRequest).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            result = ReadingMovieItem_async_List_CosmosDB("select c.year, c.title, c.info from c where c.year=1992 AND (CONTAINS(c.title,'M') OR CONTAINS(c.title,'Tzz'))");
            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync().Result;
                foreach (var movie in resultModel.ToList <MovieModel>())
                {
                    Console.WriteLine(movie.PrintInfo());
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }

            //  9.  Try scanning the movies table to retrieve movies from several decades
            //  9a. Use Table.Scan with a Search object and a ScanFilter to retrieve movies from the 1950s
            Console.WriteLine(stepString, "9a",
                              "Scan the Movies table to retrieve all movies from the 1950's");

            //DynamoDB
            ScanFilter filter = new ScanFilter();

            filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 });
            ScanOperationConfig scanConfig = new ScanOperationConfig
            {
                Filter = filter
            };

            Console.WriteLine("     -- Creating a Search object based on a ScanFilter");
            try { search = moviesTable.Scan(scanConfig); }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                Pause();
                return;
            }
            Console.WriteLine("     -- Successfully created the Search object");
            if ((search == null) || !Pause())
            {
                return;
            }

            SearchListing_async(search).Wait();
            if (!Pause() || operationFailed)
            {
                return;
            }

            //CosmosDB
            result = ReadingMovieItem_async_List_CosmosDB("select * from c where c.year BETWEEN 1950 AND 1959");
            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync();
                resultModel.Wait();
                foreach (var movie in resultModel.Result.ToList <MovieModel>())
                {
                    Console.WriteLine(movie.PrintInfo());
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }


            //  9b. Use AmazonDynamoDBClient.Scan to retrieve movies from the 1960s
            Console.WriteLine(stepString, "9b",
                              "Use a low-level scan to retrieve all movies from the 1960's");
            Console.WriteLine("     -- Using a ScanRequest to get movies from between 1960 and 1969");

            //DynamoDB
            ScanRequest sRequest = new ScanRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":y_a", new AttributeValue {
                          N = "1960"
                      } },
                    { ":y_z", new AttributeValue {
                          N = "1969"
                      } },
                },
                FilterExpression     = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs"
            };

            ClientScanning_async(sRequest).Wait();
            if (operationFailed)
            {
                return;
            }

            //CosmosDB
            result = ReadingMovieItem_async_List_CosmosDB("select c.title, c.year, c.info.actors[0], c.info.directors,c.info.running_time_secs from c where  c.year BETWEEN 1960 AND 1969");

            while (result.HasMoreResults)
            {
                var resultModel = result.ReadNextAsync();
                resultModel.Wait();
                foreach (var movie in resultModel.Result.ToList <MovieModel>())
                {
                    Console.WriteLine(movie.PrintInfo());
                    if (operationFailed)
                    {
                        return;
                    }
                }
            }

            //  10.  Finally, delete the Movies table and all its contents
            Console.WriteLine(stepString, 10,
                              "Finally, delete the Movies table and all its contents");

            //DynamoDB
            DeletingTable_async(movies_table_name).Wait();

            //CosmosDB
            DeletingCollection_async_CosmosDB().Wait();
            //For Cosmos DB Database needs to be delted for complete clean up
            DeletingDB_async_CosmosDB().Wait();
            // End:
            Console.WriteLine(
                "\n=================================================================================" +
                "\n            This concludes the DynamoDB viz-a-viz cosmodDB demo program" +
                "\n=================================================================================" +
                "\n                      ...Press any key to exit");
            Console.ReadKey();

            return;
        }
Esempio n. 20
0
        public async Task <IActionResult> webhook([FromQuery] string key)
        {
            try
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                Table credtable             = Table.LoadTable(client, "InSilico");
                ScanOperationConfig config  = new ScanOperationConfig();
                ScanFilter          filter  = new ScanFilter();
                filter.AddCondition("key", ScanOperator.IsNotNull);
                config.Filter = filter;
                Search          search = credtable.Scan(config);
                List <Document> docs   = await search.GetRemainingAsync();

                Document creds = new Document();
                foreach (Document doc in docs)  // get credentials from dynamodb
                {
                    try { doc["key"].ToString(); creds = doc; break; } // get first nonempty (only should be one entry in this db or this will break
                    catch { }
                }

                string webhookkey = creds["webhook"].ToString();
                string authkey    = creds["key"].ToString();
                string authsecret = creds["secret"].ToString();

                if (key != webhookkey)
                {
                    throw new Exception();
                }                                                 // webhook auth

                DeribitAPI deribit = new DeribitAPI(authkey, authsecret);

                StreamReader reader = new StreamReader(Request.Body);
                string       text   = reader.ReadToEnd();

                string[] fishervals = text.Split(',');
                fishervals.Select(p => p.Replace(" ", "")); // remove all whitespace

                Console.WriteLine(fishervals.Length);

                double fisher1; double.TryParse(fishervals[0], out fisher1);
                double fisher2; double.TryParse(fishervals[1], out fisher2);
                double fisher = (fisher1 + fisher2) / 2;

                double mark; double.TryParse(fishervals[2], out mark);

                // trade logic
                double sell     = 1.9;
                double buy      = sell * -1;
                double quantity = 0;
                double entry    = 0;
                double movement = 0;
                string dir      = "";

                // close in-profit position logic
                string  pos        = deribit.getPosition("ETH-PERPETUAL");
                JObject posjobject = JObject.Parse(pos);
                dir      = (string)posjobject.SelectToken("result.direction");
                entry    = (double)posjobject.SelectToken("result.average_price");
                movement = (mark / entry) - 1; // zero it out for comparisons (not actually profit - used for directionality)

                string  acc     = deribit.getAccountSummary("ETH");
                JObject accjson = JObject.Parse(acc);
                double.TryParse(accjson.SelectToken("result.available_funds").ToString(), out quantity);
                quantity = (quantity * mark) / 5;
                quantity = Math.Round(quantity);

                if (quantity < 1)
                {
                    Console.WriteLine("fund account"); return(Ok());
                }                 // liqd kek

                if (fisher < buy) // buy logic (swing low)
                {
                    deribit.marketOrder("buy", "ETH-PERPETUAL", quantity.ToString());
                    Console.WriteLine($"buy {quantity} - ETHUSD @ {mark}");

                    if (dir == "sell" && movement < 0)
                    {
                        // take profit on successful short
                        deribit.marketOrder("buy", "ETH-PERPETUAL", quantity.ToString());
                    }
                }
                else if (fisher > sell) // sell logic (swing high)
                {
                    deribit.marketOrder("sell", "ETH-PERPETUAL", quantity.ToString());
                    Console.WriteLine($"sell {quantity} - ETHUSD @ {mark}");

                    if (dir == "buy" && movement > 0)
                    {
                        // take profit on successful long
                        deribit.marketOrder("sell", "ETH-PERPETUAL", quantity.ToString());
                    }
                }

                return(Ok());
            }
            catch
            {
                Console.WriteLine("error");
                return(BadRequest());
            }
        }
Esempio n. 21
0
        public List <PlanItem> GetPlanByAny(Guid?planUId, string name, string uniqueName, string planFile, bool?planFileIsUri, Guid?planContainerUId, string createdBy, DateTime?createdTime, string modifiedBy,
                                            DateTime?modifiedTime)
        {
            List <PlanItem> planList = new List <PlanItem>();

            if (string.IsNullOrWhiteSpace(PlanTable))
            {
                throw new Exception("Plan table name must be specified.");
            }

            try
            {
                Table table = Table.LoadTable(_client, PlanTable);

                ScanFilter scanFilter = new ScanFilter();

                if (planUId != null && planUId != Guid.Empty)
                {
                    scanFilter.AddCondition("UId", ScanOperator.Equal, planUId);
                }
                if (!string.IsNullOrWhiteSpace(name))
                {
                    scanFilter.AddCondition("Name", ScanOperator.Equal, name);
                }
                if (!string.IsNullOrWhiteSpace(uniqueName))
                {
                    scanFilter.AddCondition("UniqueName", ScanOperator.Equal, uniqueName);
                }
                if (!string.IsNullOrWhiteSpace(planFile))
                {
                    scanFilter.AddCondition("PlanFile", ScanOperator.Equal, planFile);
                }
                if (planFileIsUri != null)
                {
                    scanFilter.AddCondition("PlanFileIsUri", ScanOperator.Equal, planFileIsUri);
                }
                if (planContainerUId != null && planContainerUId != Guid.Empty)
                {
                    scanFilter.AddCondition("PlanContainerUId", ScanOperator.Equal, planContainerUId);
                }
                if (!string.IsNullOrWhiteSpace(createdBy))
                {
                    scanFilter.AddCondition("AuditCreatedBy", ScanOperator.Equal, createdBy);
                }
                if (createdTime != null)
                {
                    scanFilter.AddCondition("AuditCreatedTime", ScanOperator.Equal, createdTime);
                }
                if (!string.IsNullOrWhiteSpace(modifiedBy))
                {
                    scanFilter.AddCondition("AuditModifiedBy", ScanOperator.Equal, modifiedBy);
                }
                if (modifiedTime != null)
                {
                    scanFilter.AddCondition("AuditModifiedTime", ScanOperator.Equal, modifiedTime);
                }

                if (scanFilter.ToConditions().Count == 0)
                {
                    throw new Exception("At least one filter condition must be specified.");
                }

                Search search = table.Scan(scanFilter);

                do
                {
                    List <Document> documentList = search.GetNextSet();
                    if (documentList.Count == 0)
                    {
                        throw new Exception("Plan cannot be found.");
                    }

                    foreach (Document document in documentList)
                    {
                        string   json = document.ToJsonPretty();
                        PlanItem plan = JsonConvert.DeserializeObject <PlanItem>(json, _settings);
                        planList.Add(plan);
                    }
                } while (!search.IsDone);
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                throw;
            }

            return(planList);
        }
        public async Task <ResponseModel <IdentityViewModel> > Register(UserSignUpModel model)
        {
            ResponseModel <IdentityViewModel> response = new ResponseModel <IdentityViewModel>();

            try
            {
                ScanFilter filter = new ScanFilter();
                filter.AddCondition("Email", ScanOperator.Equal, model.Email);
                filter.AddCondition("IsDeleted", ScanOperator.Equal, false);
                IEnumerable <UserDetails> UserList = await _context.GetAsync(filter);

                if (!UserList.Any())
                {
                    model.Password = CommonHelper.CreatePassword(8);
                    UserDetails userModel = _mapper.Map <UserDetails>(model);
                    userModel.AddedOn  = DateTime.UtcNow;
                    userModel.Salt     = Hasher.GetSalt();
                    userModel.Password = Hasher.GenerateHash(userModel.Password + userModel.Salt);
                    userModel.UserName = model.Email;
                    userModel.Email    = model.Email;
                    userModel.Id       = Guid.NewGuid().ToString();
                    //Need to pull dynamicly from db
                    Roles userRole = new Roles();
                    userRole.Description = "";
                    userRole.Id          = Guid.NewGuid().ToString();
                    userRole.RomeName    = StaticRoles.Student;
                    userModel.Usertype   = userRole.RomeName;
                    userModel.Roles      = userRole;
                    userModel.IsActive   = true;
                    userModel.IsDeleted  = false;
                    userModel.IsStatic   = false;
                    await this._context.SaveAsync(userModel);

                    response.Entity = _mapper.Map <IdentityViewModel>(userModel);
                    response.ReturnMessage.Add("User has been Added successfully.");
                    response.Status = true;

                    // Sending User Registration Edm
                    // MailHelper _mailServices = new MailHelper();

                    //tem fixes
                    StringBuilder sb = new StringBuilder();
                    sb.Append("UserName :"******"password :"******"", userModel.Email, "Welcome", sb.ToString(), "", "");
                    await _mailService.SendMail("", userModel.Email, "Welcome to inventory management system", sb.ToString());
                }
                else
                {
                    response.Entity = new IdentityViewModel();
                    response.ReturnMessage.Add("User already exist.");
                    response.Status = true;
                }
            }
            catch (Exception ex)
            {
                response.Status = false;
                response.ReturnMessage.Add(ex.Message);
            }
            return(response);
        }
Esempio n. 23
0
        private void BtnDisplay_Click(object sender, EventArgs e)
        {
            //Set a local DB context
            context = new DynamoDBContext(client);

            Table StudentTable = Table.LoadTable(client, tableName);

            ScanFilter scanFilter = new ScanFilter();

            scanFilter.AddCondition("buy", ScanOperator.GreaterThanOrEqual, 1);

            Search search = StudentTable.Scan(scanFilter);

            List <Document> documentList = new List <Document>();

            DGV.Rows.Clear();
            DGV.ColumnCount = 4;

            DGV.Columns[0].Width = 270;

            DataGridViewRow row = new DataGridViewRow();

            row.CreateCells(DGV);
            row.Cells[0].Value             = "Student Id";
            row.Cells[1].Value             = "Student Name";
            row.Cells[2].Value             = "College Name";
            row.Cells[3].Value             = "Class Name";
            row.DefaultCellStyle.BackColor = Color.Blue;
            row.DefaultCellStyle.ForeColor = Color.White;
            DGV.Rows.Add(row);
            do
            {
                documentList = search.GetNextSet();
                foreach (var document in documentList)
                {
                    row = new DataGridViewRow();
                    row.CreateCells(DGV);
                    foreach (var attribute in document.GetAttributeNames())
                    {
                        string stringValue = null;
                        var    value       = document[attribute];
                        if (value is Primitive)
                        {
                            stringValue = value.AsPrimitive().Value.ToString();
                        }
                        else if (value is PrimitiveList)
                        {
                            stringValue = string.Join(",", (from primitive
                                                            in value.AsPrimitiveList().Entries

                                                            select primitive.Value).ToArray());
                        }
                        if (attribute == "date")
                        {
                            row.Cells[0].Value = stringValue;
                        }
                        else if (attribute == "buy")
                        {
                            row.Cells[1].Value = stringValue;
                        }
                        else if (attribute == "sell")
                        {
                            row.Cells[2].Value = stringValue;
                        }
                        else if (attribute == "fix")
                        {
                            row.Cells[3].Value = stringValue;
                        }
                    }
                    DGV.Rows.Add(row);
                }
            } while (!search.IsDone);

            foreach (DataGridViewColumn c in DGV.Columns)
            {
                c.DefaultCellStyle.Font = new Font("Arial", 12F, GraphicsUnit.Pixel);
            }

            PnlGrid.Visible = true;
        }
Esempio n. 24
0
        private void TestHashRangeTable(Table hashRangeTable, DynamoDBEntryConversion conversion)
        {
            // Put an item
            Document doc1 = new Document();

            doc1["Name"]     = "Alan";
            doc1["Age"]      = 31;
            doc1["Company"]  = "Big River";
            doc1["Score"]    = 120;
            doc1["IsTester"] = true;
            doc1["Manager"]  = "Barbara";
            doc1["Aliases"]  = new HashSet <string> {
                "Al", "Steve"
            };
            doc1["PastManagers"] = new List <string> {
                "Carl", "Karl"
            };
            hashRangeTable.PutItem(doc1);

            // Update a non-existent item creates the item
            Document doc2 = new Document();

            doc2["Name"]     = "Chuck";
            doc2["Age"]      = 30;
            doc2["Company"]  = "Big River";
            doc2["Score"]    = 94;
            doc1["IsTester"] = false;
            doc2["Manager"]  = "Barbara";
            doc2["Aliases"]  = new HashSet <string> {
                "Charles"
            };
            hashRangeTable.UpdateItem(doc2);

            // Save more items
            Document doc3 = new Document();

            doc3["Name"]     = "Diane";
            doc3["Age"]      = 40;
            doc3["Company"]  = "Madeira";
            doc1["IsTester"] = true;
            doc3["Score"]    = 140;
            doc3["Manager"]  = "Eva";
            hashRangeTable.UpdateItem(doc3);
            var oldDoc3 = doc3.Clone() as Document;

            // Changing the range key will force a creation of a new item
            doc3["Age"]   = 24;
            doc3["Score"] = 101;
            hashRangeTable.UpdateItem(doc3);

            // Get item
            var retrieved = hashRangeTable.GetItem("Alan", 31);

            // Verify retrieved document
            Assert.IsTrue(AreValuesEqual(doc1, retrieved, conversion));
            var tagsRetrieved = retrieved["Aliases"];

            Assert.IsTrue(tagsRetrieved is PrimitiveList);
            Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count);
            // Test bool storage for different conversions
            var isTesterRetrieved = retrieved["IsTester"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual("1", isTesterRetrieved.AsPrimitive().Value as string);
            }
            else
            {
                Assert.IsTrue(isTesterRetrieved is DynamoDBBool);
            }
            // Test HashSet<string> storage for different conversions
            var pastManagersRetrieved = retrieved["PastManagers"];

            if (conversion == DynamoDBEntryConversion.V1)
            {
                Assert.AreEqual(2, pastManagersRetrieved.AsPrimitiveList().Entries.Count);
            }
            else
            {
                Assert.AreEqual(2, pastManagersRetrieved.AsDynamoDBList().Entries.Count);
            }

            // Get item using GetItem overloads that expect a key in different ways
            retrieved = hashRangeTable.GetItem(doc2);
            Assert.IsTrue(AreValuesEqual(doc2, retrieved, conversion));
            retrieved = hashRangeTable.GetItem(oldDoc3, new GetItemOperationConfig {
                ConsistentRead = true
            });
            Assert.IsTrue(AreValuesEqual(oldDoc3, retrieved, conversion));
            retrieved = hashRangeTable.GetItem("Diane", 24, new GetItemOperationConfig {
                ConsistentRead = true
            });
            Assert.IsTrue(AreValuesEqual(doc3, retrieved, conversion));

            // Scan the hash-and-range-key table
            var items = hashRangeTable.Scan(new ScanFilter()).GetRemaining();

            Assert.AreEqual(4, items.Count);

            // Scan by pages
            var search = hashRangeTable.Scan(new ScanOperationConfig {
                Limit = 1
            });

            items.Clear();
            while (!search.IsDone)
            {
                var set = search.GetNextSet();
                items.AddRange(set);
            }
            Assert.AreEqual(4, items.Count);

            // Scan in parallel
            var segment1 = hashRangeTable.Scan(new ScanOperationConfig {
                Segment = 0, TotalSegments = 2
            }).GetRemaining();
            var segment2 = hashRangeTable.Scan(new ScanOperationConfig {
                Segment = 1, TotalSegments = 2
            }).GetRemaining();

            Assert.AreEqual(4, segment1.Count + segment2.Count);

            // Query items
            items = hashRangeTable.Query("Diane", new QueryFilter()).GetRemaining();
            Assert.AreEqual(2, items.Count);

            // Query local index
            items = hashRangeTable.Query(new QueryOperationConfig
            {
                IndexName = "LocalIndex",
                Filter    = new QueryFilter("Name", QueryOperator.Equal, "Diane")
            }).GetRemaining();
            Assert.AreEqual(2, items.Count);

            // Query global index
            var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "Big River");

            queryFilter.AddCondition("Score", QueryOperator.GreaterThan, 100);
            items = hashRangeTable.Query(new QueryOperationConfig
            {
                IndexName = "GlobalIndex",
                Filter    = queryFilter
            }).GetRemaining();
            Assert.AreEqual(1, items.Count);

            // Scan local index
            var scanFilter = new ScanFilter();

            scanFilter.AddCondition("Name", ScanOperator.Equal, "Diane");
            items = hashRangeTable.Scan(new ScanOperationConfig
            {
                IndexName = "LocalIndex",
                Filter    = scanFilter
            }).GetRemaining();
            Assert.AreEqual(2, items.Count);

            // Scan global index
            scanFilter = new ScanFilter();
            scanFilter.AddCondition("Company", ScanOperator.Equal, "Big River");
            scanFilter.AddCondition("Score", ScanOperator.GreaterThan, 100);
            items = hashRangeTable.Query(new QueryOperationConfig
            {
                IndexName = "GlobalIndex",
                Filter    = queryFilter
            }).GetRemaining();
            Assert.AreEqual(1, items.Count);
        }
        public async Task <ResponseModel <List <InventoryHistory> > > GetHistoryLog(SearchParam fipso, SecurityModel securityModel)
        {
            ResponseModel <List <InventoryHistory> > response = new ResponseModel <List <InventoryHistory> >();

            try
            {
                PagingInfo paging = new PagingInfo();
                paging.CurrentPage    = fipso.CurrentPage;
                paging.PageSize       = fipso.PageSize;
                paging.SortDirection  = fipso.SortDirection;
                paging.SortExpression = fipso.SortExpression;

                ScanFilter filter = new ScanFilter();

                if (!string.IsNullOrEmpty(fipso.Status))
                {
                    filter.AddCondition("ReturnStatus", ScanOperator.Equal, fipso.Status);
                }

                if (string.IsNullOrEmpty(fipso.SortExpression))
                {
                    fipso.SortExpression = "FirstName";
                }
                if (paging.SortDirection != string.Empty)
                {
                    fipso.SortExpression = fipso.SortExpression + " " + paging.SortDirection;
                }
                int rows = 0;
                IEnumerable <InventoryHistory> bookshistory = await _dynamoDbHistoryContex.GetAsync(filter);

                var filterData = new List <InventoryHistory>();
                if (!string.IsNullOrEmpty(fipso.SearchText))
                {
                    filterData = bookshistory.Where(x => x.BookName.ToLower().Contains(fipso.SearchText.ToLower()) ||
                                                    x.BookAuthor.ToLower().Contains(fipso.SearchText) ||
                                                    x.BookPublication.ToLower().Contains(fipso.SearchText)
                                                    ).ToList();
                }
                else
                {
                    filterData = bookshistory.ToList();
                }
                var resultList = from p in filterData.AsQueryable() select p;
                rows = resultList.Count();

                var bookList = resultList.OrderBy(fipso.SortExpression).Skip((paging.CurrentPage - 1) * paging.PageSize).Take(paging.PageSize).ToList();
                paging.TotalRows  = rows;
                paging.TotalPages = Functions.CalculateTotalPages(rows, paging.PageSize);

                response.Entity     = bookList;
                response.TotalRows  = paging.TotalRows;
                response.TotalPages = paging.TotalPages;
                response.Status     = true;
            }
            catch (AmazonServiceException amazonEx)
            {
                response.Status = false;
                response.ReturnMessage.Add($"Amazon error in table operation! Error: {amazonEx.Message}");
            }
            catch (System.Exception ex)
            {
                response.Status = false;
                response.ReturnMessage.Add(ex.Message);
            }
            return(response);
        }
Esempio n. 26
0
        public static void Main()
        {
            bool response;
            var  step = 1;

            //  1.  Create a DynamoDB client connected to a DynamoDB-Local instance
            Console.WriteLine(StepString, step,
                              "Create a DynamoDB client connected to a DynamoDB-Local instance");
            response = createClient(UseDynamoDbLocal);

            if (!response)
            {
                Console.WriteLine("Could not create client, bye.");
                return;
            }

            pause();
            step++;

            // Check whether table exists.
            var tableExists = CheckingTableExistence_async(MoviesTableName);

            if (tableExists.Result)
            {
                Console.WriteLine("     -- Table already exists...");

                if (DeleteExistingTable)
                {
                    var deleteTable = DeletingTable_async(MoviesTableName);

                    if (!deleteTable.Result)
                    {
                        Console.WriteLine("Could not delete existing table, bye.");
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            //  2.  Create a table for movie data asynchronously
            Console.WriteLine(StepString, step, "Create a table for movie data");

            var createTable = CreateTable_async(MoviesTableName,
                                                MovieItemsAttributes,
                                                MoviesKeySchema,
                                                MoviesTableProvisionedThroughput);

            if (!createTable.Result)
            {
                Console.WriteLine("Could not create table, bye.");
                return;
            }

            try
            {
                MoviesTable            = Table.LoadTable(DdbIntro.Client, MoviesTableName);
                MoviesTableDescription = GetTableDescription(MoviesTableName).Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    " Error: Could not access the new '{0}' table after creating it;\n" +
                    "        Reason: {1}.", MoviesTableName, ex.Message);

                return;
            }

            pause();
            step++;

            //  3.  Load movie data into the Movies table asynchronously
            if ((MoviesTableDescription != null) &&
                (MoviesTableDescription.ItemCount == 0))
            {
                Console.WriteLine(StepString, step, "Load movie data into the Movies table");
                var loadData = LoadingData_async(MoviesTable, MovieDataPath);

                if (!loadData.Result)
                {
                    Console.WriteLine("Could not load data into table.");
                    return;
                }
            }

            pause();
            step++;

            //  4.  Add a new movie to the Movies table
            Document newItemDocument = new Document
            {
                ["year"]  = year,
                ["title"] = title,
                ["info"]  = Document.FromJson(
                    "{\"plot\" : \"Nothing happens at all.\",\"rating\" : 0}")
            };

            Console.WriteLine(StepString, step, "Add a new movie to the Movies table");

            var writeNew = WritingNewMovie_async(newItemDocument);

            if (!writeNew.Result)
            {
                Console.WriteLine("Could not add movie to table, bye.");
                return;
            }

            pause();
            step++;

            //  5.  Read and display the new movie record that was just added
            Console.WriteLine(StepString, step, "Read the new movie record that was just added");

            var movieRecord = ReadingMovie_async(year, title);

            pause();

            if (movieRecord.Result.Count < 1)
            {
                Console.WriteLine("Could not retrieve info about new movie.");
            }
            else
            {
                Console.WriteLine("Here is the movie:");
                showDocument(movieRecord.Result);
            }

            pause();
            step++;

            //  6.  Update the new movie record in various ways
            //-------------------------------------------------
            //  6a.  Create an UpdateItemRequest to:
            //       -- modify the plot and rating of the new movie, and
            //       -- add a list of actors to it
            Console.WriteLine(StepString, step + "a",
                              "Change the plot and rating for the new movie and add a list of actors");
            UpdateItemRequest updateRequest = new UpdateItemRequest()
            {
                TableName = MoviesTableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { PartitionKeyName, new AttributeValue {
                          N = "2018"
                      } },
                    { SortKeyName, new AttributeValue {
                          S = "The Big New Movie"
                      } }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":r", new AttributeValue {
                          N = "5.5"
                      } },
                    { ":p", new AttributeValue {
                          S = "Everything happens all at once!"
                      } },
                    { ":a", new AttributeValue
                      {
                          L = new List <AttributeValue>
                          {
                              new AttributeValue {
                                  S = "Larry"
                              },
                              new AttributeValue {
                                  S = "Moe"
                              },
                              new AttributeValue {
                                  S = "Curly"
                              }
                          }
                      } }
                },
                UpdateExpression = "SET info.rating = :r, info.plot = :p, info.actors = :a",
                ReturnValues     = "NONE"
            };

            var updateMovie = UpdatingMovie_async(updateRequest);

            if (!updateMovie.Result)
            {
                Console.WriteLine("Could not update movie, bye.");
                return;
            }

            pause();

            //  6b  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(StepString, step + "b",
                              "Increment the new movie's rating atomically");
            Console.WriteLine("  -- Incrementing the rating of the new movie by 1...");

            updateRequest.ExpressionAttributeValues = new Dictionary <string, AttributeValue>
            {
                { ":inc", new AttributeValue {
                      N = "1"
                  } }
            };

            updateRequest.UpdateExpression = "SET info.rating = info.rating + :inc";

            updateMovie = UpdatingMovie_async(updateRequest);
            if (!updateMovie.Result)
            {
                Console.WriteLine("Could not update movie, bye.");
                return;
            }

            pause();

            //  6c  Change the UpdateItemRequest so as to increment the rating of the
            //      new movie, and then make the update request asynchronously.
            Console.WriteLine(StepString, step + "c",
                              "Now try the same increment again with a condition that fails... ");
            Console.WriteLine("  -- Now trying to increment the new movie's rating, but this time\n" +
                              "     ONLY ON THE CONDITION THAT the movie has more than 3 actors...");
            updateRequest.ExpressionAttributeValues.Add(":n", new AttributeValue {
                N = "3"
            });
            updateRequest.ConditionExpression = "size(info.actors) > :n";

            updateMovie = UpdatingMovie_async(updateRequest);
            if (!updateMovie.Result)
            {
                Console.WriteLine("Could not update movie, as expected.");
            }

            pause();
            step++;

            //  7.  Try conditionally deleting the movie that we added

            //  7a.  Try conditionally deleting the movie that we added
            Console.WriteLine(StepString, step + "a",
                              "Try deleting the new movie record with a condition that fails");
            Console.WriteLine("  -- Trying to delete the new movie,\n" +
                              "     -- but ONLY ON THE CONDITION THAT its rating is 5.0 or less...");
            Expression condition = new Expression();

            condition.ExpressionAttributeValues[":val"] = 5.0;
            condition.ExpressionStatement = "info.rating <= :val";

            var deleteItem = DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition);

            if (!deleteItem.Result)
            {
                Console.WriteLine("Could not delete movie, as expected.");
            }

            pause();

            //  7b.  Now increase the cutoff to 7.0 and try to delete again...
            Console.WriteLine(StepString, step + "b",
                              "Now increase the cutoff to 7.0 and try to delete the movie again...");
            Console.WriteLine("  -- Now trying to delete the new movie again,\n" +
                              "     -- but this time on the condition that its rating is 7.0 or less...");
            condition.ExpressionAttributeValues[":val"] = 7.0;

            deleteItem = DeletingItem_async(MoviesTable, 2018, "The Big New Movie", condition);
            if (!deleteItem.Result)
            {
                Console.WriteLine("Could not delete movie, bye.");
                return;
            }

            pause();
            step++;

            //  8.  Query the Movies table in 3 different ways
            Search search;

            //  8a. Just query on the year
            Console.WriteLine(StepString, step + "a",
                              "Query the Movies table using a Search object for all movies from 1985");
            Console.WriteLine("  -- First, create a Search object...");
            try
            {
                search = MoviesTable.Query(1985, new Expression());
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                return;
            }

            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query:");
            pause();

            var searchResponse = SearchListing_async(search);

            if (searchResponse.Result.Count < 1)
            {
                Console.WriteLine("Did not get any search results, bye.");
                return;
            }

            foreach (var docs in searchResponse.Result)
            {
                foreach (var doc in docs)
                {
                    showMovieDocShort(doc);
                }
            }

            //  8b. SearchListing_async
            Console.WriteLine(StepString, step + "b",
                              "Query for 1992 movies with titles from B... to Hzz... using Table.Query");
            Console.WriteLine("  -- Now setting up a QueryOperationConfig for the 'Search'...");
            QueryOperationConfig config = new QueryOperationConfig();

            config.Filter = new QueryFilter();
            config.Filter.AddCondition("year", QueryOperator.Equal, new DynamoDBEntry[] { 1992 });
            config.Filter.AddCondition("title", QueryOperator.Between, new DynamoDBEntry[] { "B", "Hzz" });
            config.AttributesToGet = new List <string> {
                "year", "title", "info"
            };
            config.Select = SelectValues.SpecificAttributes;
            Console.WriteLine("     -- Creating the Search object based on the QueryOperationConfig");

            try
            {
                search = MoviesTable.Query(config);
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                return;
            }

            Console.WriteLine("     -- Successfully created the Search object,\n" +
                              "        so now we'll display the movies retrieved by the query:");
            pause();

            searchResponse = SearchListing_async(search);
            if (searchResponse.Result.Count < 1)
            {
                Console.WriteLine("Did not get any search results, bye.");
                return;
            }

            foreach (var docs in searchResponse.Result)
            {
                foreach (var doc in docs)
                {
                    showMovieDocShort(doc);
                }
            }

            //  8c. Query using a QueryRequest
            Console.WriteLine(StepString, step + "c",
                              "Query the Movies table for 1992 movies with titles from M... to Tzz...");
            Console.WriteLine("  -- Next use a low-level query to retrieve a selection of movie attributes");
            QueryRequest qRequest = new QueryRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":qYr", new AttributeValue {
                          N = "1992"
                      } },
                    { ":tSt", new AttributeValue {
                          S = "M"
                      } },
                    { ":tEn", new AttributeValue {
                          S = "Tzz"
                      } }
                },
                KeyConditionExpression = "#yr = :qYr and title between :tSt and :tEn",
                ProjectionExpression   = "#yr, title, info.actors[0], info.genres, info.running_time_secs"
            };

            Console.WriteLine("     -- Using a QueryRequest to get the lead actor and genres of\n" +
                              "        1992 movies with titles between 'M...' and 'Tzz...'.");

            var clientQuery = ClientQuerying_async(qRequest);

            if (clientQuery.Result.Count < 1)
            {
                Console.WriteLine("Could not query for movie, bye.");
                return;
            }

            Console.WriteLine("         Here are the movies retrieved:" +
                              "         --------------------------------------------------------------------------");
            foreach (Dictionary <string, AttributeValue> item in clientQuery.Result.Items)
            {
                showMovieAttrsShort(item);
            }

            Console.WriteLine("     -- Retrieved {0} movies.", clientQuery.Result.Items.Count);

            pause();
            step++;

            //  9.  Try scanning the movies table to retrieve movies from several decades
            //  9a. Use Table.Scan with a Search object and a ScanFilter to retrieve movies from the 1950s
            Console.WriteLine(StepString, step + "a",
                              "Scan the Movies table to retrieve all movies from the 1950's");
            ScanFilter filter = new ScanFilter();

            filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 });
            ScanOperationConfig scanConfig = new ScanOperationConfig
            {
                Filter = filter
            };

            Console.WriteLine("     -- Creating a Search object based on a ScanFilter");

            try
            {
                search = MoviesTable.Scan(scanConfig);
            }
            catch (Exception ex)
            {
                Console.WriteLine("     ERROR: Failed to create the Search object because:\n            " +
                                  ex.Message);
                return;
            }

            Console.WriteLine("     -- Successfully created the Search object");

            pause();

            searchResponse = SearchListing_async(search);
            if (searchResponse.Result.Count < 1)
            {
                Console.WriteLine("Did not get any search results, bye.");
                return;
            }

            foreach (var docs in searchResponse.Result)
            {
                foreach (var doc in docs)
                {
                    showMovieDocShort(doc);
                }
            }


            //  9b. Use AmazonDynamoDBClient.Scan to retrieve movies from the 1960s
            Console.WriteLine(StepString, step + "b",
                              "Use a low-level scan to retrieve all movies from the 1960's");
            Console.WriteLine("     -- Using a ScanRequest to get movies from between 1960 and 1969");
            ScanRequest sRequest = new ScanRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":y_a", new AttributeValue {
                          N = "1960"
                      } },
                    { ":y_z", new AttributeValue {
                          N = "1969"
                      } },
                },
                FilterExpression     = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs"
            };

            var clientScan = ClientScanning_async(sRequest);

            Console.WriteLine("         Here are the movies retrieved:\n" +
                              "         --------------------------------------------------------------------------");
            foreach (Dictionary <string, AttributeValue> item in clientScan.Result.Items)
            {
                showMovieAttrsShort(item);
            }

            Console.WriteLine("     -- Retrieved {0} movies.", clientScan.Result.Items.Count);

            pause();
            step++;

            //  10.  Finally, delete the Movies table and all its contents
            Console.WriteLine(StepString, step,
                              "Finally, delete the Movies table and all its contents");

            var deletingTable = DeletingTable_async(MoviesTableName);

            if (!deletingTable.Result)
            {
                Console.WriteLine("Could not delete the table.");
            }


            Console.WriteLine(
                "\n=================================================================================" +
                "\n            This concludes the DynamoDB Getting-Started demo program" +
                "\n=================================================================================");

            pause();
        }
Esempio n. 27
0
        public async Task <IActionResult> login([FromHeader] string Authorization, [FromHeader] string User, [FromHeader] string Password)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Document searchdetails = new Document();

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"].ToString() == "test" && doc["DefaultId"].ToString() == "hello")
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }
                }
                catch
                {
                    return(BadRequest("authorizaion failed"));
                }

                Table userreg = Table.LoadTable(amazonDynamoDBClient, "UserRegistry");
                var   obj     = new object();

                try
                {
                    Document userregdoc = await userreg.GetItemAsync(User);

                    if (User == userregdoc["User"].ToString() && Password == userregdoc["Password"].ToString())
                    {
                        Document ret = await UserTable.GetItemAsync(User);

                        obj = new { Id = ret["DefaultId"].ToString(), Secret = ret["DefaultSecret"].ToString() };
                    }
                    else
                    {
                        return(BadRequest("fail"));
                    }
                }
                catch
                {
                    return(BadRequest("error"));
                }

                string json = JsonConvert.SerializeObject(obj);
                return(Content(json, "application/json"));
            }
            catch
            {
                return(BadRequest());
            }
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            // Get an AmazonDynamoDBClient for the local DynamoDB database
            AmazonDynamoDBClient client = GetLocalClient();

            // Get a Table object for the table that you created in Step 1
            Table table = GetTableObject(client, "Movies");

            if (table == null)
            {
                PauseForDebugWindow();
                return;
            }


            /*-----------------------------------------------------------------------
             *  4.2a:  Call Table.Scan to return the movies released in the 1950's,
             *         displaying title, year, lead actor and lead director.
             *-----------------------------------------------------------------------*/
            ScanFilter filter = new ScanFilter();

            filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 });
            ScanOperationConfig config = new ScanOperationConfig
            {
                AttributesToGet = new List <string> {
                    "year, title, info"
                },
                Filter = filter
            };
            Search search = table.Scan(filter);

            // Display the movie information returned by this query
            Console.WriteLine("\n\n Movies released in the 1950's (Document Model):" +
                              "\n--------------------------------------------------");
            List <Document> docList = new List <Document>();
            Document        infoDoc;
            string          movieFormatString = "    \"{0}\" ({1})-- lead actor: {2}, lead director: {3}";

            do
            {
                try
                {
                    docList = search.GetNextSet();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message);
                    break;
                }
                foreach (var doc in docList)
                {
                    infoDoc = doc["info"].AsDocument();
                    Console.WriteLine(movieFormatString,
                                      doc["title"],
                                      doc["year"],
                                      infoDoc["actors"].AsArrayOfString()[0],
                                      infoDoc["directors"].AsArrayOfString()[0]);
                }
            } while (!search.IsDone);


            /*-----------------------------------------------------------------------
             *  4.2b:  Call AmazonDynamoDBClient.Scan to return all movies released
             *         in the 1960's, only downloading the title, year, lead
             *         actor and lead director attributes.
             *-----------------------------------------------------------------------*/
            ScanRequest sRequest = new ScanRequest
            {
                TableName = "Movies",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#yr", "year" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":y_a", new AttributeValue {
                          N = "1960"
                      } },
                    { ":y_z", new AttributeValue {
                          N = "1969"
                      } },
                },
                FilterExpression     = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors[0]"
            };

            ScanResponse sResponse;

            try
            {
                sResponse = client.Scan(sRequest);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n Error: Low-level scan failed, because: " + ex.Message);
                PauseForDebugWindow();
                return;
            }

            // Display the movie information returned by this scan
            Console.WriteLine("\n\n Movies released in the 1960's (low-level):" +
                              "\n-------------------------------------------");
            foreach (Dictionary <string, AttributeValue> item in sResponse.Items)
            {
                Dictionary <string, AttributeValue> info = item["info"].M;
                Console.WriteLine(movieFormatString,
                                  item["title"].S,
                                  item["year"].N,
                                  info["actors"].L[0].S,
                                  info["directors"].L[0].S);
            }
        }
Esempio n. 29
0
        public async Task <IActionResult> positions([FromHeader] string Authorization)
        {
            try
            {
                long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Document searchdetails = new Document();

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; //Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id)
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }
                }
                catch
                {
                    return(BadRequest("authorizaion failed"));
                }

                Table    PosTable = Table.LoadTable(amazonDynamoDBClient, "PositionRegistry");
                Document posdoc   = await PosTable.GetItemAsync(searchdetails["Email"].ToString());

                if (posdoc["POSSPXUSD"].ToString() == "na")
                {
                    var    returnobj  = new { AvailableBalance = posdoc["AvailableBalance"].ToString(), POSSPXUSD = posdoc["POSSPXUSD"].ToString() };
                    string returnjson = JsonConvert.SerializeObject(returnobj);
                    return(Content(returnjson, "application/json"));
                }
                else
                {
                    var returnobj = new
                    {
                        AvailableBalance = posdoc["AvailableBalance"].ToString(),
                        InitialMargin    = posdoc["InitialMargin"].ToString(),
                        MarginBalance    = posdoc["MarginBalance"].ToString(),
                        PNL            = posdoc["PNL"].ToString(),
                        PositionSPXUSD = posdoc["POSSPXUSD"].ToString(),
                        EntrySPXUSD    = posdoc["POSSPXUSDEntry"].ToString(),
                        SPXValue       = posdoc["SPXValue"].ToString(),
                        XBTValue       = posdoc["XBTValue"].ToString()
                    };
                    string returnjson = JsonConvert.SerializeObject(returnobj);
                    return(Content(returnjson, "application/json"));
                }
            }
            catch
            {
                return(BadRequest("error"));
            }
        }
Esempio n. 30
0
        public static void RunDocumentModelSample()
        {
            Console.WriteLine("Loading Businesses table");
            Table table = Table.LoadTable(client, "Businesses");

            Console.WriteLine("Creating and saving first item");
            Document chainStore2 = new Document();

            chainStore2["Name"]     = "Big Sales Inc";
            chainStore2["Id"]       = 2;
            chainStore2["Owner"]    = "Big Sales Corp";
            chainStore2["Managers"] = new List <string> {
                "Samantha Jones", "Richard Frost"
            };
            chainStore2["FoundedDate"] = new DateTime(1980, 7, 4);
            chainStore2["Address"]     = "123 Main Street, New York, New York";
            chainStore2["Employees"]   = 46;
            chainStore2["State"]       = "NY";
            table.PutItem(chainStore2);

            Console.WriteLine("Creating and saving first item");
            Document chainStore13 = new Document();

            chainStore13["Name"]     = "Big Sales Inc";
            chainStore13["Id"]       = 13;
            chainStore13["Owner"]    = "Big Sales Corp";
            chainStore13["Managers"] = new List <string> {
                "Anil Garg", "Alex Short"
            };
            chainStore13["FoundedDate"] = new DateTime(1999, 3, 15);
            chainStore13["Address"]     = "1999 West Ave, Chicago, Illinois";
            chainStore13["Employees"]   = 54;
            chainStore13["State"]       = "IL";
            table.PutItem(chainStore13);

            Console.WriteLine("Creating and saving second item");
            Document tinyDiner = new Document();

            tinyDiner["Name"]        = "Tiny Map-themed Diner";
            tinyDiner["Id"]          = 0;
            tinyDiner["Owner"]       = "John Doe";
            tinyDiner["FoundedDate"] = new DateTime(1974, 12, 10);
            tinyDiner["Address"]     = "800 Lincoln Ave, Seattle, Washington";
            tinyDiner["State"]       = "WA";
            table.PutItem(tinyDiner);


            Console.WriteLine("Creating and saving third item");
            Document internetStore = new Document();

            internetStore["Name"]        = "Best Online Store Ever";
            internetStore["Id"]          = 0;
            internetStore["Owner"]       = "Jane Doe";
            internetStore["FoundedDate"] = new DateTime(1994, 2, 19);
            internetStore["Employees"]   = 5;
            internetStore["Url"]         = "http://www.best-online-store-ever.fake";
            internetStore["Phone"]       = "425-555-1234";
            table.PutItem(internetStore);


            Console.WriteLine("Loading item");
            Document doc1 = table.GetItem("Big Sales Inc", 2);

            Console.WriteLine("Attribute counts match (should be true): " +
                              (chainStore2.GetAttributeNames().Count == doc1.GetAttributeNames().Count));

            Console.WriteLine("Loading item...");
            Document doc2 = table.GetItem("Best Online Store Ever", 0);

            Console.WriteLine("Attribute counts match (should be true): " +
                              (chainStore2.GetAttributeNames().Count == doc1.GetAttributeNames().Count));
            Console.WriteLine("Change item: remove one attribute, add one, modify one attribute");
            doc2["Phone"]     = null;
            doc2["Twitter"]   = "best-online-store-ever";
            doc2["Employees"] = 4;
            Console.WriteLine("Updating item");
            table.UpdateItem(doc2);

            Console.WriteLine("Reloading item");
            doc2 = table.GetItem("Best Online Store Ever", 0);
            Console.WriteLine("Phone attribute present (should be false): " + doc2.Contains("Phone"));
            Console.WriteLine("Twitter attribute present (should be true): " + doc2.Contains("Twitter"));
            Console.WriteLine("Employees attribute equals 4: " + (object.Equals(doc2["Employees"].AsPrimitive().Value, "4")));

            Console.WriteLine("Loading nonexistent item");
            Document doc3 = table.GetItem("Big Sales Inc", 3);

            Console.WriteLine("Returned document == null (should be true): " + (doc3 == null));



            Search query;

            Console.WriteLine();
            Console.WriteLine("Querying for items (Equals)");
            query = table.Query("Big Sales Inc", new QueryFilter("Id", QueryOperator.Equal, 2));
            List <Document> queryItems1 = query.GetRemaining();

            Console.WriteLine("Number of items returned (should be 1): " + queryItems1.Count);

            Console.WriteLine();
            Console.WriteLine("Querying for items (Between)");
            QueryFilter filter = new QueryFilter();

            filter.AddCondition("Name", QueryOperator.Equal, "Big Sales Inc");
            filter.AddCondition("Id", QueryOperator.Between, 0, 15);
            QueryOperationConfig queryConfig = new QueryOperationConfig
            {
                Filter = filter,
                Limit  = 1
            };

            query = table.Query(queryConfig);
            int totalItems = 0;

            while (!query.IsDone)
            {
                Console.WriteLine("Retrieving next set (page) of items");
                List <Document> querySet = query.GetNextSet();
                Console.WriteLine("Number of items returned in set (should be 1, unless last set, which will be 0): " + querySet.Count);

                foreach (Document doc in querySet)
                {
                    Console.WriteLine("Retrieving individual properties");
                    Primitive     name     = doc["Name"].AsPrimitive();
                    Primitive     id       = doc["Id"].AsPrimitive();
                    PrimitiveList managers = doc["Managers"].AsPrimitiveList();
                    Console.WriteLine("Name = {0}, Id = {1}, # of managers = {2}", name.Value, id.Value, managers.Entries.Count);
                    totalItems++;
                }
            }
            Console.WriteLine("Total items found (should be 2): " + totalItems);



            Search     scan;
            ScanFilter scanFilter;

            Console.WriteLine();
            Console.WriteLine("Scanning for items (GreaterThan)");
            scanFilter = new ScanFilter();
            scanFilter.AddCondition("Employees", ScanOperator.GreaterThan, 50);
            scan = table.Scan(scanFilter);
            List <Document> scanItems1 = scan.GetRemaining();

            Console.WriteLine("Number of items returned (should be 1): " + scanItems1.Count);

            Console.WriteLine();
            Console.WriteLine("Scanning for items (GreaterThan and LessThan)");
            scanFilter = new ScanFilter();
            scanFilter.AddCondition("Employees", ScanOperator.GreaterThan, 2);
            scanFilter.AddCondition("FoundedDate", ScanOperator.LessThan, new DateTime(1993, 1, 1));
            scan = table.Scan(scanFilter);
            List <Document> scanItems2 = scan.GetRemaining();

            Console.WriteLine("Number of items returned (should be 1): " + scanItems2.Count);


            Console.WriteLine();
            Console.WriteLine("Retrieving an item");
            Document existingDoc = table.GetItem("Big Sales Inc", 13);

            Console.WriteLine("Returned document == null (should be false): " + (existingDoc == null));
            Console.WriteLine("Deleting item");
            table.DeleteItem("Big Sales Inc", 13);
            Console.WriteLine("Retrieving same item");
            existingDoc = table.GetItem("Big Sales Inc", 13);
            Console.WriteLine("Returned document == null (should be true): " + (existingDoc == null));


            Console.WriteLine();
            Console.WriteLine("Scanning for items (no filter) and deleting all");
            scanFilter = new ScanFilter();
            scan       = table.Scan(scanFilter);
            List <Document> scanItems3 = scan.GetRemaining();

            Console.WriteLine("Number of items returned (should be 3): " + scanItems3.Count);
            for (int i = 0; i < scanItems3.Count; i++)
            {
                Document item = scanItems3[i];
                Console.WriteLine("Deleting item {0} of {1}", i + 1, scanItems3.Count);
                table.DeleteItem(item);
            }

            Console.WriteLine("Scanning table again");
            scan       = table.Scan(scanFilter);
            scanItems3 = scan.GetRemaining();
            Console.WriteLine("Number of items returned (should be 0): " + scanItems3.Count);
        }
Esempio n. 31
0
        public async Task <IActionResult> PostOrder([FromHeader] string Authorization, [FromBody] OrderPost orderPost)
        {
            try
            {
                long timestamp          = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                long markpricetimestamp = timestamp;// - DateTime.UtcNow.Second;

                if (Request.ContentType == "application/json")
                {
                    ;
                }
                else
                {
                    return(BadRequest("improper content type"));
                }

                if (orderPost.OrderType == "limit")
                {
                    if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && string.IsNullOrEmpty(orderPost.Price) && orderPost.OrderQuantity == null)
                    {
                        return(BadRequest("bad params"));
                    }
                }
                else if (orderPost.OrderType == "market")
                {
                    if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && orderPost.OrderQuantity == null)
                    {
                        return(BadRequest("bad params"));
                    }
                }
                else
                {
                    return(BadRequest("missing params"));
                }

                Console.WriteLine(orderPost.Contract + orderPost.OrderQuantity + orderPost.OrderType + orderPost.Side);
                if (string.IsNullOrEmpty(orderPost.Contract) || string.IsNullOrEmpty(orderPost.OrderType) || string.IsNullOrEmpty(orderPost.Side) || orderPost.OrderQuantity == null)
                {
                    return(BadRequest("missing variables"));
                }

                AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
                Table    UserTable     = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry");
                Table    SPXMarkTable  = Table.LoadTable(amazonDynamoDBClient, "SPXMarkPrice");
                Document searchdetails = new Document();

                orderPost.OrderType = orderPost.OrderType.ToLower();

                int    orderId;
                string socket;

                try
                {
                    string[] autharray  = Authorization.Split(' ');
                    string   authtype   = autharray[0];
                    string   authstring = autharray[1];

                    if (authtype == "Basic")
                    {
                        byte[] data          = Convert.FromBase64String(authstring);
                        string decodedString = Encoding.UTF8.GetString(data);

                        string[] splitauth = decodedString.Split(":");
                        string   id        = splitauth[0];
                        string   secret    = splitauth[1]; Console.WriteLine(id + secret);

                        ScanOperationConfig scanOperation = new ScanOperationConfig();
                        ScanFilter          scanFilter    = new ScanFilter();
                        scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id);
                        Search          search  = UserTable.Scan(scanOperation);
                        List <Document> details = await search.GetRemainingAsync();

                        foreach (Document doc in details)
                        {
                            if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id)
                            {
                                Console.WriteLine("successful auth");
                                searchdetails = doc;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        searchdetails["Email"].ToString();
                    }
                    else
                    {
                        return(BadRequest("Bad authorization"));
                    }

                    // verifiy valid account balance
                    Document userdetails = await UserTable.GetItemAsync(searchdetails["Email"].ToString());

                    Document markprice = new Document();
                    markpricetimestamp = markpricetimestamp - (markpricetimestamp % 5);
                    try { markprice = await SPXMarkTable.GetItemAsync(markpricetimestamp.ToString()); markprice["BTCPrice"].ToString(); }
                    catch { try { markpricetimestamp -= 5; markprice = await SPXMarkTable.GetItemAsync((markpricetimestamp).ToString()); markprice["BTCPrice"].ToString(); } catch { Console.WriteLine("bigbad"); } }

                    double availablebalance = searchdetails["AvailableBalance"].AsDouble();
                    if (orderPost.OrderQuantity > ((availablebalance * markprice["BTCPrice"].AsDouble()) * 100))
                    {
                        return(BadRequest("bad amount"));
                    }

                    // atomic id generate
                    Table    idgenerator = Table.LoadTable(amazonDynamoDBClient, "IdGenerator");
                    Document currentid   = await idgenerator.GetItemAsync("Main");

                    Document newid = new Document();
                    newid["Id"] = "Main";

                    double count = currentid["Count"].AsDouble();
                    count         += 1;
                    newid["Count"] = count.ToString();

                    UpdateItemOperationConfig updateItemOperationConfig = new UpdateItemOperationConfig();
                    ExpectedValue             expected = new ExpectedValue(ScanOperator.Equal);
                    updateItemOperationConfig.Expected = currentid;

                    try
                    {
                        Document test = await idgenerator.UpdateItemAsync(newid, updateItemOperationConfig);

                        orderId = (int)count;
                    }
                    catch
                    {
                        return(BadRequest("please try again"));
                    }

                    Table    orderreg = Table.LoadTable(amazonDynamoDBClient, "OrderRegistry");
                    Document addorder = new Document();
                    addorder["Id"]    = orderId.ToString();
                    addorder["Email"] = searchdetails["Email"].ToString();
                    addorder["Side"]  = orderPost.Side.ToString();
                    if (orderPost.OrderType == "limit")
                    {
                        addorder["Price"] = orderPost.Price.ToString();
                    }
                    addorder["OrderQuantity"] = orderPost.OrderQuantity.ToString();
                    addorder["Contract"]      = orderPost.Contract;
                    addorder["OrderType"]     = orderPost.OrderType;
                    addorder["Status"]        = "open";
                    addorder["Timestamp"]     = timestamp.ToString();
                    //addorder["Add"] = "true";
                    await orderreg.PutItemAsync(addorder);

                    // send tcp message to engine
                    try
                    {
                        TcpClient tcpclnt = new TcpClient();
                        Console.WriteLine("Connecting.....");

                        tcpclnt.Connect("52.213.34.99", port);
                        // use the ipaddress as in the server program

                        Console.WriteLine("Connected");
                        Console.Write("Enter the string to be transmitted : ");
                        var    enginepayload = new object();
                        double spymark       = markprice["SPXPrice"].AsDouble();
                        spymark  = Math.Round(spymark);
                        spymark *= 100;

                        if (orderPost.OrderType == "limit")
                        {
                            enginepayload = new
                            {
                                Method        = "Post",
                                Side          = orderPost.Side,
                                Id            = orderId.ToString(),
                                Price         = orderPost.Price,
                                OrderQuantity = orderPost.OrderQuantity.ToString(),
                                OrderType     = orderPost.OrderType,
                                Contract      = orderPost.Contract,
                                Secret        = "secret",
                                //Timestamp = timestamp.ToString(),
                                //User = searchdetails["Email"].ToString(),
                                //AvailableBalance = searchdetails["AvailableBalance"].ToString()
                            };
                        }
                        else if (orderPost.OrderType == "market")
                        {
                            enginepayload = new
                            {
                                Method        = "Post",
                                Side          = orderPost.Side,
                                Id            = orderId.ToString(),
                                OrderQuantity = orderPost.OrderQuantity.ToString(),
                                Slippage      = 99999.ToString(),
                                OrderType     = orderPost.OrderType,
                                Contract      = orderPost.Contract,
                                Secret        = "secret",
                                //Timestamp = timestamp.ToString(),
                                //User = searchdetails["Email"].ToString(),
                                //AvailableBalance = searchdetails["AvailableBalance"].ToString()
                            };
                        }
                        else
                        {
                            return(BadRequest("invalid order type"));
                        }

                        using (SslStream sslStream = new SslStream(tcpclnt.GetStream(), false,
                                                                   new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                        {
                            sslStream.AuthenticateAsClient("52.213.34.99");
                            // This is where you read and send data

                            String str = "enginekey" + JsonConvert.SerializeObject(enginepayload);
                            //Stream stm = tcpclnt.GetStream();

                            ASCIIEncoding asen = new ASCIIEncoding();
                            byte[]        ba   = asen.GetBytes(str);
                            Console.WriteLine("Transmitting.....");

                            sslStream.Write(ba, 0, ba.Length);
                            //sslStream.Close();

                            /*byte[] bb = new byte[1000];
                             * int k = await sslStream.ReadAsync(bb, 0, 1000);
                             *
                             * var socketresult = Encoding.UTF8.GetString(bb).TrimEnd('\0');
                             * Console.WriteLine(socketresult);
                             * socket = socketresult;*/
                        }
                        tcpclnt.Close();
                    }

                    catch (Exception e)
                    {
                        Console.WriteLine("Error..... " + e.StackTrace);
                        return(BadRequest("error with engine"));
                    }
                }
                catch
                {
                    return(BadRequest("failed processing"));
                }

                var    returnobj  = new { Id = orderId, Timestamp = markpricetimestamp.ToString(), Message = "transmitted", Result = "sucess" };
                string returnjson = JsonConvert.SerializeObject(returnobj);
                return(Content(returnjson, "application/json"));
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }