here is the code launched when updating the database from my razor page (when I move a card from the syncfusion Kanban tool) :
[Route("api/Kanbans/Update")]
[HttpPost]
public List<Kanban> UpdateCard([FromBody] CRUDModel<Kanban> value)
{
Kanban Kanbanvalue = value.Value;
IQueryable<Kanban> filterData = _context.Kanbans.Include(c => c.IdAssigneeKanbanNavigation).Where(c => c.IdKanban == Convert.ToInt32(Kanbanvalue.IdKanban));
if (filterData.Any())
{
Kanban card = _context.Kanbans.Single(A => A.IdKanban == Convert.ToUInt32(Kanbanvalue.IdKanban));
card.TitleKanban = Kanbanvalue.TitleKanban;
card.TaskKanban = Kanbanvalue.TaskKanban;
card.StatusKanban = Kanbanvalue.StatusKanban;
card.IdAssigneeKanban = Kanbanvalue.IdAssigneeKanban;
}
_context.SaveChanges();
return _context.Kanbans.ToList();
}
With that code, the database is updated well but the razor page doesn't refresh on its own. I have to press the F5 key to perform the refresh.
Here is the code launched when F5 is pressed (and works well) :
[Route("api/[controller]")]
[HttpPost]
public List<Kanban> LoadCard()
{
return _context.Kanbans
.Include(c => c.IdAssigneeKanbanNavigation)
.ToList();
}
And also, after update (before I refresh with F5) :
In my razor page, the mouse pointer takes the turning round shape (waiting) endlessly.
In the dev tool console of my browser I have this error :
Uncaught (in promise) Error: System.NullReferenceException: Object reference not set to an instance of an object.
at Syncfusion.Blazor.Kanban.Internal.CrudAction1.<CrudOperation>d__2[[ligprod.Server.Models.Kanban, ligprod.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() at Syncfusion.Blazor.Kanban.SfKanban1.d__336[[ligprod.Server.Models.Kanban, ligprod.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
endInvokeDotNetFromJS https://localhost:5001/_framework/blazor.webassembly.js:1
Rt https://localhost:5001/_framework/blazor.webassembly.js:1
St https://localhost:5001/_framework/blazor.webassembly.js:1
_mono_wasm_invoke_js_blazor https://localhost:5001/_framework/dotnet.6.0.3.lw3578l2th.js:1
_mono_background_exec https://localhost:5001/_framework/dotnet.6.0.3.lw3578l2th.js:1
pump_message https://localhost:5001/_framework/dotnet.6.0.3.lw3578l2th.js:1
Am I writting something wrong or forgetting something in my code (blazor webassembly aspnet hosted, .net 6) ?
Related
I am currently implementing Audit.NET into an ASP.NET Core Web API project that is using EF Core. I am using the Entity Framework Data Provider and currently have it configured to map all entities to a single audit log (AuditLog) table with the code below.
Audit.Core.Configuration.Setup()
.UseEntityFramework(_ => _
.AuditTypeMapper(t => typeof(AuditLog))
.AuditEntityAction<AuditLog>((ev, entry, audit) =>
{
audit.Date = DateTime.UtcNow;
audit.AuditData = JsonConvert.SerializeObject(entry);
audit.UserIdentifier = userId;
})
.IgnoreMatchedProperties(true));
This is working great, however, I would like to write audit entries to the BlogApprovals table if the entity type is Blog - in addition to the entry getting added to AuditLog. So for a Blog entity I would like an audit record in both BlogApprovals and AuditLog. Is this possible?
Not really, since the EntityFrameworkDataProvider is designed to map each entity to only one audit entity.
But you could trigger the extra insert, after the operation is complete, by using an OnSaving Custom Action, like this:
Audit.Core.Configuration.AddOnSavingAction(scope =>
{
// OnSaving event fires after context SaveChanges
var efEvent = (scope.Event as AuditEventEntityFramework)?.EntityFrameworkEvent;
if (efEvent != null && efEvent.Success)
{
foreach (var e in efEvent.Entries)
{
if (e.Table == "Blogs" && e.Action == "Insert")
{
// there was an insert on blogs table, insert the blogapproval
var ctx = efEvent.GetDbContext() as MyContext;
ctx.BlogApproval.Add(new BlogApproval() { Note = "note..." });
(ctx as IAuditBypass).SaveChangesBypassAudit();
}
}
}
});
strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.
I think I am missing something in my understanding of tracking property value changes in entity framework.
I have an application where i store service requests. Whenever a team value in changed in the service request record, I want to create a team history record in a related teamhistory entity.
I have created the app in MVC using the standard scaffolding for controllers and views.
In the (post)edit task in the controller, the standard logic generated has the following code
if (ModelState.IsValid)
{
db.Entry(serviceRequest).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(serviceRequest);
I have modified that to include the creating of the teamhistory record and an individualhistory record for individual assigned within team. The code for creating these related records work, BUT i want these records only created when the values on team or member(individual) change from what they were previously.
So far the conditions i have specified due not trigger this correctly because I havent gotten the condition right. Below is the current code:
//string teamorig = db.Entry(serviceRequest).Property(u => u.Team).OriginalValue.ToString();
//string teamcurr = db.Entry(serviceRequest).Property(u => u.Team).CurrentValue.ToString();
//if (teamorig != teamcurr)
var TeamIsModified = db.Entry(serviceRequest).Property(u => u.Team).IsModified;
if (TeamIsModified)
{
serviceRequest.TeamAssignmentHistories.Add(new TeamAssignmentHistory()
{
DateAssigned = DateTime.Now,
AssignedBy = User.Identity.Name,
ServiceRequest = serviceRequest.Id,
Team = serviceRequest.Team
});
}
//=========================================================================================
// if individual assigned has changed add individual history record========================
var IndividualIsModified = db.Entry(serviceRequest).Property(u => u.Member).IsModified;
if (IndividualIsModified)
{
serviceRequest.IndividualAssignmentHistories.Add(new IndividualAssignmentHistory()
{
DateAssigned = DateTime.Now,
AssignedBy = User.Identity.Name,
ServiceRequest = serviceRequest.Id,
AssignedTo = serviceRequest.Member.Value,
});
}
//===========================================================================================
The var teamismodified logic doesnt work. When I save the page without making any changes on it- the logic kicks off because in debugging it thinks the field has been modified.
When I comment out that code and uncomment the code above it for original and currentvalues- ie the teamorig and teamcurr logic, teamcurr and teamorig have the same values in debug, even when they have been forced into a change on the save in the MVC view page. Because they have the same values, the if condition is false so the team history record is not created.
The above code has been sandwiched in between
db.Entry(serviceRequest).State = EntityState.Modified;
and
await db.SaveChangesAsync();
statements.
What am I not understanding about entity framework tracking changes in mvc? Why does think its modified when i make not changes to team, and why are teamorig and teamcurr the same when I do make the changes?
Any advice would be welcome. Thanks
I'm have a Breeze, Typescript, MVC 5.2, Knockout, Entity Framework webapp. I try to update a value of an User entity when the user clicks on a row in a grid (kogrid). The value is (should be) saved in the entityChanged eventhandler, but in Fiddler I see that the property value has not changed and the entityAspect.entityState is set to Modified (!) The originalValuesMap has the old TenantId and is the only value in the map.
I subscribe to the entity changed event like this:
this.EntityManager.entityChanged.subscribe((data: breeze.EntityChangedEventArgs) => {
if (data.entityAction == breeze.EntityAction.PropertyChange) {
return this.EntityManager.saveChanges(<breeze.Entity[]> new Array(data.entity))
.fail((error) => alert("Failed. " + error));}
});
The data arrives correctly a the eventhandler. A savechanges call is made, but the changed value (tenantId) has not changed.
The eventhandler for the rowclick is as follows:
ViewModel).OnRowClick = (tenantId: KnockoutObservable<System.IGuid>, viewModel: Imp.Scripts._TenantListViewModel) => {
entityManager.fetchEntityByKey("User", viewModel.Settings().CurrentUser().UserId(), false)
.then(entityKeyResult => {
(<Imp.Classes.UserBreeze>entityKeyResult.entity).CurrentTenantId(tenantId());
//entityManager.saveChanges(<breeze.Entity[]> new Array(entityKeyResult.entity));
})
.fail((error)=> alert("Error setting current tenant. " + error));});
When I disable the entityChanged subscription and enable the comment out line entityManager.saveChanges.... the entity is saved correctly. If I uncomment the line, but keep the subscription, it does not work.
How can I save the changed entity automatically after it changes?
EDIT:
Workaround is to disable the entityChanged eventhandler temporarily before changing the value CurrentTenantId on the current user, save the entity manually and re-subscribe to the entityChanged event.
But this solution smells.
Few suggestions:
Consider throttling the saves if propertychanged events are fired frequently. Knockout has a rate limiting extender for this purpose.
You may also want to consider using breeze save queuing plugin so you don't need to worry about overlapping save calls as much.
To troubleshoot the save issue, try adding the following code immediately before calling saveChanges:
if (data.entityAction === breeze.EntityAction.PropertyChange) {
var pcArgs = <breeze.PropertyChangedEventArgs>data.args;
console.log('Property Changed. PropertyName: ' + pcArgs.propertyName + '; Old Value: ' + (pcArgs.oldValue ? pcArgs.oldValue.toString() : 'null') + '; New Value: ' + (pcArgs.newValue ? pcArgs.newValue.toString() : 'null') + ';');
}
I have a problem to implement a simple HTTP redirection.
I use Liferay 6.0.6, our portlets are build with JSF2.0 / PortletFaces.
I want to call a redirection when a view is loaded (and not when an action is triggered). Currently, my function is called by the PreRenderView listener.
<f:metadata>
<f:event listener="#{myControler.dispatch}" type="preRenderView" />
</f:metadata>
In this function, i can check the permissions, do other stuff, and in some cases I want to redirect the user to a new page (not another view).
I tried several methods, unsuccessfully.
Specifically, I thought that this method would work :
getFacesContext().getExternalContext().redirect(url);
getFacesContext().responseComplete()
// => Can only redirect during ACTION_PHASE
This error is logical, but is there a solution to force the redirection.
It could be realized in another function, called otherwise, I only need the Hibernate Session (set at the beginning of the Render Phase)
Have you ideas to resolve this problem?
Thanks!
ps : <redirect /> or ?faces-redirect don't work with the portlets.
You can't do this in the render phase by design. Reasons:
It's possible that portlets are rendered asynchronously, so the page might already be displayed when your portlet is being rendered
It's possible that parts of the page are already delivered to the client, so that the HTTP Headers are already sent - for this reason, by design you don't have access to them in the render phase
What would be the expected outcome if two portlets rendered on the same page would decide that they'd like to forwards to another page? Who would win?
A hacky workaround is to render some javascript redirect, but this is veeeery un-portal-like and can mess up other's expectations (plus, parts of the page might already be rendered, causing your users to fill a form only to be redirected by your javascript routine.
Please rethink the problem and come up with a different solution - it's really worth doing this in a portal environment.
I use this and it works for me:
public void preRenderView() throws IOException {
if (!checkUtente()) {
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "errore.xhtml?faces-redirect=true");
fc.renderResponse();
}
}
Use the below method it will work
public static void redirect(final String url) throws IOException {
final javax.portlet.PortletResponse portletResponse
= getPortletResponse();
if (portletResponse instanceof ActionResponse) {
final javax.portlet.ActionResponse actionResponse
= (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(url);
} else if (portletResponse instanceof ResourceResponse) {
final FacesContext ctx = FacesContext.getCurrentInstance();
if (ctx.getPartialViewContext().isPartialRequest()) {
final ResourceResponse portletResResp
= (ResourceResponse) portletResponse;
PartialResponseWriter pwriter;
final ResponseWriter writer = ctx.getResponseWriter();
if (writer instanceof PartialResponseWriter) {
pwriter = (PartialResponseWriter) writer;
} else {
pwriter = ctx.getPartialViewContext()
.getPartialResponseWriter();
}
portletResResp.setContentType(Constants.CONTENT_TYPE);
portletResResp.setCharacterEncoding(Constants.ENCODING_TYPE);
// addResponseHeader("Cache-Control", "no-cache");
pwriter.startDocument();
pwriter.redirect(url);
pwriter.endDocument();
ctx.responseComplete();
} else {
throw new UnsupportedEncodingException(
"Can only redirect during RESOURCE_PHASE "
+ "if a Partial-(JSF AJAX)-Request has "
+ "been triggered");
}
} else {
throw new UnsupportedEncodingException(
"Can not redirect during the current phase: "
+ portletResponse.getClass().getSimpleName());
}
}