public HttpResponseMessage AddBlogPost(BlogPageAddRequest model)
        {
            List<int> newTags = null;
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            string userId = _userService.GetCurrentUserId();

            if (model.NewTags != null && model.NewTags.Any())
            {
                newTags = new List<int>();
                newTags = TagsService.AddMultiple(model.NewTags, true);

                if (model.Tags == null)
                {
                    model.Tags = new List<int>();
                }

                foreach (var item in newTags)
                {
                    model.Tags.Add(item);
                }
            }

            ItemResponse<Int32> response = new ItemResponse<Int32>();
            response.Item = _blogService.Add(model, userId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage GetReferralById(int referralId)
        {
            ItemResponse<Referral> response = new ItemResponse<Referral>();

            response.Item = _referralService.GetById(referralId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage ViewById(int id)
        {
            ItemResponse<Payment> response = new ItemResponse<Payment>();

            response.Item = _paymentsService.SelectById(id);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage GetNameById(int TagId)
        {
            ItemResponse<string> response = new ItemResponse<string>();

            response.Item = _tagsService.GetNameById(TagId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage GetById(int siteLinkId)
        {
            ItemResponse<SiteLink> response = new ItemResponse<SiteLink>();

            response.Item = _siteLinksService.GetById(siteLinkId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Get(int id)
        {
            ItemResponse<Comment> response = new ItemResponse<Comment>();

            response.Item = _commentsService.Get(id);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage DeleteEvent(int eventEntryId)
        {
            ItemResponse<int> response = new ItemResponse<int>();

            _analyticsService.Delete(eventEntryId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage GetEvent(int eventId)
        {
            ItemResponse<Event> response = new ItemResponse<Event>();

            response.Item = _eventsService.GetById(eventId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Insert(TrackCourseRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();
            response.Item = _trackCourseService.Insert(model);
            return Request.CreateResponse(response);
        }
        public HttpResponseMessage GetsUser()
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<UserInfo> response = new ItemResponse<UserInfo>();
            string UserId = UserService.GetCurrentUserId();
            response.Item = _userDataService.GetByUserId(UserId);
            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Add(AttendanceAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            ItemResponse<Attendance> response = new ItemResponse<Attendance>();
            string userId = UserService.GetCurrentUserId();
            response.Item = _attendanceService.Add(model, userId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage PaymentsInsert(PaymentsAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();
            ItemResponse<Int32> response = new ItemResponse<Int32>();
            response.Item = _paymentsService.Add(model, userId);
            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Add(CommentAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();
            string userId = UserService.GetCurrentUserId();
            response.Item = _commentsService.Insert(model, userId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Create(SectionsAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();

            string userId = UserService.GetCurrentUserId();
            response.Item = _sectionService.Create(userId, model);
            return Request.CreateResponse(response);
        }
 public HttpResponseMessage UploadDataToAws(DataInsertRequest model, int fileType)
 {
     try
     {
         ItemResponse<File> response = new ItemResponse<File>();
         response.Item = _filesService.ProcessData(model.Data, model.FileName, fileType);
         return Request.CreateResponse(response);
     }
     catch (AmazonS3Exception s3Exception)
     {
         return Request.CreateResponse(HttpStatusCode.BadRequest, s3Exception);
     }
 }
        public HttpResponseMessage AddContent(CMSContentItemAddRequest model)
        {
            // if the Model does not pass validation, there will be an Error response returned with errors
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            ItemResponse<int> response = new ItemResponse<int>();

            response.Item = _cmsService.AddContent(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Add(WikiAddRequest model)
        {
            // if the Model does not pass validation, there will be an Error response returned with errors
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();
            string userId = UserService.GetCurrentUserId();
            response.Item = WikiService.Add(model, userId);
            return Request.CreateResponse(response);
        }
        public HttpResponseMessage DeleteMedia(int imageId)
        {
            HttpResponseMessage result = null;

            List<Media> doomedItem = _MediaService.GetPictureById(imageId);
            _MediaService.DeleteById(imageId);
            _fileService.Delete(doomedItem[0].Path);

            ItemResponse<bool> deleteConfirm = new ItemResponse<bool>();
            deleteConfirm.Item = true;
            result = Request.CreateResponse(HttpStatusCode.OK, deleteConfirm.Item);
            return result;
        }
        public HttpResponseMessage ExternalPost()
        {
            HttpResponseMessage result = null;
            HttpRequest httpRequest = HttpContext.Current.Request;
            TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(ConfigService.AwsAccessKeyId
                                , ConfigService.AwsSecretAccessKey
                                , Amazon.RegionEndpoint.USWest2));

            if (httpRequest.Files.Count > 0)
            {
                foreach (string file in httpRequest.Files)
                {
                    HttpPostedFile postedFile = httpRequest.Files[file];

                    string guid = Guid.NewGuid().ToString();

                    string remoteFilePath = ConfigService.RemoteFilePath + guid + "_" + postedFile.FileName;
                    TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest
                    {
                        BucketName = ConfigService.BucketName,
                        //FilePath = filePath,
                        InputStream = postedFile.InputStream,
                        //StorageClass = S3StorageClass.ReducedRedundancy,
                        //PartSize = 6291456, // 6 MB.
                        Key = remoteFilePath,
                        //CannedACL = S3CannedACL.PublicRead
                    };
                    fileTransferUtility.Upload(fileTransferUtilityRequest);

                    string paraRemoteFilePath = "/" + remoteFilePath;

                    ItemResponse<string> response = new ItemResponse<string>();

                    string userId = UserService.GetCurrentUserId();

                    ProfileService.UpdatePhotoPath(userId, paraRemoteFilePath);

                    response.Item = remoteFilePath;

                    return Request.CreateResponse(HttpStatusCode.Created, response.Item);

                }

            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }
        public HttpResponseMessage AddBudget(BudgetBoxAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string user = _userService.GetCurrentUserId();

            ItemResponse<Int32> response = new ItemResponse<Int32>();
            response.Item = _budgetBoxService.Add(model, user);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage InsertFaq(FaqsAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            string Id = _userService.GetCurrentUserId();

            ItemResponse<int> response = new ItemResponse<int>();

            response.Item = FaqsService.insert(model, Id);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Add(TagsAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

            }

            ItemResponse<Int32> response = new ItemResponse<Int32>();

            response.Item = _tagsService.Add(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage FollowThread(FollowForumRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();

            string userId = _userService.GetCurrentUserId();
            response.Item = _followForumService.FollowThread(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage AddEvent(EventFormAddRequest model)
        {
            // if the Model does not pass validation, there will be an Error response returned with errors
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();
            ItemResponse<Int32> response = new ItemResponse<Int32>();

            response.Item = _eventsService.Add(model, userId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage Add(TrackAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            ItemResponse<int> response = new ItemResponse<int>();
            //grabbing the ID that is currently assgined to UserService (current user)
            //this is where you get the current userId

            response.Item = _trackService.Add(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage AddUserInfo(UserAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();

            ItemResponse<int> response = new ItemResponse<int>();

            response.Item = _userService.Add(model, userId);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage AddTemplate(CMSTemplateAddRequest model)
        {
            // if the Model does not pass validation, there will be an Error response returned with errors
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();
            ItemResponse<int> response = new ItemResponse<int>();
            //pass in userId to page method

            response.Item = _cmsService.AddTemplate(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage AddPerson(TestPersonAddRequest model)
        {
            // if the Model does not pass validation, there will be an Error response returned with errors
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();

            ItemResponse<Guid> response = new ItemResponse<Guid>();

            response.Item = TestService.InsertTest(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage SendMail(CommAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            string userId = _userService.GetCurrentUserId();

            ItemResponse<int> response = new ItemResponse<int>();

            response.Item = CommunicationsService.Add(model, userId);

            MailService.SendContactUs(model);

            return Request.CreateResponse(response);
        }
        public HttpResponseMessage SubscribeUser(MailChimpAddRequest model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            try
            {
                EmailParameter result = _emailCampaignService.AddSubscriber(model.Email, model.FirstName, model.LastName);

                SuccessResponse response = new SuccessResponse();
                return Request.CreateResponse(HttpStatusCode.OK, response);
            }
            catch (MailChimpAPIException ex)
            {
                var error = ex.MailChimpAPIError;

                if(error.Code == "214")
                {
                    //e-mail already subscribed
                    ErrorResponse er = new ErrorResponse("214");
                    return Request.CreateResponse(HttpStatusCode.BadRequest, er);
                }
                else if (error.Code == "100")
                {
                    //invalid e-mail
                    ErrorResponse er = new ErrorResponse("100");
                    return Request.CreateResponse(HttpStatusCode.BadRequest, er);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e);

                ErrorResponse er = new ErrorResponse("General error occurred.");
                return Request.CreateResponse(HttpStatusCode.BadRequest, er);
            }

            ItemResponse<EmailParameter> emailParam = new ItemResponse<EmailParameter>();
            return Request.CreateResponse(emailParam);
        }
Exemple #31
0
        public static async Task Testing()
        {
            var client    = new CosmosClient(EndpointUri, PrimaryKey);
            var database  = client.GetDatabase(databaseId);
            var container = database.GetContainer(containerId); //TODO: delete and recreate container to mimic "truncate"

            var t = new Team()
            {
                LongName  = "EYE EM GEE",
                ShortName = "IMG",
                Class     = "6A",
                District  = 1
            };



            ItemResponse <Team> teamResponse = await container.CreateItemAsync <Team>(t);

            Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", teamResponse.Resource.Id, teamResponse.RequestCharge);



            //ItemResponse<Team> andersenFamilyResponse = await container.ReadItemAsync<Team>(t.Id, new PartitionKey(t.Class));
            //Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id);



            var sqlQueryText = "SELECT * FROM c WHERE c.Class = '6A'";

            Console.WriteLine("Running query: {0}\n", sqlQueryText);

            QueryDefinition     queryDefinition        = new(sqlQueryText);
            FeedIterator <Team> queryResultSetIterator = container.GetItemQueryIterator <Team>(queryDefinition);

            List <Team> teams = new();

            while (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <Team> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                foreach (Team teem in currentResultSet)
                {
                    teams.Add(teem);
                    Console.WriteLine("\tRead {0}\n", teem);
                }
            }

            foreach (Team tm in teams)
            {
                Console.Write(tm.Id);
            }



            ItemResponse <Team> updateResponse = await container.ReadItemAsync <Team>("EYE EM GEE", new PartitionKey("6A"));

            var itemBody = updateResponse.Resource;

            itemBody.District = 2;

            // replace the item with the updated content
            updateResponse = await container.ReplaceItemAsync <Team>(itemBody, itemBody.Id, new PartitionKey(itemBody.Class));

            Console.WriteLine("Updated Team [{0},{1}].\n \tBody is now: {2}\n", itemBody.LongName, itemBody.Id, updateResponse.Resource);



            // Delete an item. Note we must provide the partition key value and id of the item to delete
            ItemResponse <Team> wakefieldFamilyResponse = await container.DeleteItemAsync <Team>(t.Id, new PartitionKey(t.Class));

            Console.WriteLine("Deleted Team [{0},{1}]\n", t.Class, t.Id);
        }
Exemple #32
0
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            var itemRequest = (ItemRequest)filterContext.ActionArguments["itemRequest"];

            if (String.IsNullOrWhiteSpace(itemRequest.ServerPath) == false)
            {
                var splitPath  = itemRequest.ServerPath.Split('/');
                var itemDetail = itemManagement.GetItemDetailsFromItemName(splitPath[1]);
                itemRequest.CategoryId = itemDetail.Id;
            }

            filterContext.ActionArguments["itemRequest"] = itemRequest;

            var userId = userManagement.GetUserId(itemRequest.UserName);

            var permissionAccess = itemManagement.GetItemTypesWithCreateAccess(userId);

            if (permissionAccess[ItemType] == false)
            {
                var apiResponse = new ItemResponse
                {
                    Status        = false,
                    StatusMessage = "Permission denied to add item - " + ItemType.ToString()
                };
                var response = new HttpResponseMessage
                {
                    Content = new StringContent(javaScriptSerializer.Serialize(apiResponse))
                };
                filterContext.Response = response;
            }
            else
            {
                if (String.IsNullOrEmpty(itemRequest.Name))
                {
                    var apiResponse = new ItemResponse
                    {
                        Status        = false,
                        StatusMessage = "Item name should not be empty"
                    };
                    var response = new HttpResponseMessage
                    {
                        Content = new StringContent(javaScriptSerializer.Serialize(apiResponse))
                    };
                    filterContext.Response = response;
                }

                if (itemManagement.IsItemNameAlreadyExists(itemRequest.Name, itemRequest.CategoryId))
                {
                    var apiResponse = new ItemResponse
                    {
                        Status        = false,
                        StatusMessage = "Item with the same name is already exist in the specified Category"
                    };
                    var response = new HttpResponseMessage
                    {
                        Content = new StringContent(javaScriptSerializer.Serialize(apiResponse))
                    };
                    filterContext.Response = response;
                }
            }

            base.OnActionExecuting(filterContext);
        }
Exemple #33
0
        public async Task <Employee> AddEmployeeAsync(Employee employee)
        {
            ItemResponse <Employee> response = await this.container.CreateItemAsync(employee, new PartitionKey(employee.id));

            return(response.Resource);
        }
Exemple #34
0
        public async Task <Employee> GetEmployeeAsync(string id)
        {
            ItemResponse <Employee> response = await this.container.ReadItemAsync <Employee>(id : id, partitionKey : new PartitionKey(id));

            return(response.Resource);
        }
Exemple #35
0
        public async Task PointOperationDiagnostic(bool disableDiagnostics)
        {
            ItemRequestOptions      requestOptions      = new ItemRequestOptions();
            PatchItemRequestOptions patchRequestOptions = new PatchItemRequestOptions();

            if (disableDiagnostics)
            {
                requestOptions.DiagnosticContextFactory      = () => EmptyCosmosDiagnosticsContext.Singleton;
                patchRequestOptions.DiagnosticContextFactory = () => EmptyCosmosDiagnosticsContext.Singleton;
            }
            else
            {
                // Add 10 seconds to ensure CPU history is recorded
                await Task.Delay(TimeSpan.FromSeconds(10));
            }

            //Checking point operation diagnostics on typed operations
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> createResponse = await this.Container.CreateItemAsync <ToDoActivity>(
                item : testItem,
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> readResponse = await this.Container.ReadItemAsync <ToDoActivity>(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readResponse.Diagnostics,
                disableDiagnostics);

            testItem.description = "NewDescription";
            ItemResponse <ToDoActivity> replaceResponse = await this.Container.ReplaceItemAsync <ToDoActivity>(
                item : testItem,
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                requestOptions : requestOptions);

            Assert.AreEqual(replaceResponse.Resource.description, "NewDescription");

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceResponse.Diagnostics,
                disableDiagnostics);

            testItem.description = "PatchedDescription";
            ContainerInternal     containerInternal = (ContainerInternal)this.Container;
            List <PatchOperation> patch             = new List <PatchOperation>()
            {
                PatchOperation.Replace("/description", testItem.description)
            };
            ItemResponse <ToDoActivity> patchResponse = await containerInternal.PatchItemAsync <ToDoActivity>(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                patchOperations : patch,
                requestOptions : patchRequestOptions);

            Assert.AreEqual(patchResponse.Resource.description, "PatchedDescription");

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                patchResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> deleteResponse = await this.Container.DeleteItemAsync <ToDoActivity>(
                partitionKey : new Cosmos.PartitionKey(testItem.pk),
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(deleteResponse);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteResponse.Diagnostics,
                disableDiagnostics);

            //Checking point operation diagnostics on stream operations
            ResponseMessage createStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.pk),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage readStreamResponse = await this.Container.ReadItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage replaceStreamResponse = await this.Container.ReplaceItemStreamAsync(
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage patchStreamResponse = await containerInternal.PatchItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                patchOperations : patch,
                requestOptions : patchRequestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                patchStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage deleteStreamResponse = await this.Container.DeleteItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.pk),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteStreamResponse.Diagnostics,
                disableDiagnostics);

            // Ensure diagnostics are set even on failed operations
            testItem.description = new string('x', Microsoft.Azure.Documents.Constants.MaxResourceSizeInBytes + 1);
            ResponseMessage createTooBigStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.pk),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            Assert.IsFalse(createTooBigStreamResponse.IsSuccessStatusCode);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createTooBigStreamResponse.Diagnostics,
                disableDiagnostics);
        }
Exemple #36
0
        public async Task TestQueryWithSpecialPartitionKeysAsync()
        {
            QueryWithSpecialPartitionKeysArgs[] queryWithSpecialPartitionKeyArgsList = new QueryWithSpecialPartitionKeysArgs[]
            {
                new QueryWithSpecialPartitionKeysArgs()
                {
                    Name  = "Guid",
                    Value = Guid.NewGuid(),
                    ValueToPartitionKey = val => val.ToString(),
                },
                //new QueryWithSpecialPartitionKeysArgs()
                //{
                //    Name = "DateTime",
                //    Value = DateTime.Now,
                //    ValueToPartitionKey = val =>
                //    {
                //        string str = JsonConvert.SerializeObject(
                //            val,
                //            new JsonSerializerSettings()
                //            {
                //                Converters = new List<JsonConverter> { new IsoDateTimeConverter() }
                //            });
                //        return str.Substring(1, str.Length - 2);
                //    },
                //},
                new QueryWithSpecialPartitionKeysArgs()
                {
                    Name  = "Enum",
                    Value = HttpStatusCode.OK,
                    ValueToPartitionKey = val => (int)val,
                },
                new QueryWithSpecialPartitionKeysArgs()
                {
                    Name  = "CustomEnum",
                    Value = HttpStatusCode.OK,
                    ValueToPartitionKey = val => val.ToString(),
                },
                new QueryWithSpecialPartitionKeysArgs()
                {
                    Name  = "ResourceId",
                    Value = "testid",
                    ValueToPartitionKey = val => val,
                },
                new QueryWithSpecialPartitionKeysArgs()
                {
                    Name  = "CustomDateTime",
                    Value = new DateTime(2016, 11, 12),
                    ValueToPartitionKey = val => EpochDateTimeConverter.DateTimeToEpoch((DateTime)val),
                },
            };

            foreach (QueryWithSpecialPartitionKeysArgs testArg in queryWithSpecialPartitionKeyArgsList)
            {
                // For this test we need to split direct and gateway runs into separate collections,
                // since the query callback inserts some documents (thus has side effects).
                await this.CreateIngestQueryDeleteAsync <QueryWithSpecialPartitionKeysArgs>(
                    ConnectionModes.Direct,
                    CollectionTypes.SinglePartition,
                    QueryTestsBase.NoDocuments,
                    ImplementationAsync,
                    testArg,
                    "/" + testArg.Name);

                await this.CreateIngestQueryDeleteAsync <QueryWithSpecialPartitionKeysArgs>(
                    ConnectionModes.Direct,
                    CollectionTypes.MultiPartition,
                    QueryTestsBase.NoDocuments,
                    ImplementationAsync,
                    testArg,
                    "/" + testArg.Name);

                await this.CreateIngestQueryDeleteAsync <QueryWithSpecialPartitionKeysArgs>(
                    ConnectionModes.Gateway,
                    CollectionTypes.SinglePartition,
                    QueryTestsBase.NoDocuments,
                    ImplementationAsync,
                    testArg,
                    "/" + testArg.Name);

                await this.CreateIngestQueryDeleteAsync <QueryWithSpecialPartitionKeysArgs>(
                    ConnectionModes.Gateway,
                    CollectionTypes.MultiPartition,
                    QueryTestsBase.NoDocuments,
                    ImplementationAsync,
                    testArg,
                    "/" + testArg.Name);
            }

            async Task ImplementationAsync(
                Container container,
                IReadOnlyList <CosmosObject> documents,
                QueryWithSpecialPartitionKeysArgs testArgs)
            {
                QueryWithSpecialPartitionKeysArgs args = testArgs;

                SpecialPropertyDocument specialPropertyDocument = new SpecialPropertyDocument
                {
                    Id = Guid.NewGuid().ToString()
                };

                specialPropertyDocument.GetType().GetProperty(args.Name).SetValue(specialPropertyDocument, args.Value);
                object getPropertyValueFunction(SpecialPropertyDocument d) => d.GetType().GetProperty(args.Name).GetValue(d);

                ItemResponse <SpecialPropertyDocument> response = await container.CreateItemAsync <SpecialPropertyDocument>(specialPropertyDocument);

                dynamic returnedDoc = response.Resource;

                Assert.AreEqual(args.Value, getPropertyValueFunction((SpecialPropertyDocument)returnedDoc));

                PartitionKey key = new PartitionKey(args.ValueToPartitionKey(args.Value));

                response = await container.ReadItemAsync <SpecialPropertyDocument>(response.Resource.Id, new Cosmos.PartitionKey(key));

                returnedDoc = response.Resource;
                Assert.AreEqual(args.Value, getPropertyValueFunction((SpecialPropertyDocument)returnedDoc));

                returnedDoc = (await this.RunSinglePartitionQuery <SpecialPropertyDocument>(
                                   container,
                                   "SELECT * FROM t")).Single();

                Assert.AreEqual(args.Value, getPropertyValueFunction(returnedDoc));

                string query;

                switch (args.Name)
                {
                case "Guid":
                    query = $"SELECT * FROM T WHERE T.Guid = '{(Guid)args.Value}'";
                    break;

                case "Enum":
                    query = $"SELECT * FROM T WHERE T.Enum = '{(HttpStatusCode)args.Value}'";
                    break;

                case "DateTime":
                    query = $"SELECT * FROM T WHERE T.DateTime = '{(DateTime)args.Value}'";
                    break;

                case "CustomEnum":
                    query = $"SELECT * FROM T WHERE T.CustomEnum = '{(HttpStatusCode)args.Value}'";
                    break;

                case "ResourceId":
                    query = $"SELECT * FROM T WHERE T.ResourceId = '{(string)args.Value}'";
                    break;

                case "CustomDateTime":
                    query = $"SELECT * FROM T WHERE T.CustomDateTime = '{(DateTime)args.Value}'";
                    break;

                default:
                    query = null;
                    break;
                }

                returnedDoc = (await container.GetItemQueryIterator <SpecialPropertyDocument>(
                                   query,
                                   requestOptions: new QueryRequestOptions()
                {
                    MaxItemCount = 1,
                    PartitionKey = new Cosmos.PartitionKey(args.ValueToPartitionKey),
                }).ReadNextAsync()).First();

                Assert.AreEqual(args.Value, getPropertyValueFunction(returnedDoc));
            }
        }
        public async Task AadMockTest(ConnectionMode connectionMode)
        {
            int    requestCount = 0;
            string databaseId   = Guid.NewGuid().ToString();
            string containerId  = Guid.NewGuid().ToString();

            using (CosmosClient cosmosClient = TestCommon.CreateCosmosClient())
            {
                Database database = await cosmosClient.CreateDatabaseAsync(databaseId);

                Container container = await database.CreateContainerAsync(
                    containerId,
                    "/id");
            }


            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            LocalEmulatorTokenCredential simpleEmulatorTokenCredential = new LocalEmulatorTokenCredential(authKey);
            CosmosClientOptions          clientOptions = new CosmosClientOptions()
            {
                ConnectionMode     = connectionMode,
                ConnectionProtocol = connectionMode == ConnectionMode.Direct ? Protocol.Tcp : Protocol.Https,
            };

            if (connectionMode == ConnectionMode.Direct)
            {
                long lsn = 2;
                clientOptions.TransportClientHandlerFactory = (transport) => new TransportClientWrapper(transport,
                                                                                                        interceptorAfterResult: (request, storeResponse) =>
                {
                    // Force a barrier request on create item.
                    // There needs to be 2 regions and the GlobalCommittedLSN must be behind the LSN.
                    if (storeResponse.StatusCode == HttpStatusCode.Created)
                    {
                        if (requestCount == 0)
                        {
                            requestCount++;
                            lsn = storeResponse.LSN;
                            storeResponse.Headers.Set(Documents.WFConstants.BackendHeaders.NumberOfReadRegions, "2");
                            storeResponse.Headers.Set(Documents.WFConstants.BackendHeaders.GlobalCommittedLSN, "0");
                        }
                    }

                    // Head request is the barrier request
                    // The GlobalCommittedLSN is set to -1 because the local emulator doesn't have geo-dr so it has to be
                    // overridden for the validation to succeed.
                    if (request.OperationType == Documents.OperationType.Head)
                    {
                        if (requestCount == 1)
                        {
                            requestCount++;
                            storeResponse.Headers.Set(Documents.WFConstants.BackendHeaders.NumberOfReadRegions, "2");
                            storeResponse.Headers.Set(Documents.WFConstants.BackendHeaders.GlobalCommittedLSN, lsn.ToString(CultureInfo.InvariantCulture));
                        }
                    }

                    return(storeResponse);
                });
            }

            using CosmosClient aadClient = new CosmosClient(
                      endpoint,
                      simpleEmulatorTokenCredential,
                      clientOptions);

            TokenCredentialCache tokenCredentialCache = ((AuthorizationTokenProviderTokenCredential)aadClient.AuthorizationTokenProvider).tokenCredentialCache;

            // The refresh interval changes slightly based on how fast machine calculate the interval based on the expire time.
            Assert.IsTrue(15 <= tokenCredentialCache.BackgroundTokenCredentialRefreshInterval.Value.TotalMinutes, "Default background refresh should be 25% of the token life which is defaulted to 1hr");
            Assert.IsTrue(tokenCredentialCache.BackgroundTokenCredentialRefreshInterval.Value.TotalMinutes > 14.7, "Default background refresh should be 25% of the token life which is defaulted to 1hr");

            Database aadDatabase = await aadClient.GetDatabase(databaseId).ReadAsync();

            Container aadContainer = await aadDatabase.GetContainer(containerId).ReadContainerAsync();

            ToDoActivity toDoActivity = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> itemResponse = await aadContainer.CreateItemAsync(
                toDoActivity,
                new PartitionKey(toDoActivity.id));

            // Gateway does the barrier requests so only direct mode needs to be validated.
            if (connectionMode == ConnectionMode.Direct)
            {
                Assert.AreEqual(2, requestCount, "The barrier request was never called.");
            }

            toDoActivity.cost = 42.42;
            await aadContainer.ReplaceItemAsync(
                toDoActivity,
                toDoActivity.id,
                new PartitionKey(toDoActivity.id));

            await aadContainer.ReadItemAsync <ToDoActivity>(
                toDoActivity.id,
                new PartitionKey(toDoActivity.id));

            await aadContainer.UpsertItemAsync(toDoActivity);

            await aadContainer.DeleteItemAsync <ToDoActivity>(
                toDoActivity.id,
                new PartitionKey(toDoActivity.id));
        }
        public async Task PointOperationDiagnostic(bool disableDiagnostics)
        {
            ItemRequestOptions requestOptions = new ItemRequestOptions();

            if (disableDiagnostics)
            {
                requestOptions.DiagnosticContextFactory = () => EmptyCosmosDiagnosticsContext.Singleton;
            }
            ;

            //Checking point operation diagnostics on typed operations
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> createResponse = await this.Container.CreateItemAsync <ToDoActivity>(
                item : testItem,
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> readResponse = await this.Container.ReadItemAsync <ToDoActivity>(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readResponse.Diagnostics,
                disableDiagnostics);

            testItem.description = "NewDescription";
            ItemResponse <ToDoActivity> replaceResponse = await this.Container.ReplaceItemAsync <ToDoActivity>(
                item : testItem,
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            Assert.AreEqual(replaceResponse.Resource.description, "NewDescription");

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> deleteResponse = await this.Container.DeleteItemAsync <ToDoActivity>(
                partitionKey : new Cosmos.PartitionKey(testItem.status),
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(deleteResponse);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteResponse.Diagnostics,
                disableDiagnostics);

            //Checking point operation diagnostics on stream operations
            ResponseMessage createStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.status),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage readStreamResponse = await this.Container.ReadItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage replaceStreamResponse = await this.Container.ReplaceItemStreamAsync(
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage deleteStreamResponse = await this.Container.DeleteItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteStreamResponse.Diagnostics,
                disableDiagnostics);

            // Ensure diagnostics are set even on failed operations
            testItem.description = new string('x', Microsoft.Azure.Documents.Constants.MaxResourceSizeInBytes + 1);
            ResponseMessage createTooBigStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.status),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            Assert.IsFalse(createTooBigStreamResponse.IsSuccessStatusCode);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createTooBigStreamResponse.Diagnostics,
                disableDiagnostics);
        }
        // Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
        // <Main>
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile("appSettings.json")
                                               .Build();

            string endpoint = configuration["EndPointUrl"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json");
            }

            string authKey = configuration["AuthorizationKey"];

            if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
            {
                throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json");
            }

            // Connecting to Emulator. Change if you want a live account
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey);

            // Declare a JSON schema to use with the schema validation handler
            var myContainerSchema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type': 'string'}
  },
  'required': ['name']
}");

            cosmosClientBuilder.AddCustomHandlers(
                new LoggingHandler(),
                new ConcurrencyHandler(),
                new ThrottlingHandler(),
                new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema))
                );

            CosmosClient client = cosmosClientBuilder.Build();

            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");

            Database database = databaseResponse.Database;

            ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");

            Container container = containerResponse.Container;

            Item item = new Item()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = "Test Item",
                Description = "Some random test item",
                Completed   = false
            };

            // Create
            await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id));

            item.Completed = true;

            // Replace
            await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id));

            // Querying
            FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions()
            {
                MaxConcurrency = 1
            });
            List <Item> results = new List <Item>();

            while (query.HasMoreResults)
            {
                FeedResponse <Item> response = await query.ReadNextAsync();

                results.AddRange(response.ToList());
            }

            // Read Item

            ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
            {
                IfMatchEtag = cosmosItemResponse.ETag
            };

            // Concurrency

            List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > >
            {
                UpdateItemForConcurrency(container, itemRequestOptions, item),
                UpdateItemForConcurrency(container, itemRequestOptions, item)
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (CosmosException ex)
            {
                // Verify that our custom handler caught the scenario
                Debug.Assert(999.Equals(ex.SubStatusCode));
            }

            // Delete
            await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            // Schema validation

            containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll2", "/id");

            container = containerResponse.Container;

            // Insert an item with invalid schema
            var writeSucceeded = true;

            try
            {
                await container.CreateItemAsync(new { id = "12345" });
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Insert an item with valid schema
            try
            {
                await container.CreateItemAsync(new { id = "12345", name = "Youri" });

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);

            // Update an item with invalid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Update an item with valid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345", name = "Vladimir" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);
        }
Exemple #40
0
        // </RunBasicOperationsOnDynamicObjects>

        /// <summary>
        /// 3. Using ETags to control execution of operations
        /// 3.1 - Use ETag to control if a ReplaceItem operation should check if ETag of request matches Item
        /// 3.2 - Use ETag to control if ReadItem should only return a result if the ETag of the request does not match the Item
        /// </summary>
        /// <returns></returns>
        // <UseETags>
        private static async Task UseETags()
        {
            //******************************************************************************************************************
            // 3.1 - Use ETag to control if a replace should succeed, or not, based on whether the ETag on the request matches
            //       the current ETag value of the persisted Item
            //
            // All items in Cosmos have an _etag field. This gets set on the server every time a item is updated.
            //
            // When doing a replace of a item you can opt-in to having the server only apply the Replace if the ETag
            // on the request matches the ETag of the item on the server.
            // If someone did an update to the same item since you read it, then the ETag on the server will not match
            // and the Replace operation can be rejected.
            //******************************************************************************************************************
            Console.WriteLine("\n3.1 - Using optimistic concurrency when doing a ReplaceItemAsync");

            //read a item
            ItemResponse <SalesOrder> itemResponse = await container.ReadItemAsync <SalesOrder>(
                partitionKey : new PartitionKey("Account1"),
                id : "SalesOrder1");

            Console.WriteLine("ETag of read item - {0}", itemResponse.ETag);

            SalesOrder item = itemResponse;

            //Update the total due
            itemResponse.Resource.TotalDue = 1000000;

            //persist the change back to the server
            ItemResponse <SalesOrder> updatedDoc = await container.ReplaceItemAsync <SalesOrder>(
                partitionKey : new PartitionKey(item.AccountNumber),
                id : item.Id,
                item : item);

            Console.WriteLine("ETag of item now that is has been updated - {0}", updatedDoc.ETag);

            //now, using the originally retrieved item do another update
            //but set the AccessCondition class with the ETag of the originally read item and also set the AccessConditionType
            //this tells the service to only do this operation if ETag on the request matches the current ETag on the item
            //in our case it won't, because we updated the item and therefore gave it a new ETag
            try
            {
                itemResponse.Resource.TotalDue = 9999999;
                updatedDoc = await container.ReplaceItemAsync <SalesOrder>(itemResponse, item.Id, new PartitionKey(item.AccountNumber), new ItemRequestOptions { IfMatchEtag = itemResponse.ETag });
            }
            catch (CosmosException cre)
            {
                //   now notice the failure when attempting the update
                //   this is because the ETag on the server no longer matches the ETag of doc (b/c it was changed in step 2)
                if (cre.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    Console.WriteLine("As expected, we have a pre-condition failure exception\n");
                }
            }

            //*******************************************************************************************************************
            // 3.2 - ETag on a ReadItemAsync request can be used to tell the server whether it should return a result, or not
            //
            // By setting the ETag on a ReadItemRequest along with an AccessCondition of IfNoneMatch instructs the server
            // to only return a result if the ETag of the request does not match that of the persisted Item
            //*******************************************************************************************************************

            Console.WriteLine("\n3.2 - Using ETag to do a conditional ReadItemAsync");

            // Get a item
            ItemResponse <SalesOrder> response = await container.ReadItemAsync <SalesOrder>(partitionKey : new PartitionKey("Account2"), id : "SalesOrder2");

            item = response;
            Console.WriteLine($"Read doc with StatusCode of {response.StatusCode}");

            // Get the item again with conditional access set, no item should be returned
            response = await container.ReadItemAsync <SalesOrder>(
                partitionKey : new PartitionKey("Account2"),
                id : "SalesOrder2",
                requestOptions : new ItemRequestOptions()
            {
                IfNoneMatchEtag = itemResponse.ETag
            });

            Console.WriteLine("Read doc with StatusCode of {0}", response.StatusCode);

            // Now change something on the item, then do another get and this time we should get the item back
            response.Resource.TotalDue = 42;

            response = await container.ReplaceItemAsync <SalesOrder>(item, item.Id, new PartitionKey(item.AccountNumber));

            response = await container.ReadItemAsync <SalesOrder>(
                partitionKey : new PartitionKey("Account2"),
                id : "SalesOrder2",
                requestOptions : new ItemRequestOptions()
            {
                IfNoneMatchEtag = itemResponse.ETag
            });


            Console.WriteLine("Read doc with StatusCode of {0}", response.StatusCode);
        }
Exemple #41
0
        public async Task TimeToLivePropertyPath()
        {
            string containerName    = Guid.NewGuid().ToString();
            string partitionKeyPath = "/user";
            int    timeToLivetimeToLiveInSeconds = 10;
            CosmosContainerProperties setting    = new CosmosContainerProperties()
            {
                Id           = containerName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        partitionKeyPath
                    }, Kind = PartitionKind.Hash
                },
                TimeToLivePropertyPath = "/creationDate",
            };

            ContainerResponse containerResponse = null;

            try
            {
                containerResponse = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

                Assert.Fail("CreateColleciton with TtlPropertyPath and with no DefaultTimeToLive should have failed.");
            }
            catch (CosmosException exeption)
            {
                // expected because DefaultTimeToLive was not specified
                Assert.AreEqual(HttpStatusCode.BadRequest, exeption.StatusCode);
            }

            // Verify the container content.
            setting.DefaultTimeToLive = timeToLivetimeToLiveInSeconds;
            containerResponse         = await this.cosmosDatabase.CreateContainerIfNotExistsAsync(setting);

            CosmosContainer cosmosContainer = containerResponse;

            Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
            Assert.AreEqual("/creationDate", containerResponse.Resource.TimeToLivePropertyPath);

            //verify removing the ttl property path
            setting.TimeToLivePropertyPath = null;
            containerResponse = await cosmosContainer.ReplaceAsync(setting);

            cosmosContainer = containerResponse;
            Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
            Assert.IsNull(containerResponse.Resource.TimeToLivePropertyPath);

            //adding back the ttl property path
            setting.TimeToLivePropertyPath = "/creationDate";
            containerResponse = await cosmosContainer.ReplaceAsync(setting);

            cosmosContainer = containerResponse;
            Assert.AreEqual(containerResponse.Resource.TimeToLivePropertyPath, "/creationDate");

            //Creating an item and reading before expiration
            var payload = new { id = "testId", user = "******", creationDate = ToEpoch(DateTime.UtcNow) };
            ItemResponse <dynamic> createItemResponse = await cosmosContainer.CreateItemAsync <dynamic>(payload);

            Assert.IsNotNull(createItemResponse.Resource);
            Assert.AreEqual(createItemResponse.StatusCode, HttpStatusCode.Created);
            ItemResponse <dynamic> readItemResponse = await cosmosContainer.ReadItemAsync <dynamic>(new Cosmos.PartitionKey(payload.user), payload.id);

            Assert.IsNotNull(readItemResponse.Resource);
            Assert.AreEqual(readItemResponse.StatusCode, HttpStatusCode.OK);

            containerResponse = await cosmosContainer.DeleteAsync();

            Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
        }
Exemple #42
0
        public async Task  TestJsonSerializerSettings(bool useGateway)
        {
            CosmosClient cosmosClient = TestCommon.CreateCosmosClient((cosmosClientBuilder) => {
                if (useGateway)
                {
                    cosmosClientBuilder.WithCustomSerializer(new CustomJsonSerializer(CustomSerializationTests.GetSerializerWithCustomConverterAndBinder())).WithConnectionModeGateway();
                }
                else
                {
                    cosmosClientBuilder.WithCustomSerializer(new CustomJsonSerializer(CustomSerializationTests.GetSerializerWithCustomConverterAndBinder())).WithConnectionModeDirect();
                }
            });
            Container container = cosmosClient.GetContainer(this.databaseName, this.partitionedCollectionName);

            Random rnd = new Random();

            byte[] bytes = new byte[100];
            rnd.NextBytes(bytes);
            TestDocument testDocument = new TestDocument(new KerberosTicketHashKey(bytes));

            //create and read
            ItemResponse <TestDocument> createResponse = await container.CreateItemAsync <TestDocument>(testDocument);

            ItemResponse <TestDocument> readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Id, new Cosmos.PartitionKey(testDocument.Name));

            this.AssertEqual(testDocument, readResponse.Resource);
            this.AssertEqual(testDocument, createResponse.Resource);

            // upsert
            ItemResponse <TestDocument> upsertResponse = await container.UpsertItemAsync <TestDocument>(testDocument);

            readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Id, new Cosmos.PartitionKey(testDocument.Name));

            this.AssertEqual(testDocument, readResponse.Resource);
            this.AssertEqual(testDocument, upsertResponse.Resource);

            // replace
            ItemResponse <TestDocument> replacedResponse = await container.ReplaceItemAsync <TestDocument>(testDocument, testDocument.Id);

            readResponse = await container.ReadItemAsync <TestDocument>(testDocument.Id, new Cosmos.PartitionKey(testDocument.Name));

            this.AssertEqual(testDocument, readResponse.Resource);
            this.AssertEqual(testDocument, replacedResponse.Resource);

            QueryDefinition             sql          = new QueryDefinition("select * from r");
            FeedIterator <TestDocument> feedIterator =
                container.GetItemQueryIterator <TestDocument>(queryDefinition: sql, requestOptions: new QueryRequestOptions()
            {
                MaxItemCount = 1
            });

            List <TestDocument> allDocuments = new List <TestDocument>();

            while (feedIterator.HasMoreResults)
            {
                allDocuments.AddRange(await feedIterator.ReadNextAsync());
            }

            this.AssertEqual(testDocument, allDocuments.First());

            //Will add LINQ test once it is available with new V3 OM
            // // LINQ Lambda
            // var query1 = client.CreateDocumentQuery<TestDocument>(partitionedCollectionUri, options)
            //            .Where(_ => _.Id.CompareTo(String.Empty) > 0)
            //            .Select(_ => _.Id);
            // string query1Str = query1.ToString();
            // var result = query1.ToList();
            // Assert.AreEqual(1, result.Count);
            // Assert.AreEqual(testDocument.Id, result[0]);

            // // LINQ Query
            // var query2 =
            //     from f in client.CreateDocumentQuery<TestDocument>(partitionedCollectionUri, options)
            //     where f.Id.CompareTo(String.Empty) > 0
            //     select f.Id;
            // string query2Str = query2.ToString();
            // var result2 = query2.ToList();
            // Assert.AreEqual(1, result2.Count);
            // Assert.AreEqual(testDocument.Id, result2[0]);
        }
        private static async Task RunDemo()
        {
            ToDoActivity activeActivity = new ToDoActivity()
            {
                Id           = Guid.NewGuid().ToString(),
                ActivityId   = Guid.NewGuid().ToString(),
                PartitionKey = "myPartitionKey",
                Status       = "Active"
            };

            ToDoActivity completedActivity = new ToDoActivity()
            {
                Id           = Guid.NewGuid().ToString(),
                ActivityId   = Guid.NewGuid().ToString(),
                PartitionKey = "myPartitionKey",
                Status       = "Completed"
            };

            // Create items that use System.Text.Json serialization attributes
            ItemResponse <ToDoActivity> createActiveActivity = await container.CreateItemAsync(activeActivity, new PartitionKey(activeActivity.PartitionKey));

            Console.WriteLine($"Created Active activity with id {createActiveActivity.Resource.Id} that cost {createActiveActivity.RequestCharge}");

            ItemResponse <ToDoActivity> createCompletedActivity = await container.CreateItemAsync(completedActivity, new PartitionKey(completedActivity.PartitionKey));

            Console.WriteLine($"Created Completed activity with id {createCompletedActivity.Resource.Id} that cost {createCompletedActivity.RequestCharge}");

            // Execute queries materializing responses using System.Text.Json
            // NOTE: GetItemLinqQueryable does not support System.Text.Json attributes. LINQ will not translate the name based on the attributes
            // which can result in no or invalid results coming back. https://github.com/Azure/azure-cosmos-dotnet-v3/issues/3250
            using FeedIterator <ToDoActivity> iterator = container.GetItemQueryIterator <ToDoActivity>("select * from c where c.status = 'Completed'");
            while (iterator.HasMoreResults)
            {
                FeedResponse <ToDoActivity> queryResponse = await iterator.ReadNextAsync();

                Console.WriteLine($"Obtained {queryResponse.Count} results on query for {queryResponse.RequestCharge}");
            }

            // Read items materializing responses using System.Text.Json
            ItemResponse <ToDoActivity> readActiveActivity = await container.ReadItemAsync <ToDoActivity>(activeActivity.Id, new PartitionKey(completedActivity.PartitionKey));

            Console.WriteLine($"Read Active activity with id {activeActivity.Id} that cost {readActiveActivity.RequestCharge}");

            // Using TransactionalBatch to atomically create multiple items as a single transaction
            string       batchPartitionKey = "myPartitionKey";
            ToDoActivity newActivity       = new ToDoActivity()
            {
                Id           = Guid.NewGuid().ToString(),
                ActivityId   = Guid.NewGuid().ToString(),
                PartitionKey = batchPartitionKey,
                Status       = "Active"
            };

            ToDoActivity anotherNewActivity = new ToDoActivity()
            {
                Id           = Guid.NewGuid().ToString(),
                ActivityId   = Guid.NewGuid().ToString(),
                PartitionKey = batchPartitionKey,
                Status       = "Active"
            };

            TransactionalBatchResponse batchResponse = await container.CreateTransactionalBatch(new PartitionKey(batchPartitionKey))
                                                       .CreateItem(newActivity)
                                                       .CreateItem(anotherNewActivity)
                                                       .ExecuteAsync();

            if (batchResponse.IsSuccessStatusCode)
            {
                Console.WriteLine($"Completed transactional batch that cost {batchResponse.RequestCharge}");
            }
        }
Exemple #44
0
        public static async void Run([BlobTrigger("uploads/{name}", Connection = "StorageAccountConnection")]Stream myBlob, string name, ILogger log)
        {
            // Process the image using Cognitive Services Computer Vision!
            string subscriptionKey = "[Cognitive Vision API Key]";
            string endpoint = "[Cognitive Vision Endpoint]";

            bool blnSuccess = false;


            // Create a client
            ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
            try
            {
                OcrResult result = await client.RecognizePrintedTextAsync(true, "[Azure Storage Account Root URL]" + name, OcrLanguages.En);

                if (result != null)
                {
                    // Get the image text
                    // THIS WILL BE REPLACED BY 3rd PARTY OCR
                    StringBuilder sb = new StringBuilder();
                    foreach (OcrRegion region in result.Regions)
                    {
                        foreach (OcrLine line in region.Lines)
                        {
                            foreach (OcrWord word in line.Words)
                            {
                                sb.Append(word.Text + " ");
                            };
                        };
                    };

                    // Mkae sure the plate was recognized.
                    if (sb.ToString() != "")
                    {

                        var arr1 = new string[] { "Illinois Ave", "Marvin Gardens", "Park Place", "Baltic Ave" };
                        Random random = new Random();

                        /// Create a new CosmosDB document 
                        LicenseRecord item = new LicenseRecord()
                        {
                            Id = Guid.NewGuid().ToString(),
                            PlateNumber = sb.ToString(), // Extracted from OCR
                            Location = arr1[random.Next(arr1.Length)], // Extracted from OCR
                            PhotoURL = "[Azure Storage Account Root URL] + name, // Uploaded Photo
                            DateCaptured = DateTime.Now, // Extracted from OCR / Upload time
                            IsProcessed = false
                        };

                        using (CosmosClient cosmosdbclient = new CosmosClient("AccountEndpoint=[Azure CosmosDB endpoint];AccountKey=[Azure CosmosDB account key]"))
                        {
                            Container container = cosmosdbclient.GetContainer("[Azure CosmosDB database name]", "[Azure CosmosDB container name]");
                            if (container != null)
                            {
                                ItemResponse<LecnseRecord> response = await container.CreateItemAsync(item, new PartitionKey(item.Id));
                                blnSuccess = true;
                            }
                        }
                    }


                    // Move the original blob
                    // If successful, move to Processed container
                    // If failure, move to Unprocessed container
                    var cred = new StorageCredentials("[Azure Stoage Account name]", "[Azure Storage account key]");
                    var account = new CloudStorageAccount(cred, true);
                    var storageclient = account.CreateCloudBlobClient();
                    var sourceContainer = storageclient.GetContainerReference("uploads");
                    var sourceBlob = sourceContainer.GetBlockBlobReference(name);
                    string strDestinationContainer = "processed";
                    if (!blnSuccess)
                    {
                        strDestinationContainer = "unprocessed";
                    }
                    var destinationContainer = storageclient.GetContainerReference(strDestinationContainer);
                    var destinationBlob = destinationContainer.GetBlockBlobReference(name);
                    await destinationBlob.StartCopyAsync(sourceBlob);
                    await sourceBlob.DeleteIfExistsAsync();
                };

            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            };
        }
Exemple #45
0
        public async Task ItemTest(bool directMode)
        {
            CosmosClient client    = directMode ? DirectCosmosClient : GatewayCosmosClient;
            Database     database  = client.GetDatabase(DatabaseId);
            Container    container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk");

            List <string> createdIds = new List <string>()
            {
                "BasicQueryItem",
                "BasicQueryItem2",
                "BasicQueryItem3"
            };

            List <dynamic> queryResults = await this.ToListAsync(
                container.GetItemQueryStreamIterator,
                container.GetItemQueryIterator <dynamic>,
                "select * from T where STARTSWITH(T.id, \"basicQueryItem\", true)",
                CosmosBasicQueryTests.RequestOptions);

            if (queryResults.Count < 3)
            {
                foreach (string id in createdIds)
                {
                    dynamic item = new
                    {
                        id = id,
                        pk = id,
                    };

                    ItemResponse <dynamic> createResponse = await container.CreateItemAsync <dynamic>(item : item);
                }

                queryResults = await this.ToListAsync(
                    container.GetItemQueryStreamIterator,
                    container.GetItemQueryIterator <dynamic>,
                    "select * from T where Contains(T.id, \"basicqueryitem\", true)",
                    CosmosBasicQueryTests.RequestOptions);
            }

            List <string> ids = queryResults.Select(x => (string)x.id).ToList();

            CollectionAssert.AreEquivalent(createdIds, ids);

            //Read All
            List <dynamic> results = await this.ToListAsync(
                container.GetItemQueryStreamIterator,
                container.GetItemQueryIterator <dynamic>,
                null,
                CosmosBasicQueryTests.RequestOptions);


            ids = results.Select(x => (string)x.id).ToList();
            CollectionAssert.IsSubsetOf(createdIds, ids);

            //Read All with partition key
            results = await this.ToListAsync(
                container.GetItemQueryStreamIterator,
                container.GetItemQueryIterator <dynamic>,
                null,
                new QueryRequestOptions()
            {
                MaxItemCount = 1,
                PartitionKey = new PartitionKey("BasicQueryItem")
            });

            Assert.AreEqual(1, results.Count);

            //Read All with partition key
            results = container.GetItemLinqQueryable <dynamic>(
                allowSynchronousQueryExecution: true,
                requestOptions: new QueryRequestOptions()
            {
                MaxItemCount = 1,
                PartitionKey = new PartitionKey("BasicQueryItem")
            }).ToList();

            Assert.AreEqual(1, results.Count);

            // LINQ to feed iterator Read All with partition key
            using (FeedIterator <dynamic> iterator = container.GetItemLinqQueryable <dynamic>(
                       allowSynchronousQueryExecution: true,
                       requestOptions: new QueryRequestOptions()
            {
                MaxItemCount = 1,
                PartitionKey = new PartitionKey("BasicQueryItem")
            }).ToFeedIterator())
            {
                List <dynamic> linqResults = new List <dynamic>();
                while (iterator.HasMoreResults)
                {
                    linqResults.AddRange(await iterator.ReadNextAsync());
                }

                Assert.AreEqual(1, linqResults.Count);
                Assert.AreEqual("BasicQueryItem", linqResults.First().pk.ToString());
            }
        }
        public async Task TestHttpRequestExceptionScenarioAsync()
        {
            // testhost.dll.config sets it to 2 seconds which causes it to always expire before retrying. Remove the override.
            System.Configuration.ConfigurationManager.AppSettings["UnavailableLocationsExpirationTimeInSeconds"] = "500";

            string     accountName               = "testAccount";
            string     primaryRegionNameForUri   = "eastus";
            string     secondaryRegionNameForUri = "westus";
            string     globalEndpoint            = $"https://{accountName}.documents.azure.com:443/";
            Uri        globalEndpointUri         = new Uri(globalEndpoint);
            string     primaryRegionEndpoint     = $"https://{accountName}-{primaryRegionNameForUri}.documents.azure.com";
            string     secondaryRegionEndpiont   = $"https://{accountName}-{secondaryRegionNameForUri}.documents.azure.com";
            string     databaseName              = "testDb";
            string     containerName             = "testContainer";
            string     containerRid              = "ccZ1ANCszwk=";
            ResourceId containerResourceId       = ResourceId.Parse(containerRid);

            List <AccountRegion> writeRegion = new List <AccountRegion>()
            {
                new AccountRegion()
                {
                    Name     = "East US",
                    Endpoint = $"{primaryRegionEndpoint}:443/"
                }
            };

            List <AccountRegion> readRegions = new List <AccountRegion>()
            {
                new AccountRegion()
                {
                    Name     = "East US",
                    Endpoint = $"{primaryRegionEndpoint}:443/"
                },
                new AccountRegion()
                {
                    Name     = "West US",
                    Endpoint = $"{secondaryRegionEndpiont}:443/"
                }
            };

            List <AccountRegion> writeRegionFailedOver = new List <AccountRegion>()
            {
                new AccountRegion()
                {
                    Name     = "West US",
                    Endpoint = $"{secondaryRegionEndpiont}:443/"
                }
            };

            List <AccountRegion> readRegionsFailedOver = new List <AccountRegion>()
            {
                new AccountRegion()
                {
                    Name     = "West US",
                    Endpoint = $"{secondaryRegionEndpiont}:443/"
                },
                new AccountRegion()
                {
                    Name     = "East US",
                    Endpoint = $"{primaryRegionEndpoint}:443/"
                },
            };

            // Create a mock http handler to inject gateway responses.
            // MockBehavior.Strict ensures that only the mocked APIs get called
            Mock <IHttpHandler> mockHttpHandler = new Mock <IHttpHandler>(MockBehavior.Strict);


            mockHttpHandler.Setup(x => x.SendAsync(
                                      It.Is <HttpRequestMessage>(m => m.RequestUri == globalEndpointUri || m.RequestUri.ToString().Contains(primaryRegionNameForUri)),
                                      It.IsAny <CancellationToken>())).Throws(new HttpRequestException("Mock HttpRequestException to simulate region being down"));

            int count = 0;

            mockHttpHandler.Setup(x => x.SendAsync(
                                      It.Is <HttpRequestMessage>(x => x.RequestUri == new Uri(secondaryRegionEndpiont)),
                                      It.IsAny <CancellationToken>()))
            .Returns <HttpRequestMessage, CancellationToken>((request, cancellationToken) =>
            {
                // Simulate the legacy gateway being down. After 40 requests simulate the write region pointing to new location.
                count++;
                if (count < 2)
                {
                    return(Task.FromResult(MockSetupsHelper.CreateStrongAccount(accountName, writeRegion, readRegions)));
                }
                else
                {
                    return(Task.FromResult(MockSetupsHelper.CreateStrongAccount(accountName, writeRegionFailedOver, readRegionsFailedOver)));
                }
            });


            MockSetupsHelper.SetupContainerProperties(
                mockHttpHandler: mockHttpHandler,
                regionEndpoint: secondaryRegionEndpiont,
                databaseName: databaseName,
                containerName: containerName,
                containerRid: containerRid);

            MockSetupsHelper.SetupPartitionKeyRanges(
                mockHttpHandler: mockHttpHandler,
                regionEndpoint: secondaryRegionEndpiont,
                containerResourceId: containerResourceId,
                partitionKeyRangeIds: out IReadOnlyList <string> secondaryRegionPartitionKeyRangeIds);

            MockSetupsHelper.SetupAddresses(
                mockHttpHandler: mockHttpHandler,
                partitionKeyRangeId: secondaryRegionPartitionKeyRangeIds.First(),
                regionEndpoint: secondaryRegionEndpiont,
                regionName: secondaryRegionNameForUri,
                containerResourceId: containerResourceId,
                primaryReplicaUri: out TransportAddressUri secondaryRegionprimaryReplicaUri);

            Mock <TransportClient> mockTransport = new Mock <TransportClient>(MockBehavior.Strict);

            MockSetupsHelper.SetupRequestTimeoutException(
                mockTransport,
                secondaryRegionprimaryReplicaUri);

            // Partition key ranges are the same in both regions so the SDK
            // does not need to go the secondary to get the partition key ranges.
            // Only the addresses need to be mocked on the secondary
            MockSetupsHelper.SetupAddresses(
                mockHttpHandler: mockHttpHandler,
                partitionKeyRangeId: secondaryRegionPartitionKeyRangeIds.First(),
                regionEndpoint: secondaryRegionEndpiont,
                regionName: secondaryRegionNameForUri,
                containerResourceId: containerResourceId,
                primaryReplicaUri: out TransportAddressUri secondaryRegionPrimaryReplicaUri);

            MockSetupsHelper.SetupCreateItemResponse(
                mockTransport,
                secondaryRegionPrimaryReplicaUri);

            CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
            {
                EnablePartitionLevelFailover = true,
                ConsistencyLevel             = Cosmos.ConsistencyLevel.Strong,
                ApplicationPreferredRegions  = new List <string>()
                {
                    Regions.EastUS,
                    Regions.WestUS
                },
                HttpClientFactory             = () => new HttpClient(new HttpHandlerHelper(mockHttpHandler.Object)),
                TransportClientHandlerFactory = (original) => mockTransport.Object,
            };

            CosmosClient customClient = new CosmosClient(
                globalEndpoint,
                Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())),
                cosmosClientOptions);

            Container container = customClient.GetContainer(databaseName, containerName);

            ToDoActivity toDoActivity = new ToDoActivity()
            {
                Id = "TestItem",
                Pk = "TestPk"
            };

            ItemResponse <ToDoActivity> response = await container.CreateItemAsync(toDoActivity, new Cosmos.PartitionKey(toDoActivity.Pk));

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            mockTransport.VerifyAll();
            mockHttpHandler.VerifyAll();

            // Clears all the setups. No network calls should be done on the next operation.
            mockHttpHandler.Reset();
            mockTransport.Reset();

            MockSetupsHelper.SetupCreateItemResponse(
                mockTransport,
                secondaryRegionPrimaryReplicaUri);

            ToDoActivity toDoActivity2 = new ToDoActivity()
            {
                Id = "TestItem2",
                Pk = "TestPk"
            };

            response = await container.CreateItemAsync(toDoActivity2, new Cosmos.PartitionKey(toDoActivity2.Pk));

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            // Reset it back to the override to avoid impacting other tests.
            System.Configuration.ConfigurationManager.AppSettings["UnavailableLocationsExpirationTimeInSeconds"] = "2";
        }
Exemple #47
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            cosmosClient = new CosmosClient(endpointUri, primaryKey, new CosmosClientOptions()
            {
                ApplicationName = "BeaconsACN"
            });

//-----------------------------CREANDO LA BASE DE DATOS---------------------------------//
            database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);

            log.LogInformation("Created Database: {0}\n", database.Id);
//-----------------------------CREANDO EL CONTENEDOR---------------------------//
            container = await database.CreateContainerIfNotExistsAsync(containerId, "/mac", 400);

            log.LogInformation("Created Container: {0}\n", container.Id);
//----------------------------INSTANCIANDO BEACONS Y CREANDO EL ITEM-----------//

            Users CreateItemTraking = new Users
            {
                id   = data?.id ?? null,
                mac  = data?.mac ?? null,
                date = data?.date ?? null,
                hour = data?.hour ?? null,
                user = data?.user ?? null
            };

            try
            {
                //  Lea el item para ver si existe.
                ItemResponse <Users> CreateItemTrackingResponse = await container.ReadItemAsync <Users>(CreateItemTraking.mac, new PartitionKey(CreateItemTraking.mac));

                log.LogInformation(">>>");
                log.LogInformation("Item in database with id: {0} already exists\n", CreateItemTrackingResponse.Resource.mac);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                // Crea un item en el contenedor
                ItemResponse <Users> CreateItemTrackingResponse = await container.UpsertItemAsync <Users>(CreateItemTraking, new PartitionKey(CreateItemTraking.mac));

                log.LogInformation(">>>");
                log.LogInformation("Created item in database with id: {0} Operation consumed {1} RUs.\n", CreateItemTrackingResponse.Resource.mac, CreateItemTrackingResponse.RequestCharge);
            }
            string response = "{\"ID\": \"" + data?.id + "\", \"MAC\": \"" + data?.mac + "\", \"DATE\": \"" + data?.date + "\", \"HOUR\": \"" + data?.hour + "\", \"USER\": \"" + data?.user + "\",\"status\":200, \"message\":\"OK\"}";

            string responseMessage;

            if (data?.mac == null)
            {
                responseMessage = "{ \"status\":400, \"message\":\"Error HTTP 400 (Bad Request)\"}";
                log.LogError(responseMessage);
            }
            else
            {
                responseMessage = response;
                log.LogInformation(response);
            }

            return(new OkObjectResult(CreateItemTraking));
        }
        public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            if (this._cosmos == null)
            {
                throw new ArgumentException("GrainState collection not initialized.");
            }

            string id = this.GetKeyString(grainReference);

            string partitionKey = await this.BuildPartitionKey(grainType, grainReference);

            if (this._logger.IsEnabled(LogLevel.Trace))
            {
                this._logger.Trace(
                    "Writing: GrainType={0} Key={1} Grainid={2} ETag={3} from Collection={4} with PartitionKey={5}",
                    grainType, id, grainReference, grainState.ETag, this._options.Collection, partitionKey);
            }

            ItemResponse <GrainStateEntity> response = null;

            try
            {
                var entity = new GrainStateEntity
                {
                    ETag         = grainState.ETag,
                    Id           = id,
                    GrainType    = grainType,
                    State        = grainState.State,
                    PartitionKey = partitionKey
                };

                if (string.IsNullOrWhiteSpace(grainState.ETag))
                {
                    response = await ExecuteWithRetries(() => this._container.CreateItemAsync(
                                                            entity,
                                                            new PartitionKey(partitionKey))).ConfigureAwait(false);

                    grainState.ETag = response.Resource.ETag;
                }
                else
                {
                    response = await ExecuteWithRetries(() =>
                                                        this._container.ReplaceItemAsync(
                                                            entity, entity.Id,
                                                            new PartitionKey(partitionKey),
                                                            new ItemRequestOptions {
                        IfMatchEtag = grainState.ETag
                    }))
                               .ConfigureAwait(false);

                    grainState.ETag = response.Resource.ETag;
                }
            }
            catch (CosmosException dce) when(dce.StatusCode == HttpStatusCode.PreconditionFailed)
            {
                throw new CosmosConditionNotSatisfiedException(grainType, grainReference, this._options.Collection, "Unknown", grainState.ETag, dce);
            }
            catch (Exception exc)
            {
                this._logger.LogError(exc, $"Failure writing state for Grain Type {grainType} with Id {id}.");
                throw;
            }
        }
        public void VerifySynchronizationContextDoesNotLock()
        {
            string databaseId = Guid.NewGuid().ToString();
            SynchronizationContext prevContext = SynchronizationContext.Current;

            try
            {
                TestSynchronizationContext syncContext = new TestSynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(syncContext);
                syncContext.Post(_ =>
                {
                    using (CosmosClient client = TestCommon.CreateCosmosClient())
                    {
                        Cosmos.Database database = client.CreateDatabaseAsync(databaseId).GetAwaiter().GetResult();
                        database = client.CreateDatabaseIfNotExistsAsync(databaseId).GetAwaiter().GetResult();

                        database.ReadStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                        database.ReadAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                        QueryDefinition databaseQuery = new QueryDefinition("select * from T where T.id = @id").WithParameter("@id", databaseId);
                        FeedIterator <DatabaseProperties> databaseIterator = client.GetDatabaseQueryIterator <DatabaseProperties>(databaseQuery);
                        while (databaseIterator.HasMoreResults)
                        {
                            databaseIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        Container container = database.CreateContainerAsync(Guid.NewGuid().ToString(), "/pk").GetAwaiter().GetResult();
                        container           = database.CreateContainerIfNotExistsAsync(container.Id, "/pk").GetAwaiter().GetResult();

                        ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();
                        ItemResponse <ToDoActivity> response = container.CreateItemAsync <ToDoActivity>(item: testItem).ConfigureAwait(false).GetAwaiter().GetResult();
                        Assert.IsNotNull(response);
                        string diagnostics = response.Diagnostics.ToString();
                        Assert.IsTrue(diagnostics.Contains("Synchronization Context"));

                        using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                        try
                        {
                            ToDoActivity tempItem = ToDoActivity.CreateRandomToDoActivity();
                            CancellationToken cancellationToken = cancellationTokenSource.Token;
                            cancellationTokenSource.Cancel();
                            container.CreateItemAsync <ToDoActivity>(item: tempItem, cancellationToken: cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
                            Assert.Fail("Should have thrown a cancellation token");
                        }
                        catch (CosmosOperationCanceledException oe)
                        {
                            string exception = oe.ToString();
                            Assert.IsTrue(exception.Contains("Synchronization Context"));
                        }

                        // Test read feed
                        container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true,
                            requestOptions: new QueryRequestOptions()
                        {
                        }).ToList();

                        FeedIterator feedIterator = container
                                                    .GetItemLinqQueryable <ToDoActivity>()
                                                    .ToStreamIterator();

                        while (feedIterator.HasMoreResults)
                        {
                            feedIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        FeedIterator <ToDoActivity> feedIteratorTyped = container.GetItemLinqQueryable <ToDoActivity>()
                                                                        .ToFeedIterator <ToDoActivity>();

                        while (feedIteratorTyped.HasMoreResults)
                        {
                            feedIteratorTyped.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        // Test query
                        container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true,
                            requestOptions: new QueryRequestOptions()
                        {
                        }).Where(item => item.id != "").ToList();

                        FeedIterator queryIterator = container.GetItemLinqQueryable <ToDoActivity>()
                                                     .Where(item => item.id != "").ToStreamIterator();

                        while (queryIterator.HasMoreResults)
                        {
                            queryIterator.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        FeedIterator <ToDoActivity> queryIteratorTyped = container.GetItemLinqQueryable <ToDoActivity>()
                                                                         .Where(item => item.id != "").ToFeedIterator <ToDoActivity>();

                        while (queryIteratorTyped.HasMoreResults)
                        {
                            queryIteratorTyped.ReadNextAsync().GetAwaiter().GetResult();
                        }

                        double costAsync = container.GetItemLinqQueryable <ToDoActivity>()
                                           .Select(x => x.cost).SumAsync().GetAwaiter().GetResult();

                        double cost = container.GetItemLinqQueryable <ToDoActivity>(
                            allowSynchronousQueryExecution: true).Select(x => x.cost).Sum();

                        ItemResponse <ToDoActivity> deleteResponse = container.DeleteItemAsync <ToDoActivity>(partitionKey: new Cosmos.PartitionKey(testItem.pk), id: testItem.id).ConfigureAwait(false).GetAwaiter().GetResult();
                        Assert.IsNotNull(deleteResponse);
                    }
                }, state: null);
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(prevContext);
                using (CosmosClient client = TestCommon.CreateCosmosClient())
                {
                    client.GetDatabase(databaseId).DeleteAsync().GetAwaiter().GetResult();
                }
            }
        }
Exemple #50
0
        private async Task AddItemsToContainerAsync()
        {
            Family andersenFamily = new Family
            {
                Id       = "Andersen.1",
                LastName = "Andersen",
                Parents  = new Parent[]
                {
                    new Parent {
                        FirstName = "Thomas"
                    },
                    new Parent {
                        FirstName = "Mary kAY"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FirstName = "Henriette Thaulow",
                        Gender    = "female",
                        Grade     = 5,
                        Pets      = new Pet[]
                        {
                            new Pet {
                                GivenName = "Fluffy"
                            }
                        }
                    }
                },
                Address = new Address {
                    State = "WA", County = "King", City = "Seattle"
                },
                IsRegistered = false
            };

            try
            {
                ItemResponse <Family> andersenFamilyResponse =
                    await container.ReadItemAsync <Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));

                Console.WriteLine($"item in database with id: {andersenFamilyResponse.Resource.Id} already exists\n");
            }
            catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                ItemResponse <Family> andersenFamilyResponse =
                    await container.CreateItemAsync <Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));

                Console.WriteLine($"Created item in database with id: {andersenFamilyResponse.Resource.Id} Operation consumed {andersenFamilyResponse.RequestCharge} RUs.\n");
            }
            Family wakefieldFamily = new Family
            {
                Id       = "Wakefield.7",
                LastName = "Wakefield",
                Parents  = new Parent[]
                {
                    new Parent {
                        FamilyName = "Wakefield", FirstName = "Robin"
                    },
                    new Parent {
                        FamilyName = "Miller", FirstName = "Ben"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FamilyName = "Meriam",
                        FirstName  = "Jesse",
                        Gender     = "female",
                        Grade      = 8,
                        Pets       = new Pet[]
                        {
                            new Pet {
                                GivenName = "Goofy"
                            },
                            new Pet {
                                GivenName = "Shadow"
                            }
                        }
                    },
                    new Child
                    {
                        FamilyName = "Miller",
                        FirstName  = "Lisa",
                        Gender     = "female",
                        Grade      = 1
                    }
                },
                Address = new Address {
                    State = "NY", County = "Manhattan", City = "NY"
                },
                IsRegistered = true
            };

            try
            {
                ItemResponse <Family> wakefieldFamilyResponse =
                    await container.ReadItemAsync <Family>(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName));

                Console.WriteLine($"item in database with id: {wakefieldFamilyResponse.Resource.Id} already exists\n");
            }
            catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                ItemResponse <Family> wakefieldFamilyResponse =
                    await container.CreateItemAsync <Family>(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName));

                Console.WriteLine($"Created item in database with id: {wakefieldFamilyResponse.Resource.Id} Operation consumed {wakefieldFamilyResponse.RequestCharge} RUs.\n");
            }
        }
Exemple #51
0
        public async Task <Employee> UpdateEmployeeAsync(Employee employee)
        {
            ItemResponse <Employee> response = await this.container.UpsertItemAsync <Employee>(item : employee, partitionKey : new PartitionKey(employee.id));

            return(response.Resource);
        }
Exemple #52
0
        private async Task VerifyItemOperations(
            Cosmos.PartitionKey partitionKey,
            string partitionKeySerialized,
            dynamic testItem,
            ItemRequestOptions requestOptions = null)
        {
            ResponseMessage response            = null;
            HttpStatusCode  httpStatusCode      = HttpStatusCode.OK;
            int             testHandlerHitCount = 0;
            TestHandler     testHandler         = new TestHandler((request, cancellationToken) =>
            {
                Assert.IsTrue(request.RequestUri.OriginalString.StartsWith(@"dbs/testdb/colls/testcontainer"));
                Assert.AreEqual(requestOptions, request.RequestOptions);
                Assert.AreEqual(ResourceType.Document, request.ResourceType);
                Assert.IsNotNull(request.Headers.PartitionKey);
                Assert.AreEqual(partitionKeySerialized, request.Headers.PartitionKey);
                testHandlerHitCount++;
                response         = new ResponseMessage(httpStatusCode, request, errorMessage: null);
                response.Content = request.Content;
                return(Task.FromResult(response));
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                (builder) => builder.AddCustomHandlers(testHandler));

            Container container = client.GetDatabase("testdb")
                                  .GetContainer("testcontainer");

            ItemResponse <dynamic> itemResponse = await container.CreateItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReadItemAsync <dynamic>(
                partitionKey : partitionKey,
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.UpsertItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReplaceItemAsync <dynamic>(
                id : testItem.id,
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.DeleteItemAsync <dynamic>(
                partitionKey : partitionKey,
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            Assert.AreEqual(5, testHandlerHitCount, "An operation did not make it to the handler");

            CosmosSerializer jsonSerializer = MockCosmosUtil.Serializer;

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.CreateItemStreamAsync(
                           partitionKey: partitionKey,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.ReadItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.UpsertItemStreamAsync(
                           partitionKey: partitionKey,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.ReplaceItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = jsonSerializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.DeleteItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            Assert.AreEqual(10, testHandlerHitCount, "A stream operation did not make it to the handler");
        }
Exemple #53
0
 public async Task DeleteEmployeeAsync(string id)
 {
     ItemResponse <Employee> response = await this.container.DeleteItemAsync <Employee>(id : id, partitionKey : new PartitionKey(id));
 }
        public async Task PointOperationThrottledDiagnostic(bool disableDiagnostics)
        {
            string errorMessage        = "Mock throttle exception" + Guid.NewGuid().ToString();
            Guid   exceptionActivityId = Guid.NewGuid();
            // Set a small retry count to reduce test time
            CosmosClient throttleClient = TestCommon.CreateCosmosClient(builder =>
                                                                        builder.WithThrottlingRetryOptions(TimeSpan.FromSeconds(5), 5)
                                                                        .WithTransportClientHandlerFactory(transportClient => new TransportClientWrapper(
                                                                                                               transportClient,
                                                                                                               (uri, resourceOperation, request) => TransportClientHelper.ReturnThrottledStoreResponseOnItemOperation(
                                                                                                                   uri,
                                                                                                                   resourceOperation,
                                                                                                                   request,
                                                                                                                   exceptionActivityId,
                                                                                                                   errorMessage)))
                                                                        );

            ItemRequestOptions requestOptions = new ItemRequestOptions();

            if (disableDiagnostics)
            {
                requestOptions.DiagnosticContextFactory = () => EmptyCosmosDiagnosticsContext.Singleton;
            }
            ;

            Container containerWithThrottleException = throttleClient.GetContainer(
                this.database.Id,
                this.Container.Id);

            //Checking point operation diagnostics on typed operations
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();

            try
            {
                ItemResponse <ToDoActivity> createResponse = await containerWithThrottleException.CreateItemAsync <ToDoActivity>(
                    item : testItem,
                    requestOptions : requestOptions);

                Assert.Fail("Should have thrown a request timeout exception");
            }
            catch (CosmosException ce) when((int)ce.StatusCode == (int)Documents.StatusCodes.TooManyRequests)
            {
                string exception = ce.ToString();

                Assert.IsNotNull(exception);
                Assert.IsTrue(exception.Contains(exceptionActivityId.ToString()));
                Assert.IsTrue(exception.Contains(errorMessage));

                string diagnosics = ce.Diagnostics.ToString();

                if (disableDiagnostics)
                {
                    Assert.IsTrue(string.IsNullOrEmpty(diagnosics));
                }
                else
                {
                    Assert.IsFalse(string.IsNullOrEmpty(diagnosics));
                    Assert.IsTrue(exception.Contains(diagnosics));
                    DiagnosticValidator.ValidatePointOperationDiagnostics(ce.DiagnosticsContext);
                }
            }
        }
Exemple #55
0
        public override async Task <ItemResponse <DataEncryptionKeyProperties> > CreateDataEncryptionKeyAsync(
            string id,
            string encryptionAlgorithm,
            EncryptionKeyWrapMetadata encryptionKeyWrapMetadata,
            ItemRequestOptions requestOptions   = null,
            CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }

            if (!CosmosEncryptionAlgorithm.VerifyIfSupportedAlgorithm(encryptionAlgorithm))
            {
                throw new ArgumentException(string.Format("Unsupported Encryption Algorithm {0}", encryptionAlgorithm), nameof(encryptionAlgorithm));
            }

            if (encryptionKeyWrapMetadata == null)
            {
                throw new ArgumentNullException(nameof(encryptionKeyWrapMetadata));
            }

            CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);

            byte[] wrappedDek = null;
            EncryptionKeyWrapMetadata updatedMetadata = null;
            InMemoryRawDek            inMemoryRawDek  = null;

            if (string.Equals(encryptionAlgorithm, CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized))
            {
                (wrappedDek, updatedMetadata, inMemoryRawDek) = await this.GenerateAndWrapRawDekForLegacyEncAlgoAsync(
                    id,
                    encryptionAlgorithm,
                    encryptionKeyWrapMetadata,
                    diagnosticsContext,
                    cancellationToken);
            }
            else if (string.Equals(encryptionAlgorithm, CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized))
            {
                (wrappedDek, updatedMetadata) = this.GenerateAndWrapPdekForMdeEncAlgo(id, encryptionKeyWrapMetadata);
            }

            DataEncryptionKeyProperties dekProperties = new DataEncryptionKeyProperties(
                id,
                encryptionAlgorithm,
                wrappedDek,
                updatedMetadata,
                DateTime.UtcNow);

            ItemResponse <DataEncryptionKeyProperties> dekResponse = await this.DekProvider.Container.CreateItemAsync(
                dekProperties,
                new PartitionKey(dekProperties.Id),
                cancellationToken : cancellationToken);

            this.DekProvider.DekCache.SetDekProperties(id, dekResponse.Resource);

            if (string.Equals(encryptionAlgorithm, CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized))
            {
                this.DekProvider.DekCache.SetRawDek(id, inMemoryRawDek);
            }

            return(dekResponse);
        }
        public async Task PointOperationForbiddenDiagnostic()
        {
            List <int> stringLength = new List <int>();

            foreach (int maxCount in new int[] { 1, 2, 4 })
            {
                int count = 0;
                List <(string, string)> activityIdAndErrorMessage = new List <(string, string)>(maxCount);
                Guid   transportExceptionActivityId = Guid.NewGuid();
                string transportErrorMessage        = $"TransportErrorMessage{Guid.NewGuid()}";
                Guid   activityIdScope = Guid.Empty;
                Action <Uri, Documents.ResourceOperation, Documents.DocumentServiceRequest> interceptor =
                    (uri, operation, request) =>
                {
                    Assert.AreNotEqual(Trace.CorrelationManager.ActivityId, Guid.Empty, "Activity scope should be set");

                    if (request.ResourceType == Documents.ResourceType.Document)
                    {
                        if (activityIdScope == Guid.Empty)
                        {
                            activityIdScope = Trace.CorrelationManager.ActivityId;
                        }
                        else
                        {
                            Assert.AreEqual(Trace.CorrelationManager.ActivityId, activityIdScope, "Activity scope should match on retries");
                        }

                        if (count >= maxCount)
                        {
                            TransportClientHelper.ThrowTransportExceptionOnItemOperation(
                                uri,
                                operation,
                                request,
                                transportExceptionActivityId,
                                transportErrorMessage);
                        }

                        count++;
                        string activityId   = Guid.NewGuid().ToString();
                        string errorMessage = $"Error{Guid.NewGuid()}";

                        activityIdAndErrorMessage.Add((activityId, errorMessage));
                        TransportClientHelper.ThrowForbiddendExceptionOnItemOperation(
                            uri,
                            request,
                            activityId,
                            errorMessage);
                    }
                };

                Container containerWithTransportException = TransportClientHelper.GetContainerWithIntercepter(
                    this.database.Id,
                    this.Container.Id,
                    interceptor);
                //Checking point operation diagnostics on typed operations
                ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();

                try
                {
                    ItemResponse <ToDoActivity> createResponse = await containerWithTransportException.CreateItemAsync <ToDoActivity>(
                        item : testItem);

                    Assert.Fail("Should have thrown a request timeout exception");
                }
                catch (CosmosException ce) when(ce.StatusCode == System.Net.HttpStatusCode.RequestTimeout)
                {
                    string exceptionToString = ce.ToString();

                    Assert.IsNotNull(exceptionToString);
                    stringLength.Add(exceptionToString.Length);

                    // Request timeout info will be in the exception message and in the diagnostic info.
                    Assert.AreEqual(2, Regex.Matches(exceptionToString, transportExceptionActivityId.ToString()).Count);
                    Assert.AreEqual(2, Regex.Matches(exceptionToString, transportErrorMessage).Count);

                    // Check to make sure the diagnostics does not include duplicate info.
                    foreach ((string activityId, string errorMessage) in activityIdAndErrorMessage)
                    {
                        Assert.AreEqual(1, Regex.Matches(exceptionToString, activityId).Count);
                        Assert.AreEqual(1, Regex.Matches(exceptionToString, errorMessage).Count);
                    }
                }
            }

            // Check if the exception message is not growing exponentially
            Assert.IsTrue(stringLength.Count > 2);
            for (int i = 0; i < stringLength.Count - 1; i++)
            {
                int currLength = stringLength[i];
                int nextLength = stringLength[i + 1];
                Assert.IsTrue(nextLength < currLength * 2,
                              $"The diagnostic string is growing faster than linear. Length: {currLength}, Next Length: {nextLength}");
            }
        }
Exemple #57
0
    public static async Task Main(string[] args)
    {
        using (CosmosClient client = new CosmosClient(_endpointUri, _primaryKey))
        {
            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("EntertainmentDatabase");

            Database targetDatabase = databaseResponse.Database;
            await Console.Out.WriteLineAsync($"Database Id:\t{targetDatabase.Id}");

            ContainerResponse response = await targetDatabase.CreateContainerIfNotExistsAsync("DefaultCollection", "/id");

            Container defaultContainer = response.Container;
            await Console.Out.WriteLineAsync($"Default Container Id:\t{defaultContainer.Id}");

            IndexingPolicy indexingPolicy = new IndexingPolicy
            {
                IndexingMode  = IndexingMode.Consistent,
                Automatic     = true,
                IncludedPaths =
                {
                    new IncludedPath
                    {
                        Path = "/*"
                    }
                }
            };

            ContainerProperties containerProperties = new ContainerProperties("CustomCollection", $"/{nameof(IInteraction.type)}")
            {
                IndexingPolicy = indexingPolicy,
            };
            var containerResponse = await targetDatabase.CreateContainerIfNotExistsAsync(containerProperties, 10000);

            var customContainer = containerResponse.Container;
            //var customContainer = targetDatabase.GetContainer("CustomCollection");
            await Console.Out.WriteLineAsync($"Custom Container Id:\t{customContainer.Id}");

            var foodInteractions = new Bogus.Faker <PurchaseFoodOrBeverage>()
                                   .RuleFor(i => i.id, (fake) => Guid.NewGuid().ToString())
                                   .RuleFor(i => i.type, (fake) => nameof(PurchaseFoodOrBeverage))
                                   .RuleFor(i => i.unitPrice, (fake) => Math.Round(fake.Random.Decimal(1.99m, 15.99m), 2))
                                   .RuleFor(i => i.quantity, (fake) => fake.Random.Number(1, 5))
                                   .RuleFor(i => i.totalPrice, (fake, user) => Math.Round(user.unitPrice * user.quantity, 2))
                                   .GenerateLazy(500);

            foreach (var interaction in foodInteractions)
            {
                ItemResponse <PurchaseFoodOrBeverage> result = await customContainer.CreateItemAsync(interaction);

                await Console.Out.WriteLineAsync($"Item Created\t{result.Resource.id}");
            }

            var tvInteractions = new Bogus.Faker <WatchLiveTelevisionChannel>()
                                 .RuleFor(i => i.id, (fake) => Guid.NewGuid().ToString())
                                 .RuleFor(i => i.type, (fake) => nameof(WatchLiveTelevisionChannel))
                                 .RuleFor(i => i.minutesViewed, (fake) => fake.Random.Number(1, 45))
                                 .RuleFor(i => i.channelName, (fake) => fake.PickRandom(new List <string> {
                "NEWS-6", "DRAMA-15", "ACTION-12", "DOCUMENTARY-4", "SPORTS-8"
            }))
                                 .GenerateLazy(500);

            foreach (var interaction in tvInteractions)
            {
                ItemResponse <WatchLiveTelevisionChannel> result = await customContainer.CreateItemAsync(interaction);

                await Console.Out.WriteLineAsync($"Item Created\t{result.Resource.id}");
            }

            var mapInteractions = new Bogus.Faker <ViewMap>()
                                  .RuleFor(i => i.id, (fake) => Guid.NewGuid().ToString())
                                  .RuleFor(i => i.type, (fake) => nameof(ViewMap))
                                  .RuleFor(i => i.minutesViewed, (fake) => fake.Random.Number(1, 45))
                                  .GenerateLazy(500);

            foreach (var interaction in mapInteractions)
            {
                ItemResponse <ViewMap> result = await customContainer.CreateItemAsync(interaction);

                await Console.Out.WriteLineAsync($"Item Created\t{result.Resource.id}");
            }

            FeedIterator <GeneralInteraction> query = customContainer.GetItemQueryIterator <GeneralInteraction>("SELECT * FROM c");
            while (query.HasMoreResults)
            {
                foreach (GeneralInteraction interaction in await query.ReadNextAsync())
                {
                    Console.Out.WriteLine($"[{interaction.type}]\t{interaction.id}");
                }
            }
        }
    }
Exemple #58
0
        private async Task AddItemsToContainerAsync()
        {
            Family vanAppeldoornFamily = new Family
            {
                Id       = "Appeldoorn.1",
                LastName = "van Appeldoorn",
                Parents  = new Parent[]
                {
                    new Parent {
                        FirstName = "Bertus"
                    },
                    new Parent {
                        FirstName = "Mien"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FirstName = "Erikson Salvador",
                        Gender    = "Male",
                        Age       = 17,
                        Pets      = new Pet[]
                        {
                            new Pet {
                                GivenName = "Nacho"
                            },
                            new Pet {
                                GivenName = "Ricito"
                            }
                        }
                    }
                },
                Address = new Address
                {
                    Street  = "Ter Maatenlaan 23",
                    Zipcode = "3931 WE",
                    City    = "Woudenberg"
                },
                IsRegistered = false
            };

            try
            {
                ItemResponse <Family> vanAppeldoornFamilyResponse =
                    await container.ReadItemAsync <Family>(vanAppeldoornFamily.Id, new PartitionKey(vanAppeldoornFamily.LastName));

                Console.WriteLine($"Item in database with id: {vanAppeldoornFamily.Id} already exists");
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                ItemResponse <Family> vanAppeldoornFamilyResponse =
                    await container.CreateItemAsync(vanAppeldoornFamily, new PartitionKey(vanAppeldoornFamily.LastName));

                Console.WriteLine($"Created item in database with id: {vanAppeldoornFamilyResponse.Resource.Id} Operation consumed {vanAppeldoornFamilyResponse.RequestCharge} RUs.");
            }

            Family wakefieldFamily = new Family
            {
                Id       = "Wakefield.7",
                LastName = "Wakefield",
                Parents  = new Parent[]
                {
                    new Parent {
                        FamilyName = "Wakefield", FirstName = "Robin"
                    },
                    new Parent {
                        FamilyName = "Miller", FirstName = "Ben"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FamilyName = "Merriam",
                        FirstName  = "Jesse",
                        Gender     = "female",
                        Age        = 8,
                        Pets       = new Pet[]
                        {
                            new Pet {
                                GivenName = "Goofy"
                            },
                            new Pet {
                                GivenName = "Shadow"
                            }
                        }
                    },
                    new Child
                    {
                        FamilyName = "Miller",
                        FirstName  = "Lisa",
                        Gender     = "female",
                        Age        = 1
                    }
                },
                Address = new Address
                {
                    Street  = "Europe boulevard 67",
                    Zipcode = "1010AB",
                    City    = "New York"
                },
                IsRegistered = true
            };

            try
            {
                ItemResponse <Family> wakefieldFamilyResponse =
                    await container.ReadItemAsync <Family>(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName));

                Console.WriteLine($"Item in database with id: {wakefieldFamilyResponse.Resource.Id} already exists");
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                ItemResponse <Family> wakefieldFamilyResponse =
                    await container.CreateItemAsync(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName));

                Console.WriteLine($"Created item in database with id: {wakefieldFamilyResponse.Resource.Id} Operation consumed {wakefieldFamilyResponse.RequestCharge} RUs.");
            }
        }
 public ContainerDocumentCacheEntry(ItemResponse <T> response)
     : this(response?.Resource, response?.ETag)
 {
 }
Exemple #60
0
        // </ScaleContainerAsync>

        // <AddItemsToContainerAsync>
        /// <summary>
        /// Add Family items to the container
        /// </summary>
        private async Task AddItemsToContainerAsync()
        {
            // Create a family object for the Andersen family
            Family andersenFamily = new Family
            {
                Id       = "Andersen.1",
                LastName = "Andersen",
                Parents  = new Parent[]
                {
                    new Parent {
                        FirstName = "Thomas"
                    },
                    new Parent {
                        FirstName = "Mary Kay"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FirstName = "Henriette Thaulow",
                        Gender    = "female",
                        Grade     = 5,
                        Pets      = new Pet[]
                        {
                            new Pet {
                                GivenName = "Fluffy"
                            }
                        }
                    }
                },
                Address = new Address {
                    State = "WA", County = "King", City = "Seattle"
                },
                IsRegistered = false
            };

            try
            {
                // Read the item to see if it exists.
                ItemResponse <Family> andersenFamilyResponse = await this.container.ReadItemAsync <Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));

                Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen"
                ItemResponse <Family> andersenFamilyResponse = await this.container.CreateItemAsync <Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));

                // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
                Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", andersenFamilyResponse.Resource.Id, andersenFamilyResponse.RequestCharge);
            }

            // Create a family object for the Wakefield family
            Family wakefieldFamily = new Family
            {
                Id       = "Wakefield.7",
                LastName = "Wakefield",
                Parents  = new Parent[]
                {
                    new Parent {
                        FamilyName = "Wakefield", FirstName = "Robin"
                    },
                    new Parent {
                        FamilyName = "Miller", FirstName = "Ben"
                    }
                },
                Children = new Child[]
                {
                    new Child
                    {
                        FamilyName = "Merriam",
                        FirstName  = "Jesse",
                        Gender     = "female",
                        Grade      = 8,
                        Pets       = new Pet[]
                        {
                            new Pet {
                                GivenName = "Goofy"
                            },
                            new Pet {
                                GivenName = "Shadow"
                            }
                        }
                    },
                    new Child
                    {
                        FamilyName = "Miller",
                        FirstName  = "Lisa",
                        Gender     = "female",
                        Grade      = 1
                    }
                },
                Address = new Address {
                    State = "NY", County = "Manhattan", City = "NY"
                },
                IsRegistered = true
            };

            try
            {
                // Read the item to see if it exists
                ItemResponse <Family> wakefieldFamilyResponse = await this.container.ReadItemAsync <Family>(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName));

                Console.WriteLine("Item in database with id: {0} already exists\n", wakefieldFamilyResponse.Resource.Id);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                // Create an item in the container representing the Wakefield family. Note we provide the value of the partition key for this item, which is "Wakefield"
                ItemResponse <Family> wakefieldFamilyResponse = await this.container.CreateItemAsync <Family>(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName));

                // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
                Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", wakefieldFamilyResponse.Resource.Id, wakefieldFamilyResponse.RequestCharge);
            }
        }