I work in durandal project.
I use breeze to retrieve and save my data.
I want to send to the server, on saving, additional parameters other than the entity, like- who is the user that save the entity.
but, function saveChanges of breeze accept only one parameter- entities array for saving.
what can I do?
You can use the SaveOptions.tag property. Something like this:
var so = new SaveOptions({ resourceName: "SaveWithComment", tag: "Whatever data you want" });
return myEntityManager.saveChanges(null, so);
The 'tag' property is made available on the server within the ContextProvider, so you can access it like this:
// within your server side ContextProvider
protected override bool BeforeSaveEntity(EntityInfo entityInfo) {
var tag = (string)SaveOptions.Tag;
...
}
Related
The application was built on a bunch of asp .net core mvc and entity framework.
I have a map with markers on it. I want to change the parameters of a certain object through textboxes. The request from the frontend is written in axios, and it works flawlessly. From the first time I get the changes in the database. (mysql, provider: pomelo.mysql).
When I try to access the get request for the first time, I get the old state of the object.
HttpGet request is described here:
public async Task<IEnumerable<Poi>> GetPois()
{
var pois = await _poiService.GetPois();
if (pois.Status == Domain.Enum.StatusCode.Ok)
{
return pois.Data;
}
else { return null; }
}
I have an interface that describes the necessary set of manipulations with the Poi object.
IPoiService is described here:
public interface IPoiService
{
Task<BaseResponse<IEnumerable<Poi>>> GetPois();
Task<BaseResponse<Poi>> GetPoi();
Task<BaseResponse<bool>> DeletePoi();
Task<BaseResponse<Poi>> CreatePoi();
Task<BaseResponse<Poi>> UpdatePoi(Poi entity);
}
The service for working with the Poi object is described here:
public async Task<BaseResponse<IEnumerable<Poi>>> GetPois()
{
try
{
return new BaseResponse<IEnumerable<Poi>>
{
Data = await _poiRepository.GetAll().ToListAsync(),
Status = Domain.Enum.StatusCode.Ok
};
}
catch(Exception ex)
{
return new BaseResponse<IEnumerable<Poi>>
{
Status = Domain.Enum.StatusCode.InternalServerError,
Description = $"[GetPois]: {ex.Message}"
};
}
}
BaseResponse and the corresponding interface represents the response from the database, so it doesn't affect the update problem in any way.
I also have a repository that directly implements instance operations at the database level.
The repository is described here:
public class PoiRepository : IBaseRepository<Poi>
{
private readonly ApplicationDbContext db;
public PoiRepository(ApplicationDbContext db)
{
this.db = db;
db.Database.OpenConnection();
}
public Task Create(Poi entity)
{
throw new NotImplementedException();
}
public Task Delete(Poi entity)
{
throw new NotImplementedException();
}
public IQueryable<Poi> GetAll()
{
return db.Pois;
}
public Poi Update(Poi entity)
{
db.Pois.Update(entity);
db.SaveChanges();
return entity;
}
}
Thus, I get the problem that in order to get the current data, I need to perform two HttpGet requests, and only after that EF Core will return its current value to me.
The reason that Update(entity) sends off warning bells is that you are passing entities between server and client and back. When a controller returns a View(entity) you are sending a reference entity to the view engine to build the view. The view's #Model allows you to apply bindings but it is not a client-side copy of the entity. However, when your form submit or Ajax call etc. calls back with the #model that is NOT an entity, let alone the entity the view engine was given. It will only be a copy of data and only as complete as the view bindings could populate.
So it's hard to deduce what exactly you are witnessing without stepping through the application, but my gut says you are most likely getting confused by what you think is passing entity references around. Think of it this way, in your POST actions you could accept a set of ints, strings, and such for each of the values of the model, or a completely different class definition (DTO/ViewModel) with the same fields as the entity. ASP.Net would attempt to fill in using the data submitted with a Form POST or Ajax call. By accepting an "Entity" you are just telling EF to populate the data into a new untracked entity class. It's not the same instance as a DbContext originally loaded, and the DbContext is a different instance (or should be) than when the entity was originally loaded, it isn't tracking the entity that was originally loaded.
The resulting object will only contain the details that the view happened to have stored in the individual bound controls, pieced back together behind the scenes.
My recommendation is simply to never pass entities to, and especially from a view. Use an explicit ViewModel to represent the state sent to and from a view, then in your Update method:
Fetch the actual entity using the ViewModel ID,
Check a concurrency token (RowVersionNumber / Timestamp) to ensure no changes were made to the DB since you originally fetched the data to populate the View. (optional, but recommended)
Validate the data in your view model
Copy the data from the view model into the Entity. (Automapper can help here)
SaveChanges()
No use of Update or Attach in the DbContext/DbSet.
I have the following database:
And I want to use the "Nome" value as an ID instead of a generated code. Instead of -MzKveR8JIXgWsrph_or I wanted it to be Teste1.
My current insert code looks like this:
MyDatabaseRecord databaserecord = new MyDatabaseRecord
{
Nome = EntryNome.Text.ToString(),
Prato1 = EntryPrt1.Text.ToString(),
Prato2 = EntryPrt2.Text.ToString(),
Sopa = EntrySopa.Text.ToString(),
Contacto = EntryContacto.Text.ToString()
};
firebaseClient.Child("Restaurantes").PostAsync(databaserecord);
What do I need to change in order to set the decided value as a Firebase ID? I've been trying to get there but couldn't yet find the right answer.
The Firebase Realtime Database API for C# follow a REST-ful pattern for its method names. This means that calling POST on a URL creates a resource under that location with an identifier determined by the system. If you want to determine your own identifier, call PUT on the entire path (including that identifier).
So:
firebaseClient.Child("Restaurantes/RestaurantOne").PutAsync(databaserecord);
• Create model, controller and the views given below.
• On the submit button click the data about employee should be stored in cookie.
• When the user clicks on “Retrieve” ActionLink, the cookie values should be read and displayed on EmpDtl.cshtml view.
The only reason for this question is that I do not know how to Retrieve and Store data in cookies can someone show me how to do it any generic code which retrieve and store data in cookies and if possible with explanation because some of the things have not cleared to me like what is expirationMinutes and how much time a session will be created.
Image of Scenario
Something like the following will store a cookie with an expiration time. Note that for writing / deleting cookies you need to use the HttpResponse object, and to read them you use the HttpRequest object. These are both accessible in your Controller class.
public void SetCookie(string key, string value, int expirationMinutes)
{
var options = new CookieOptions();
if (expirationMinutes > 0)
{
options.Expires = DateTime.Now.AddMinutes(expirationMinutes);
}
Response.Cookies.Append(key, value, options);
}
Then to read the cookie you need Request.Cookies[key] and to delete a cookie you need Response.Cookies.Delete(key).
If you are storing sensitive information then you should use options.Secure = true to force HTTPS-only transmission of cookie data.
Currently, I'm doing something like this in my application:
// Foo Controller
public ActionResult Details(int id)
{
ViewBag.id = id;
return View();
}
// Foo Details View
<script type="text/javascript">
var viewBag = {
'id': #ViewBag.id
};// *Note: MVC will cry about a syntax error here, everything's ok though
</script>
<script type="text/javascript" src="#Url.Content("~/Views/Foo/details.js")"></script>
// details.js
$(function(){
var jqXHR = $.ajax({
'url': '/api/foo/getData/' + viewBag.id,
'type': 'GET'
});
jqXHR.done(function(data){
...do stuff with data object...
});
});
// Foo Api Controller
// Instantiates the data class object to be serialized and returned
I do this because in the <javascript> element, I don't want a huge JSON string of the object just hanging out in here. Ideally, I would like to just make a single call to the Foo Controller and have it instantiate the data class object, serialize it to a JSON string, and assign it to ViewBag.dataModel or something of the sort.
And of course I can't access #ViewBag inside a .js file since it's a server side object. Does anyone know of a neater way of doing this rather than having this somewhat unnecessary back and forth?
One thought was to parse the URL for the parameters but that could potentially get ugly depending on the route structure and I would still need to wait for the initial get of the view to get the js scripts to do all that, and still end up having to make that second call anyways.
I don't know if it's possible or not but is there a way I could dynamically generate a .js file during the view creation that could serve as a js ViewBag, add it to the page before the details.js file loads, and then be able to access it that way? Or maybe modify the details.js file on the fly (which might not be ideal if minifying/bundling is desired)?
The desired outcome is, I'm using knockoutJS and the initial object I'm trying to pass over is the ViewModel I want to bind to the page that contains all of the initial data from the server that I want to use. The data object I'm getting from the server is the ViewModel which I map to an observable and bind to the DOM. The current method I'm using seems to work fine and doesn't seem to have much overhead, but if I can avoid the second call to the server on the page's initial load, that would be ideal.
Firstly, I wouldn't write dynamic information to the script tag. Instead encode your data as JSON and then write it to a hidden field.
As you are using MVC4 you will already have a reference to JSON.NET so you should be able to do this:
In the controller
public ActionResult Details(int id)
{
var myModel = GetMyModelData(id);
string modelJson = JsonConvert.SerializeObject(product);
return View(modelJson);
}
In the view
<input type="hidden" id="model" value="#Model" />
In Javascript
var modelJson = $('#model').val();
var modelObj = JSON.parse(modelJson);
I need to somehow attach my custom data to the HttpRequest being handled by my IIS custom modules - so that code that runs in earlier stages of IIS pipeline attaches an object and code that runs in later stages can retrieve the object and use it and no other functionality of IIS pipeline processing is altered by adding that object.
The data needs to persist within one HTTP request only - I don't need it to be stored between requests. I need it to be "reset" for each new request automatically - so that when a new request comes it doesn't contain objects my code attached to the previous request.
Looks like HttpContext.Items is the way to go, although MSDN description of its purpose is not very clear.
Is using HttpContext.Current.Items the way to solve my problem?
This should work - I have done this in a project before.
I have a class which has a static property like this -
public class AppManager
{
public static RequestObject RequestObject
{
get
{
if (HttpContext.Current.Items["RequestObject"] == null)
{
HttpContext.Current.Items["RequestObject"] = new RequestObject();
}
return (RequestObject)HttpContext.Current.Items["RequestObject"];
}
set { HttpContext.Current.Items["RequestObject"] = value; }
}
}
And then RequestObject contains all my custom data so then in my app I can do
AppManager.RequestObject.CustomProperty
So far I have not come across any issues in the way HttpContext.Items works.