I'm trying to insert a new document to a cosmos database running locally with SQLAPI in the Cosmos Emulator. Selecting documents works fine but when I try to insert with below code I get the following error:
Response status code does not indicate success: NotFound (404); Substatus: 1003; ActivityId: 10e20d81-559a-47b3-8eef-021ce4138279; Reason: (Message: {"Errors":["Owner resource does not exist"]}
Code:
async Task<Product> IProductRepository.Add(Product product)
{
var container = cosmosClient.GetContainer("Invertory", "Products");
product.Id = Guid.NewGuid().ToString();
product.Category = new Category() { Name = "test" };
var x = await container.UpsertItemAsync<Product>(product);
return product;
}
It seems that the recourse (database) I try to reach not exists, but when I do a query with the same database and container and with the following code I get the expected results.
async Task<Product> IProductRepository.Get(string Id)
{
var container = cosmosClient.GetContainer("Inventory", "Products");
var iterator = (from p in container.GetItemLinqQueryable<Product>()
where p.Id.Equals(Id)
select p).ToFeedIterator();
return iterator.HasMoreResults ? (await iterator.ReadNextAsync()).First() : null;
}
What am I missing here?
There is a typo in function "IProductRepository.Add". Invertory should be Inventory.
Related
First attempt at accessing Cosmos db.
All this is in a DAL project layer of the solution (n-tier).
EndPointURI and PrimaryKey and DBName are setup by the class constructor.
I execute the client.CreateDocumentQuery
But not seeing the expected cast to the out param of the function i.e. "user".
I see the generated query string only.
I'm basing my code on this
public void GetUserByEmail(string email, out IQueryable<Shared.User> user)
{
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
user = null;
try
{
user = this.client.CreateDocumentQuery<Shared.User>(
UriFactory.CreateDocumentCollectionUri(DBName, "Users"), queryOptions)
.Where(f => f.Email == email);
}
catch (Exception ex)
{
}
}
If trying ReadDocumentAsync, I get the following
Try this, you need to return the first item
var response = this.client.CreateDocumentQuery<eUser>( UriFactory.CreateDocumentCollectionUri("demo", "Users"), queryOptions)
.Where(f => f.Email == email).AsEnumerable().ToArray().FirstOrDefault();
i am new to integration tests. I have a controller method which adds a user to the database, as shown below:
[HttpPost]
public async Task<IActionResult> CreateUserAsync([FromBody] CreateUserRequest request)
{
try
{
var command = new CreateUserCommand
{
Login = request.Login,
Password = request.Password,
FirstName = request.FirstName,
LastName = request.LastName,
MailAddress = request.MailAddress,
TokenOwnerInformation = User
};
await CommandBus.SendAsync(command);
return Ok();
}
catch (Exception e)
{
await HandleExceptionAsync(e);
return StatusCode(StatusCodes.Status500InternalServerError,
new {e.Message});
}
}
As you have noticed my method returns no information about the user which has been added to the database - it informs about the results of handling a certain request using the status codes. I have written an integration test to check is it working properly:
[Fact]
public async Task ShouldCreateUser()
{
// Arrange
var createUserRequest = new CreateUserRequest
{
Login = "testowyLogin",
Password = "testoweHaslo",
FirstName = "Aleksander",
LastName = "Kowalski",
MailAddress = "akowalski#onet.poczta.pl"
};
var serializedCreateUserRequest = SerializeObject(createUserRequest);
// Act
var response = await HttpClient.PostAsync(ApiRoutes.CreateUserAsyncRoute,
serializedCreateUserRequest);
// Assert
response
.StatusCode
.Should()
.Be(HttpStatusCode.OK);
}
I am not sure is it enough to assert just a status code of response returned from the server. I am confused because, i don't know, shall i attach to assert section code, which would get all the users and check does it contain created user for example. I don't even have any id of such a user because my application finds a new id for the user while adding him/her to the database. I also have no idea how to test methods like that:
[HttpGet("{userId:int}")]
public async Task<IActionResult> GetUserAsync([FromRoute] int userId)
{
try
{
var query = new GetUserQuery
{
UserId = userId,
TokenOwnerInformation = User
};
var user = await QueryBus
.SendAsync<GetUserQuery, UserDto>(query);
var result = user is null
? (IActionResult) NotFound(new
{
Message = (string) _stringLocalizer[UserConstants.UserNotFoundMessageKey]
})
: Ok(user);
return result;
}
catch (Exception e)
{
await HandleExceptionAsync(e);
return StatusCode(StatusCodes.Status500InternalServerError,
new {e.Message});
}
}
I believe i should somehow create a user firstly in Arrange section, get it's id and then use it in Act section with the GetUserAsync method called with the request sent by HttpClient. Again the same problem - no information about user is returned, after creation (by the way - it is not returned, because of my CQRS design in whole application - commands return no information). Could you please explain me how to write such a tests properly? Have i missed anything? Thanks for any help.
This is how I do it:
var response = (CreatedResult) await _controller.Post(createUserRequest);
response.StatusCode.Should().Be(StatusCodes.Status201Created);
The second line above is not necessary, just there for illustration.
Also, your response it's better when you return a 201 (Created) instead of the 200(OK) on Post verbs, like:
return Created($"api/users/{user.id}", user);
To test NotFound's:
var result = (NotFoundObjectResult) await _controller.Get(id);
result.StatusCode.Should().Be(StatusCodes.Status404NotFound);
The NotFoundObjectResult assumes you are returning something. If you are just responding with a 404 and no explanation, replace NotFoundObjectResult with a NotFoundResult.
And finally InternalServerErrors:
var result = (ObjectResult) await _controller.Get(id);
result.StatusCode.Should().Be(StatusCodes.Status500InternalServerError);
You can use integrationFixture for that using this NuGet package. This is an AutoFixture alternative for integration tests.
The documented examples use Get calls but you can do other calls too. Logically, you should test for the status code (OkObjectResult means 200) value and the response (which could be an empty string, that is no problem at all).
Here is the documented example for a normal Get call.
[Fact]
public async Task GetTest()
{
// arrange
using (var fixture = new Fixture<Startup>())
{
using (var mockServer = fixture.FreezeServer("Google"))
{
SetupStableServer(mockServer, "Response");
var controller = fixture.Create<SearchEngineController>();
// act
var response = await controller.GetNumberOfCharacters("Hoi");
// assert
var request = mockServer.LogEntries.Select(a => a.RequestMessage).Single();
Assert.Contains("Hoi", request.RawQuery);
Assert.Equal(8, ((OkObjectResult)response.Result).Value);
}
}
}
private void SetupStableServer(FluentMockServer fluentMockServer, string response)
{
fluentMockServer.Given(Request.Create().UsingGet())
.RespondWith(Response.Create().WithBody(response, encoding: Encoding.UTF8)
.WithStatusCode(HttpStatusCode.OK));
}
In the example above, the controller is resolved using the DI described in your Startup class.
You can also do an actual REST call using using Refit. The application is self hosted inside your test.
using (var fixture = new RefitFixture<Startup, ISearchEngine>(RestService.For<ISearchEngine>))
{
using (var mockServer = fixture.FreezeServer("Google"))
{
SetupStableServer(mockServer, "Response");
var refitClient = fixture.GetRefitClient();
var response = await refitClient.GetNumberOfCharacters("Hoi");
await response.EnsureSuccessStatusCodeAsync();
var request = mockServer.LogEntries.Select(a => a.RequestMessage).Single();
Assert.Contains("Hoi", request.RawQuery);
}
}
I am trying to use an Azure CosmosDB (former DocumentDB) repository in an API I am creating (I'm quite new to C#). I have managed to get a result with all documents using the client.CreateDocumentQuery method without passing a SQL query to it. However, when I pass a SQL query, program execution hangs and the controller responds with 404. I've tried to add a try-catch around it but I get no exception or anything.
Using Microsoft.Azure.DocumentDB.Core Version 1.9.1.
I've tried many things, other methods and also LINQ, but got nothing to work. If you have a look at this sample method, could you give me an example on how to correctly query and get a result from the document collection? I would really appreciate it!UPDATE: I updated the SQL a bit. Have tried with hard coded parameter and have tested it in the data explorer where it works. Execution seems to freeze on *var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();*
// Document repository
public async Task<IEnumerable<JObject>> GetDocsFromCollectionAsync(string someId)
{
DocumentClient client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
IDocumentQuery<JObject> documentQuery;
var documentCollectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
var queryOptions = new FeedOptions { MaxItemCount = -1 };
if (someId.IsNullOrEmpty())
{
// This works
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri,queryOptions)
.AsDocumentQuery();
}
else
{
var query = new SqlQuerySpec(
"SELECT * FROM c WHERE c.someId = #someId",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "#someId", Value = someId } }));
// This hangs during execution / returns 404 in the API controller
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri, query, queryOptions)
.AsDocumentQuery();
}
List<JObject> documents = new List<JObject>();
while (documentQuery.HasMoreResults)
{
var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();
documents.AddRange(feedResponse);
}
return documents; // Return documents to API controller
}
I have a method like this:
[HttpPost]
[ActionName("GetUserData")]
public ActionResult GetUserData()
{
using (var ctx = new myEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
ctx.Configuration.ProxyCreationEnabled = false;
var user = ctx.Users.Include("UserRoles").FirstOrDefault(x => x.UserId == 4);
ctx.Configuration.LazyLoadingEnabled = true;
ctx.Configuration.ProxyCreationEnabled = true;
return Json(new
{
Email = user.Email,
Roles = user.UserRoles
}, JsonRequestBehavior.AllowGet);
}
}
The post is done via jQuery like this:
$.post("/Administrator/GetUserData", function (data) {
console.log(data);
});
I'm trying to write out the returned data, but the console is showing me Internal Error 500 when I write the code like above...
In other case when returned result is like this:
return Json(new
{
Email = user.Email
// returning just email for example to see in console..
},JsonRequestBehavior.AllowGet);
Returning just email as a plain simple string works okay, but when I try to return the User's roles as an array via JSON , then I get problems like above...
The collection UserRoles is of Type ICollection...
What am I doing wrong here?
P.S. Guys I dug out the exception, it's like following:
Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Collections.Generic.HashSet`1[[MyModel.Models.DatabaseConnection.UserRoles, MyEntity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
it’s clear that your model of role contains a property point to user which causes the issue.
you should select an anonymous object to return
Roles = user.Roles.Select(r=> new { name = r.Name }).ToArray();
I have this code:
public async void SaveAuditLog(AuditLog a)
{
var db = new MongoDBContext();
var o = db.GetMongoDatabase(Common.Common.MongoDbConnectionString);
var audit = o.GetCollection<AuditLog>("AuditLog");
await audit.InsertOneAsync(a);
}
public IMongoDatabase GetMongoDatabase(string connectionstring)
{
MongoClient client = new MongoClient(connectionstring);
return client.GetDatabase("test");
}
this is the connection string from web.config:
<add connectionString="mongodb://localhost:27017" name="mongodb"></add>
when I check the data through robomongo, it does not show me any data inserted.
I have tried the following code as well and no data is inserted:
public async void SaveAuditLog(AuditLog a)
{
var client = new MongoClient(Common.Common.MongoDbConnectionString);
var o = client.GetDatabase("test");
var audit = o.GetCollection<BsonDocument>("AuditLog");
var document = new BsonDocument { {"Test", "test"} };
await audit.InsertOneAsync(document);
}
I am using csharpdriver for mongo with 2.2. What am I doing wrong?
found out that the data is getting inserted in mongodb and there is a bug in robomongo version 0.8.5 itself which does not show collections/documents for mongodb version 3 and above.
ran some scripts (in robomongo) which do return the data:
db.stats()
db.CollectionName.find()
downloaded mongochef and it displayed the data straight away.