Blazor problem rendering data returned from Web Api - syncfusion

I'm hoping someone can suggest how I might figure out where this underlying problem is. I think it's serialization/deserialization not the grid.
I am trying to render data returned from an ASP.NET Web Api using a Syncfusion Blazor Grid Component. The JliffDocument is from an open source library. Perhaps the fact that the object is made from composite types is a contributory factor but I can successfully serialize and deserialize the object graph within a unit test. E.g. TextElement implements an interface and Segment stores collections of that interface.
This Works (but the jlfDoc is locally created data)
<EjsGrid id="Grid" DataSource="#jlfDoc.Segments" Toolbar="#(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
<GridPageSettings PageSize="5"></GridPageSettings>
<GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
<GridColumns>
<GridColumn Field="SourceText" HeaderText="Source" IsPrimaryKey="true" TextAlign="#Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
<GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
</GridColumns>
</EjsGrid>
<hr/>
<p>#rawContent</p>
<h1>There are #segments Segments</h1>
<i>#oneTextString</i>
#functions {
public object gridData { get; set; }
public JliffDocument jlfDoc { get; set; }
public string rawContent { get; set; }
public int segments { get; set; }
public string oneTextString { get; set; }
protected override async Task OnInitAsync()
{
jlfDoc = new JliffDocument("en-US",
"it-IT",
new File("f1",
new Unit("u1",
new Segment(
new TextElement("Hello"),
new TextElement("Ciao")),
new Segment(
new TextElement("Goodnight"),
new TextElement("Buonanotte")))));
}
}
This also partially-works (The rawContent, segments and oneTextString variables DO render if the line jlfDoc = jd; is commented out and DataSource="#jlfDoc.Segments" is removed which suggests that the Api call and de-serialization of jd is successful.
<EjsGrid id="Grid" DataSource="#gridData" Toolbar="#(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
<GridPageSettings PageSize="5"></GridPageSettings>
<GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
<GridColumns>
<GridColumn Field="SourceText" HeaderText="Source" IsPrimaryKey="true" TextAlign="#Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
<GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
</GridColumns>
</EjsGrid>
<hr/>
<p>#rawContent</p>
<h1>There are #segments Segments</h1>
<i>#oneTextString</i>
#functions {
public object gridData { get; set; }
public JliffDocument jlfDoc { get; set; }
public string rawContent { get; set; }
public int segments { get; set; }
public string oneTextString { get; set; }
protected override async Task OnInitAsync()
{
string serverDoc = String.Empty;
using (HttpClient client = new HttpClient())
{
serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
}
rawContent = serverDoc;
JliffDocument jd;
JSON.MakeInto(JSON.Load(serverDoc), out jd);
segments = jd.Segments.Count;
oneTextString = jd.Segments[0].TargetText;
//jlfDoc = jd;
}
}
This two line change fails
====> DataSource reinstated |
|
<EjsGrid id="Grid" DataSource="#jlfDoc.Segments" Toolbar="#(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" AllowPaging="true">
<GridPageSettings PageSize="5"></GridPageSettings>
<GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings>
<GridColumns>
<GridColumn Field="SourceText" HeaderText="Source" IsPrimaryKey="true" TextAlign="#Syncfusion.EJ2.RazorComponents.Grids.TextAlign.Right" Width="120"></GridColumn>
<GridColumn Field="TargetText" HeaderText="Target" Width="150"></GridColumn>
</GridColumns>
</EjsGrid>
<hr/>
<p>#rawContent</p>
<h1>There are #segments Segments</h1>
<i>#oneTextString</i>
#functions {
public object gridData { get; set; }
public JliffDocument jlfDoc { get; set; }
public string rawContent { get; set; }
public int segments { get; set; }
public string oneTextString { get; set; }
protected override async Task OnInitAsync()
{
string serverDoc = String.Empty;
using (HttpClient client = new HttpClient())
{
serverDoc = await client.GetStringAsync("https://localhost:44381/api/document");
}
rawContent = serverDoc;
JliffDocument jd;
JSON.MakeInto(JSON.Load(serverDoc), out jd);
segments = jd.Segments.Count;
oneTextString = jd.Segments[0].TargetText;
jlfDoc = jd; <==== UNCOMMENTED
}
}
The error in browser tools console is:
WASM: Unhandled exception rendering component:
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Blazorgrid.Pages.Index.BuildRenderTree (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) [0x00035] in <1cc78bbb60324b879905902bf1175ac2>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__5_0 (Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder) <0x20a7d38 + 0x00020> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at (wrapper delegate-invoke) <Module>.invoke_void_RenderTreeBuilder(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder)
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x00092> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Microsoft.JSInterop.JSException: No element is currently associated with component 6
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Error: No element is currently associated with component 6
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at e.updateComponent (http://localhost:53239/_framework/blazor.webassembly.js:1:13495)
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Object.t.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:1686)
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at window.Blazor._internal.renderBatch (http://localhost:53239/_framework/blazor.webassembly.js:1:30422)
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at _mono_wasm_invoke_js_unmarshalled (http://localhost:53239/_framework/wasm/mono.js:1:170240)
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[3762]:35
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[3770]:572
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[3771]:211
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[2977]:241
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[601]:22615
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at wasm-function[601]:21413
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,T2,TRes] (System.String identifier, T0 arg0, T1 arg1, T2 arg2) <0x236bc00 + 0x00044> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Mono.WebAssembly.Interop.MonoWebAssemblyJSRuntime.InvokeUnmarshalled[T0,T1,TRes] (System.String identifier, T0 arg0, T1 arg1) <0x236bb28 + 0x00016> in <0544639430f948ad82c54a3effb7ea00>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Blazor.Rendering.WebAssemblyRenderer.UpdateDisplayAsync (Microsoft.AspNetCore.Components.Rendering.RenderBatch& batch) <0x236ba30 + 0x0001e> in <91b564433c704544acd7894656c3aff9>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x000be> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: Unhandled exception rendering component:
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: System.NullReferenceException: Object reference not set to an instance of an object.
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame..ctor (System.Int32 sequence, System.Type componentType, System.Int32 subtreeLength, Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x21001d8 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.WithComponent (Microsoft.AspNetCore.Components.Rendering.ComponentState componentState) <0x2100178 + 0x0001c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.UpdateRetainedChildComponent (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldComponentIndex, System.Int32 newComponentIndex) <0x24c9160 + 0x0004c> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) <0x24b9610 + 0x00368> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) <0x20a9950 + 0x000ae> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff (Microsoft.AspNetCore.Components.Rendering.Renderer renderer, Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, System.Int32 componentId, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] oldTree, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] newTree) <0x20a9558 + 0x0009e> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) <0x20a7190 + 0x0013a> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) <0x20a6e48 + 0x00036> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1
blazor.webassembly.js:1 WASM: at Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue () <0x20a3eb8 + 0x00056> in <13ab8f8dacb6489b93c9655168c56037>:0
d.printErr # blazor.webassembly.js:1

