I'm trying to insert some data inside my database but I get an error on my HttpPost
here it is :
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<BsonDocument>("Users");
collection.InsertOne<UserInformationViewModel>(info);
return View("_ModalContent");
}
So i get this error
The non-generic method
'IMongoCollection.InsertOne(BsonDocument,
InsertOneOptions, CancellationToken)' cannot be used with type
arguments MVCWithMongo C:\Quentin\Repos\Test\MVCWithMongo\MVCWithMongo\Controllers\UserController.cs 34 Active
I can't figure out why.
If someone could help, would be nice!
I made a modification, i don't have the error anymore but nothing happens.
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<UserInformationViewModel>("Users");
collection.InsertOne(info);
return View("_ModalContent");
}
Related
In my REST Service I have the following:
AssetController:
// GET: <AssetController>
[HttpGet("{companyID}/{machineName}")]
public Asset Get(int companyID, string machineName)
{
Database db = new Database(configuration.ConnectionString);
//DataSet ds = db.executeFunctionSelect("fngetallassets2()");
DataSet ds = db.executeViewSelect("tblasset where LOWER(name) = '" + machineName.ToLower() + "'");
//DataSet ds = db.executeDataSetProc("getallassets", null);
DataTable table = ds.Tables[0];
DataRow row = table.Rows[0];
Asset asset = new Asset
{
ID = int.Parse(row["ID"].ToString()),
CompanyID = int.Parse(row["Company_ID"].ToString()),
Name = row["Name"].ToString(),
IPAddress = row["IP_Address"].ToString(),
CreateDate = DateTime.Parse(row["Create_Date"].ToString()),
IsActive = bool.Parse(row["Is_Active"].ToString())
};
return asset;
}
This works fine... Its the PUT that I need help with
// PUT /<AssetController>/5
// Insert record into the database
[HttpPut("{asset}")]
public void Put([FromBody] string asset)
{
Database db = new Database(configuration.ConnectionString);
db.executeNonQuery("sp_AssetInsert", null);
}
Here I am trying to pass (somehow) the same asset class
In the calling windows forms I use this way to call the PUT Method:
public void InsertAsset(Asset asset)
{
ArrayList parameters = new ArrayList
{
asset.Name,
asset.IPAddress
};
RestClient client = new RestClient("https://localhost:5001/Asset/");
RestRequest request = new RestRequest(Method.PUT);
request.AddJsonBody(asset);
IRestResponse<List<string>> response = client.Execute<List<string>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
I get an error on Response.StatusCode = unsupportedmedia or something like this.
I need to know how to serialize or somehow pass either the class or the JSON string of it or whatever...
Can someone please help me figure out how to call the PUT methods as I have dozens of these to do.
Here is the calling and receiving code used to make this work.
calling:
RestClient client = new RestClient("https://localhost:5001/Asset/");
RestRequest request = new RestRequest(Method.PUT);
request.AddJsonBody(asset); <-- Asset is a class object
RestResponse response = (RestResponse)client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
Receiving Code:
// PUT /<AssetController>/5
// Insert record into the database
[HttpPut]
public void Put([FromBody] Asset asset)
{
Database db = new Database(configuration.ConnectionString);
db.executeNonQuery("sp_AssetInsert", null);
}
I needed to change the [FromBody] string asset to [FromBody] Asset asset
There are several ways to pass parameters:
as url route i.e. https://localhost:5001/Asset/42/MyCompanyName
as url parameter http:// localhost:5001/Asset?companyID=42&machineName=companyname
in body, typically as a json serialized object
when you specify the route in [HttpPut("{paramaters}")] you are specifying option 1. You can use FromBody and FromUrl attributes on the parameter to control this. Simple parameters like numbers and string would typically be part of the URL, while complex objects like Asset will probably be easier to pass in the body.
See also
restsharp parameter posting
asp.net parameter binding
I am trying to add entries to my database from HTML forms in my view, but I am not sure if my code is a good practice. I really struggled with the matching properties but I am not sure how did I done this.
This is my code:
Controller:
cinereservacionEntities CineBD = new cinereservacionEntities();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Peliculas_Agregar(PeliculasVM pelis)
{
using (var context = new cinereservacionEntities())
{
var s = context.peliculas.Add(new pelicula()
{
id_peli = pelis.Id_peli,
titulo = pelis.Titulo,
director = pelis.Director,
cast = pelis.Cast,
descripcion = pelis.Descripcion,
categoria = pelis.Categoria
});
CineBD.peliculas.Add(s);
CineBD.SaveChanges();
}
return View(pelis);
}
My code worked and entries worked but I am asking if my code is well-programmed or there is another solution/practice to simplify the entry.
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.
I have the following SpecFlow scenario:
[When(#"the registration is submitted")]
public void WhenTheRegistrationIsSubmitted()
{
//var controller = _kernel.Get<AccountController>();
var factory = new HockeyDbContextFactory();
var userRepository = new Repository<User>(factory);
var cryptoService = new CryptoService();
var roleRepository = new Repository<Role>(factory);
var playerService = new Mock<IPlayerService>();
var leagueService = new Mock<ILeagueService>();
var userService = new UserService(userRepository, cryptoService, roleRepository);
var controller = new AccountController(userService, playerService.Object, leagueService.Object);
controller.Register(_registerModel);
}
Which eventually calls the following method through my controller:
public void RegisterUser(User user)
{
var salt = _cryptoService.GenerateSalt();
var hasedPassword = _cryptoService.HashPassword(user.Password, salt);
user.PasswordSalt = salt;
user.Password = hasedPassword;
var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");
user.Roles.Add(defaultRole);
Insert(user);
}
All of my database calls are fine until I get to this line:
var defaultRole = _roleRepository.GetAll().Single(x => x.RoleName == "User");
When I breakpoint on that line and inspect the call to GetAll(), I have context and I can view the query. The exception occurs on the call to Single(). Now, if I stick a .Include(x => x.Users) on the call to GetAll(), I'm fine. This tells me it has something to do with lazy-loading.
The error i get is: error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
When RegisterUser is called from my web application, I'm fine. When RegisterUser is called from my specification test, it fails. Does anyone have some incite?
UPDATE:
To add a little more information, here is the controller action being called:
[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterModel model)
{
if (!_userService.EmailIsUnique(model.EmailAddress))
ModelState.AddModelError("EmailAddress", "Email Address is already in use.");
if (!_userService.UserNameIsUnique(model.UserName))
ModelState.AddModelError("UserName", "User Name is already in use");
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
var user = Mapper.Map<User>(model);
_userService.RegisterUser(user);
FormsAuthentication.SetAuthCookie(model.UserName, false);
return View("RegisterSuccess");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
stepping through the code, I never make it to FormsAuthentication.SetAuthCookie(model.UserName, false);
I figured out what the issue was. I was seeding my test database with this step:
[BeforeFeature]
public static void BeforeFeature()
{
MappingConfig.RegisterMappings();
Database.SetInitializer(new TestDatabaseInitializer());
}
The context in my TestDatabaseInitializer must have been conflicting with the context I created in my scenario. Thanks for the comment Gert, it gave me the idea to take a closer look at what was going on in the rest of my scenario.
I have the following method which is supposed to return a JSONResult so I can use it in an AJAX method with javascript and load autocomplete suggestions for a textbox. I will load this everytime a particular dropdown list changes.
[AcceptVerbs(HttpVerbs.Post), Authorize]
private JsonResult GetSchemaNodeValues(string SchemaNodeId)
{
var query = #"Select ld.""Value""
From ""LookupData"" ld, ""SchemaNode"" sn
Where sn.""LookupTypeId"" = ld.""LookupTypeId""
And sn.""SchemaNodeId"" = '{0}'";
DataSet data = new DataSet();
data = ServiceManager.GenericService.ExecuteQuery(String.Format(query, SchemaNodeId)).Data;
var res = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(res);
}
I get the following error under return JsonConvert.SerializeObject(res);
Error 106 Cannot implicitly convert type 'string' to 'System.Web.Mvc.JsonResult'
Is there any way to get past this?
Before this I tried using System.Web.mvc.Controller.Json(res); which returns a JSONResult from an object.
But I couldn't use it because my class is a PageDialog not a Controller so it doesn't have access to Controller's protected internal methods like JSon(). The error I got was that JSon() is inaccessible due to its protection level. The Controller class was locked and I can't make it public or create a workaround so I changed the approach using JsonConvert.SerializeObject(res);
Any suggestions would be extremely welcome.
private dynamic GetSchemaNodeValues(string SchemaNodeId)
{
...
return data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
}
or
private string GetSchemaNodeValues(string SchemaNodeId)
{
...
var result = data.Tables[0].AsEnumerable().Select(dr => new
{
Value = dr["Value"].ToString()
});
return JsonConvert.SerializeObject(result);
}