We suspect that you are trying to use a reference of an object that is not initialized (“jlfDoc” might be null). So we suggest you to add condition to check whether the object is null before accessing its property to resolve this issue as mentioned by #HenkHolterman in comment section.

Also if you forget to use [Parameter] attribute on a component property that you want to be accessed from outside of the component you may get the "No element is currently associated with component" error.

Related

NullReferenceException: at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdateDefaultString

My PurchaseOrder business object contained
public int? ReceivedByStaffId { get; set; }
[ForeignKey("ReceivedByStaffId")]
public virtual Staff ReceivedBy { get; set; }
And I was using the Audit module.
My Controller was throwing the following error on objectSpace.CommitChanges();
System.Exception: SaveChanges: inner:
ex:System.NullReferenceException: Object reference not set to an instance of an object.
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdateDefaultString(IEFCoreWeakReference objectForUpdate, EntityEntry entityEntry, Object key)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataItem.UpdatePersistentData(List`1 weakReferences)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataContainer.AttachAuditData(DbContext dbContext)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditDataContainer.SaveAuditData(DbContext dbContext)
at DevExpress.Persistent.BaseImpl.EFCore.AuditTrail.AuditTrailService.AuditedDbContext_SavedChanges(Object sender, SavedChangesEventArgs e)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 462
stacktrace: at System.Environment.get_StackTrace()
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 462
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at MyApp2.Module.Win.Features.PurchFeature.POStateViewController.actPurchStateMenu_Execute(Object sender, SingleChoiceActionExecuteEventArgs args) in D:\dev\MyApp2\MyApp2.Module.Win\Features\PurchFeature\POStateViewController.cs:line 207
at DevExpress.ExpressApp.Actions.ActionBase.ExecuteCore(Delegate handler, ActionBaseEventArgs eventArgs)
at DevExpress.ExpressApp.Actions.SingleChoiceAction.DoExecute(ChoiceActionItem selectedItem)
at DevExpress.ExpressApp.Templates.ActionControls.Binding.SingleChoiceActionBinding.ActionControl_Execute(Object sender, SingleChoiceActionControlExecuteEventArgs e)
at DevExpress.XtraBars.BarItem.OnClick(BarItemLink link)
at DevExpress.XtraBars.BarItemLink.OnLinkClick()
at DevExpress.XtraBars.BarButtonItemLink.OnLinkAction(BarLinkAction action, Object actionArgs)
at DevExpress.XtraBars.ViewInfo.BarSelectionInfo.UnPressLink(BarItemLink link)
at DevExpress.XtraBars.Controls.CustomLinksControl.OnMouseUp(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at DevExpress.XtraBars.Controls.CustomControl.WndProc(Message& msg)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)
at Interop.User32.DispatchMessageW(MSG& msg)
at Interop.User32.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.Interop.Mso.IMsoComponentManager.FPushMessageLoop(UIntPtr dwComponentID, msoloop uReason, Void* pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(msoloop reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(msoloop reason, ApplicationContext context)
at System.Windows.Forms.Application.Run()
at DevExpress.ExpressApp.Win.WinApplication.Start()
at MyApp2.Win.Program.Main() in D:\dev\MyApp2\MyApp2.Win\Program.cs:line 112
at MyApp2.Module.BusinessObjects.MyAppDbContext.SaveChanges() in D:\dev\MyApp2\MyApp2.Module\BusinessObjects\MyAppDbContext.cs:line 468
at DevExpress.ExpressApp.EFCore.EFCoreObjectSpace.DoCommit()
at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpace.DoCommit()
at DevExpress.ExpressApp.BaseObjectSpace.CommitChanges()
at MyApp2.Module.Win.Features.PurchFeature.POStateViewController.actPurchStateMenu_Execute(Object sender, SingleChoiceActionExecuteEventArgs args) in D:\dev\MyApp2\MyApp2.Module.Win\Features\PurchFeature\POStateViewController.cs:line 207
Since the Foreign Key is nullable the navigation property also needs to be nullable
public int? ReceivedByStaffId { get; set; }
[ForeignKey("ReceivedByStaffId")]
public virtual Staff? ReceivedBy { get; set; }

NRE on Xamarin.Forms and MvvmCross Messenger Plugin

I'm trying to use the MvvmCross Messenger plugin, but I simple get it to work.. it always return a "Null Reference Exception".
Here is the BaseViewModel I created to test it:
namespace TestProject.Core.ViewModels
{
public class BaseViewModel : MvxViewModel
{
private readonly IMvxMessenger _messenger;
public BaseViewModel(IMvxMessenger messenger)
{
messenger = _messenger;
}
public IMvxCommand TestMessageCommand
{
get { return new MvxCommand(DoTestMessage); }
}
private void DoTestMessage()
{
var message = new TestMessage(this, "Potato");
_messenger.Publish(message);
}
}
}
Here is the other ViewModel that should receive the message:
namespace TestProject.Core.ViewModels
{
public class HomeViewModel : MvxViewModel
{
private string _testMessage = string.Empty;
private readonly MvxSubscriptionToken _token;
public HomeViewModel(IMvxMessenger messenger)
{
_token = messenger.Subscribe<TestMessage>(OnTestMessage);
}
private void OnTestMessage(OnTestMessage testMessage)
{
_testMessage = testMessage.Result;
}
public ICommand ShowBasePageCommand
{
get { return new MvxCommand(() => ShowViewModel<BaseViewModel>()); }
}
}
}
And finally, here is the message:
namespace TestProject.Core.Messages
{
public class TestMessage
: MvxMessage
{
public QRCodeResultMessage(object sender, string result) : base(sender)
{
Result = result;
}
public string Result { get; private set; }
}
}
I bound a button on the HomePage to the "ShowBasePageCommand", and on the BasePage there is another button bound to the "TestMessageCommand".
Full Exception:
System.NullReferenceException: Object reference not set to an nstance of an object.
at TestProject.Core.ViewModels.BaseViewModel.DoTestMessage () [0x00014] in /Users/diegopatrocinio/Projects/Xamarin/TestProject/TestProject.Core/ViewModels/BaseViewModel.cs:49
at MvvmCross.Core.ViewModels.MvxCommand.Execute (System.Object parameter) [0x00009] in <69bce0378e8e413982d3b552d7e387a8>:0
at Xamarin.Forms.Button.Xamarin.Forms.IButtonController.SendClicked () [0x0000a] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Core\Button.cs:121
at Xamarin.Forms.Platform.Android.ButtonRenderer+ButtonClickListener.OnClick (Android.Views.View v) [0x0000f] in C:\BuildAgent3\work\ca3766cfc22354a1\Xamarin.Forms.Platform.Android\Renderers\ButtonRenderer.cs:303
at Android.Views.View+IOnClickListenerInvoker.n_OnClick_Landroid_view_View_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_v) [0x00011] in /Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/src/Mono.Android/platforms/android-25/src/generated/Android.Views.View.cs:1857
at at (wrapper dynamic-method) System.Object:1b16fb3a-f768-4a9f-8e2e-60f0085ed7fb (intptr,intptr,intptr)
Stack:
System.Diagnostics.Debugger.Mono_UnhandledException_internal() in
System.Diagnostics.Debugger.Mono_UnhandledException(System.NullReferenceException ex) in /Users/builder/data/lanes/4009/3a62f1ea/source/mono/mcs/class/corlib/System.Diagnostics/Debugger.cs:122
object.1b16fb3a-f768-4a9f-8e2e-60f0085ed7fb( arg0, arg1, arg2) in
TestProject.Core.ViewModels.BaseViewModel.DoTestMessage() in /Users/diegopatrocinio/Projects/Xamarin/TestProject/TestProject.Core/ViewModels/BaseViewModel.cs:49
Please note that your constructor has inverted the parameter and the class member:
public BaseViewModel(IMvxMessenger messenger)
{
messenger = _messenger;
}
Should be
public BaseViewModel(IMvxMessenger messenger)
{
_messenger = messenger;
}

Xamarin PCL connected to WCF Service throws System.typeload exception on save

I have the following WCF Service contract:
[ServiceContract]
public interface IGMesDataService
{
[OperationContract]
List<HejMessage> GetHejMessages();
[OperationContract]
void SaveHejMessage(HejMessage msg);
}
The type HejMessage is an Entity and I have added its attributes through the text templates and the result is as follows:
[DataContract]
public partial class HejMessage
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Text { get; set; }
[DataMember]
public double Latitude { get; set; }
[DataMember]
public double Longitude { get; set; }
}
The code in the xamarin.forms pcl is as follows:
in the app constructor:
GMesDataServiceClient client = new GMesDataServiceClient();
client.GetHejMessagesCompleted += Client_GetHejMessagesCompleted;
client.GetHejMessagesAsync();
and the event handler:
private void Client_GetHejMessagesCompleted(object sender, GetHejMessagesCompletedEventArgs e)
{
foreach(HejMessage msg in e.Result)
AllHejMessages.Add(msg);
}
On a "post message" button click:
private void PostButton_Clicked(object sender, EventArgs e)
{
HejMessage msg = new HejMessage
{
Text = "Awesome item",
Latitude = 100,
Longitude = 100
};
AllHejMessages.Add(msg);
GMesDataServiceClient client = new GMesDataServiceClient();
client.SaveHejMessageCompleted += Client_SaveHejMessageCompleted;
client.SaveHejMessageAsync(msg);
}
the completed event here just catches the exception for me.
When I run the wcf service locally everything works smashingly. When I deploy the service the GetHejMessages call still works but the SaveHejMessage returns the following System.TypeLoadException:
Message:
{"Inheritance security rules violated while overriding member:
'System.Data.Entity.Utilities.TaskExtensions+CultureAwaiter`1<T>.UnsafeOnCompleted(System.Action)'.
Security accessibility of the overriding method must match the security accessibility of the method being overriden."}
Stack Trace:
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternalAsync(SaveOptions options, Boolean executeInExistingTransaction, CancellationToken cancellationToken)\r\n
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesAsync(SaveOptions options, CancellationToken cancellationToken)\r\n
at System.Data.Entity.Internal.InternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.Internal.LazyInternalContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.DbContext.SaveChangesAsync(CancellationToken cancellationToken)\r\n
at System.Data.Entity.DbContext.SaveChangesAsync()\r\n
at GMesService.GMesDataService.SaveHejMessage(HejMessage msg) in C:\\Users\\Eric\\documents\\visual studio 2015\\Projects\\GMes\\GMesService\\GMesDataService.cs:line 22\r\n
at SyncInvokeSaveHejMessage(Object , Object[] , Object[] )\r\n
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)\r\n
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\r\n
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"
Any Ideas?

How can I use signalR with unity for client server communication

Can Any one tell me How can we use signalR with Unity For Client server communication.
Im getting error in my code.
The code is as below:
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using Microsoft.AspNet.SignalR.Client;
public class SignalR : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
public class Client
{
private readonly string _platform;
private readonly HubConnection _connection;
private readonly IHubProxy _proxy;
public event EventHandler<EventArgs> OnMessageReceived;
public Client(string platform)
{
_platform = platform;
_connection = new HubConnection("http://192.168.1.103");
_proxy = _connection.CreateHubProxy("Chat");
}
public void Connect()
{
_connection.Start();
_proxy.On("messageReceived", (string platform, string message) =>
{
if (OnMessageReceived != null)
OnMessageReceived(this, string.Format("{0}: {1}", platform, message));
});
Send("Connected");
}
public void Send(string message)
{
return _proxy.Invoke("Send", _platform, message);
}
}
This is my client side code.I have added ell’s in my assets for signalR.
The error details are as below:
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: Mono.CSharp.InternalErrorException: Assets/SignalR.cs(30,24): Client.Client(string) ---> System.TypeLoadException: Could not load type 'Microsoft.AspNet.SignalR.Client.Connection' from assembly 'Microsoft.AspNet.SignalR.Client, Version=2.1.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
at (wrapper managed-to-native) System.MonoType:GetMethodsByName (string,System.Reflection.BindingFlags,bool,System.Type)
at System.MonoType.GetMethods (BindingFlags bindingAttr) [0x00000] in :0
Thanks In Advance!!

Calling CreateProcess from PowerShell

I'm trying to call CreateProcess from PowerShell. The API call indicates that it succeeded, but no new application or process is visible in Task Manager.
Add-Type -TypeDefinition #"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public STARTF dwFlags;
public ShowWindow wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[Flags]
public enum CreationFlags : int
{
NONE = 0,
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_PROTECTED_PROCESS = 0x00040000,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
}
[Flags]
public enum STARTF : uint
{
STARTF_USESHOWWINDOW = 0x00000001,
STARTF_USESIZE = 0x00000002,
STARTF_USEPOSITION = 0x00000004,
STARTF_USECOUNTCHARS = 0x00000008,
STARTF_USEFILLATTRIBUTE = 0x00000010,
STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms
STARTF_FORCEONFEEDBACK = 0x00000040,
STARTF_FORCEOFFFEEDBACK = 0x00000080,
STARTF_USESTDHANDLES = 0x00000100,
}
public enum ShowWindow : short
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
public static class Kernel32
{
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
CreationFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
}
"#
$si = New-Object STARTUPINFO
$pi = New-Object PROCESS_INFORMATION
$si.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($si)
$si.wShowWindow = [ShowWindow]::SW_SHOW
$pSec = New-Object SECURITY_ATTRIBUTES
$tSec = New-Object SECURITY_ATTRIBUTES
$pSec.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($pSec)
$tSec.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($tSec)
[Kernel32]::CreateProcess("c:\windows\notepad.exe", $null, [ref] $pSec, [ref] $tSec, $false, [CreationFlags]::NONE, [IntPtr]::Zero, $null, [ref] $si, [ref] $pi)
[System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
$pi
Try using a real CurrentDirectory instead of $null:
[Kernel32]::CreateProcess("c:\windows\notepad.exe", $null, [ref] $pSec, [ref] $tSec, $false, [CreationFlags]::NONE, [IntPtr]::Zero, "c:", [ref] $si, [ref] $pi)