GraphQL json parser and AllowSynchronousIO - c#

I'm starting to implement GraphQA in .NET with https://github.com/graphql-dotnet/server, I wrote a very simple sample application and while running Graphiql I got the following error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer(Span`1 userBuffer, Boolean& readToUserBuffer)
at System.IO.StreamReader.ReadSpan(Span`1 buffer)
at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
at Newtonsoft.Json.JsonTextReader.ReadData(Boolean append, Int32 charsRequired)
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)
at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.Deserialize[T](Stream s)
at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore(HttpContext context, ICorsPolicyProvider corsPolicyProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I found a workaround here https://github.com/graphql-dotnet/graphql-dotnet/issues/1116 which states that the configuration for IIS/Krestel needs to allow Synchronous IO using the following:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
I see that https://www.nuget.org/packages/GraphQL.Server.Transports.AspNetCore.NewtonsoftJson is still in alpha, so I'm guessing I have to use the build in JSON parser of .NET Core 3.1.
What are the implications of setting AllowSynchronousIO would it make the calls the server can handle slower?

Related

C# SOAP Middleware MessageEncoder.WriteMessage

I try to run this tutorial: custom-asp-net-core-middleware-example
But the reponse message at the client say´s:
S
ystem.ServiceModel.ProtocolException: There is a problem with the XML that was received from the network. See inner exception for more details.
---> System.Xml.XmlException: Name cannot begin with the '/' character, hexadecimal value 0x2F. Line 1, position 74.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Xml.XmlUTF8TextReader.VerifyNCName(String s)
at System.Xml.XmlUTF8TextReader.ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
at System.Xml.XmlUTF8TextReader.ReadStartElement()
at System.Xml.XmlUTF8TextReader.Read()
at System.ServiceModel.Channels.Message.ReadStartBody(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion, Boolean& isFault, Boolean& isEmpty)
at System.ServiceModel.Channels.ReceivedMessage.ReadStartBody(XmlDictionaryReader reader)
at System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, Boolean[] understoodHeaders, Boolean understoodHeadersModified)
at System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.ReadMessage(ArraySegment`1 buffer, BufferManager bufferManager, String contentType)
at System.ServiceModel.Channels.MessageEncoder.ReadMessageAsync(Stream stream, BufferManager bufferManager, Int32 maxBufferSize, String contentType, CancellationToken cancellationToken)
at System.ServiceModel.Channels.HttpResponseMessageHelper.ReadChunkedBufferedMessageAsync(Task`1 inputStreamTask, TimeoutHelper timeoutHelper)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass1_0.<CreateGenericTask>b__0(IAsyncResult asyncResult)
I´ve also encounterd a problem with the request-message so I´ve written my own RequestMessage but I´m not sure whether I should write my own ResponseMessage, because I do not know how it should be.
Also I´ve changed the OperationDescription to fit the tutorials code, may there be the problem?
public OperationDescription(ContractDescription contract, MethodInfo operationMethod, OperationContractAttribute contractAttribute)
{
Contract = contract;
SoapAction = contractAttribute.Name ?? operationMethod.Name;
Name = contractAttribute.Action ?? $"{contract.Namespace.TrimEnd('/')}/{contract.Name}/{Name}".Trim('/');
IsOneWay = contractAttribute.IsOneWay;
ReplyAction = contractAttribute.ReplyAction;
DispatchMethod = operationMethod;
}

Dynamics CRM 2016 on-premise Disable a user does not work

We upgraded to CRM 365 on-premise (8.2.2) and we are using custom code to deactivate users, (to move data to another user and other things). In the end, we use this example code: https://learn.microsoft.com/en-us/dynamics365/customer-engagement/developer/sample-disable-user
But that no longer works for us after the upgrade.
Now we get '-1 is not a valid state code on mailbox with Id ' and looking at the error on the server it looks like this:
[2018-09-17 08:07:45.297] Process: w3wp |Organization: |Thread: 9 |Category: Platform.Sdk |User: |Level: Error |ReqId: 129694cd-1d73-4723-8d3e-ca9487294697 |ActivityId: ad01991a-c02a-4f1e-9db1-3a936a432752 | VersionedPluginProxyStepBase.Execute ilOffset = 0x64
Web Service Plug-in failed in SdkMessageProcessingStepId: {57CDBB1B-EA3E-DB11-86A7-000A3A5473E8}; EntityName: systemuser; Stage: 30; MessageName: SetStateDynamicEntity; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.CrmArgumentException: -1 is not a valid state code on mailbox with Id .
at Microsoft.Crm.BusinessEntities.StatusCodeValidator.Validate(EntityMetadata entityMetadata, Int32 stateCode, Int32 statusCode, Guid businessEntityId)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.SetState(BusinessEntityMoniker moniker, Int32 newState, Int32 newStatusCode, BusinessEntity originalEntity, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.SetState(BusinessEntityMoniker moniker, Int32 newState, Int32 newStatusCode, ExecutionContext context)
at Microsoft.Crm.ObjectModel.MailboxServiceInternal1.SetState(BusinessEntityMoniker moniker, Int32 newState, Int32 newStatusCode, ExecutionContext context)
at Microsoft.Crm.ObjectModel.SystemUserServiceInternal1.SetMailboxState(BusinessEntityMoniker moniker, Int32 newState, Int32 newStatusCode, ExecutionContext context)
at Microsoft.Crm.ObjectModel.SystemUserServiceInternal`1.SetState(BusinessEntityMoniker moniker, Int32 newState, Int32 newStatusCode, ExecutionContext context)
at Microsoft.Crm.ObjectModel.SystemUserService.Microsoft.Crm.Sdk.IStateful.SetStateStatus(BusinessEntityMoniker , Int32 , Int32 , ExecutionContext )
Inner Exception: System.ArgumentException: -1 is not a valid state code on mailbox with Id .
Parameter name: stateCode
So I tried to deactivate the user mailboxes first, but it does not help. Still the same issue. Anyone have the same issue and resolved it somehow?
Try to use the IOrganizationService.Update() method to update the statecode/statuscode fields.
_service.Update(new SystemUser{ Id = <systemuserid>, StateCode= new OptionSetValue(1), StatusCode= new OptionSetValue(-1)});

model difference middle tier xpand

I am trying to get the Demo provided in expand framework source to work located in
"Xpand-Source-17.1.3.6\Demos\Middle Tier\E4035-Remoting" to work out of the box but i get the exception below.Specifically i want to use the model difference in a remoting scenario.
Object reference not set to an instance of an object.
Server stack trace:
at DevExpress.ExpressApp.Security.SecurityStrategy.GetObjectSpaces()
at DevExpress.ExpressApp.Security.SecurityStrategy.RegisterProcessors(Dictionary`2 processors, Object permissionsProvider, IObjectSpace objectSpace)
at DevExpress.ExpressApp.Security.SecurityStrategy.CreateSelectDataSecurityCore(IObjectSpace objectSpace)
at DevExpress.ExpressApp.Security.SecurityStrategy.CreateSelectDataSecurity(IObjectSpace objectSpace)
at DevExpress.ExpressApp.Security.ClientServer.SecuredSerializableObjectLayer.CreateSerializableObjectLayerCore(IClientInfo clientInfo, IDataLayer dataLayer, IRequestSecurityStrategyProvider securityStrategyProvider, UnitOfWork& result_parentSession, ISecurityRule& securityRule, Boolean allowICommandChannelDoWithSecurityContext)
at DevExpress.ExpressApp.Security.ClientServer.SecuredSerializableObjectLayer.GetSerializableObjectLayer(IClientInfo clientInfo, UnitOfWork& result_parentSession)
at DevExpress.ExpressApp.Security.ClientServer.SecuredSerializableObjectLayerBase.DevExpress.ExpressApp.Security.ClientServer.ISecuredSerializableObjectLayer.LoadObjects(IClientInfo clientInfo, XPDictionaryStub dictionary, ObjectStubsQuery[] queries)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at DevExpress.ExpressApp.Security.ClientServer.ISecuredSerializableObjectLayer.LoadObjects(IClientInfo clientInfo, XPDictionaryStub dictionary, ObjectStubsQuery[] queries)
at DevExpress.Xpo.SerializableObjectLayerClient.LoadObjects(Session session, ObjectsQuery[] queries)
at DevExpress.Xpo.Logger.LogManager.Log[T](String category, LogHandler1 handler, MessageHandler1 createMessageHandler)
at DevExpress.Xpo.Session.GetObjects(ObjectsQuery query)
at DevExpress.Xpo.Session.GetObjects(XPClassInfo classInfo, CriteriaOperator criteria, SortingCollection sorting, Int32 topSelectedRecords, Boolean selectDeleted, Boolean force)
at DevExpress.Xpo.Helpers.XPObjectTypesManager.GetAllTypes()
at DevExpress.Xpo.Session.<>c__DisplayClass3a.b__38()
at DevExpress.Xpo.Logger.LogManager.Log[T](String category, LogHandler1 handler, MessageHandler1 createMessageHandler)
at DevExpress.Xpo.Session.GetObjectByKey(Type classType, Object id)
at DevExpress.ExpressApp.Xpo.XPObjectSpace.GetObjectByKey(Type objectType, Object key)
at DevExpress.ExpressApp.Security.ClientServer.ServerSecurityClient.get_User()
at Xpand.ExpressApp.ModelDifference.DataStore.Queries.QueryUserModelDifferenceObject.get_UsersContainsOperator()
at Xpand.ExpressApp.ModelDifference.DataStore.Queries.QueryUserModelDifferenceObject.GetActiveModelDifferences(String applicationName, String name, DeviceCategory deviceCategory)
at Xpand.ExpressApp.ModelDifference.DictionaryStores.XpoUserModelDictionaryDifferenceStore.GetActiveDifferenceObjects(DeviceCategory deviceCategory)
at Xpand.ExpressApp.ModelDifference.DictionaryStores.XpoUserModelDictionaryDifferenceStore.LoadCore(ModelApplicationBase userDiff)
at DevExpress.ExpressApp.ApplicationModelManager.CreateLayerByStore(String id, ModelStoreBase store)
at DevExpress.ExpressApp.XafApplication.LoadUserDifferences()
at DevExpress.ExpressApp.XafApplication.Logon(PopupWindowShowActionExecuteEventArgs logonWindowArgs)
at DevExpress.ExpressApp.Win.WinApplication.Logon(PopupWindowShowActionExecuteEventArgs logonWindowArgs)
Remoting is rather old technology as such the E4035 demo is not updated nor tested often. Instead you may use the E4036-WCF demo which is EasyTested on each build.

Error of MONGODBDriver2.4.4.0

I have facing this issues for quite sometimes, hope that got someone can save me, thx.
C# : MongoDBDriver 2.4.4.0
.NET Framework 4.5
Windows Console
C# Code
var cli = new MongoClient("server");
var dbObj = cli.GetDatabase("col");
var dbColObj = dbObj.GetCollection<MyColModel>("data");
dbColObj.Find(o=>o.Name == "OK").ToList();//
When I does this 10 times, it will success 2 times and another 8 times return the error below:
Exception : Unable to translate bytes [D3] at index -1 from specified code page to Unicode.
System.Text.DecoderExceptionFallbackBuffer.Throw(Byte[] bytesUnknown, Int32 index) +5477885
System.Text.DecoderExceptionFallbackBuffer.Fallback(Byte[] bytesUnknown, Int32 index) +9
System.Text.DecoderFallbackBuffer.InternalFallback(Byte[] bytes, Byte* pBytes) +41
System.Text.UTF8Encoding.FallbackInvalidByteSequence(Byte* pSrc, Int32 ch, DecoderFallbackBuffer fallback) +45
System.Text.UTF8Encoding.GetCharCount(Byte* bytes, Int32 count, DecoderNLS baseDecoder) +14317552
System.Text.UTF8Encoding.GetString(Byte[] bytes, Int32 index, Int32 count) +147
MongoDB.Bson.IO.ByteBufferStream.ReadString(UTF8Encoding encoding) +301
MongoDB.Bson.Serialization.Serializers.BsonStringSerializer.DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) +24
MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) +117
MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize(IBsonSerializer`1 serializer, BsonDeserializationContext context) +111
MongoDB.Bson.Serialization.Serializers.BsonValueSerializer.DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) +767
MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) +117
MongoDB.Bson.Serialization.Serializers.BsonDocumentSerializer.DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) +251
MongoDB.Bson.Serialization.Serializers.BsonValueSerializerBase`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) +117
MongoDB.Bson.RawBsonDocument.Materialize(BsonBinaryReaderSettings binaryReaderSettings) +236
MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply) +541
MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken) +296
MongoDB.Driver.Core.Servers.ServerChannel.ExecuteProtocol(IWireProtocol`1 protocol, CancellationToken cancellationToken) +183
MongoDB.Driver.Core.Operations.CommandOperationBase`1.ExecuteProtocol(IChannelHandle channel, ServerDescription serverDescription, ReadPreference readPreference, CancellationToken cancellationToken) +385

Cannot find the requested object when attempting to load new X509 Certificate

I'm just walking through the IdentityServer 3 official tutorials and I'm on the MVC app tutorial (https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html) but I've hit a roadblock. on the section 'Adding Startup' it gets you to download a certificate to use in the application, but I can't get this to work.
The sample code that is failing locally is:
X509Certificate2 LoadCertificate()
{
return new X509Certificate2(
string.Format(#"{0}\bin\identityServer\idsrv3test.pfx", AppDomain.CurrentDomain.BaseDirectory), "idsrv3test");
}
But despite the certificate being in this location, I get an error. I've even tried copying the certificate to the temp folder so I know the path is good,
X509Certificate2 LoadCertificate()
{
return new X509Certificate2("c:\\temp\\idsrv3test.pfx", "idsrv3test");
}
but it still fails with the same message:
Cannot find the requested object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Security.Cryptography.CryptographicException: Cannot find the requested object.
Source Error:
Line 33: X509Certificate2 LoadCertificate()
Line 34: {
Line 35: return new X509Certificate2("c:\\temp\\idsrv3test.pfx", "idsrv3test");
Line 36: }
Line 37: }
Stack trace:
[CryptographicException: Cannot find the requested object.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +36
System.Security.Cryptography.X509Certificates.X509Utils._QueryCertBlobType(Byte[] rawData) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) +66
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password) +109
is3_mvc.Startup.LoadCertificate() in C:\scratch\.net\IdentityServer3\is3-mvc\is3-mvc\Startup.cs:59
is3_mvc.Startup.<Configuration>b__4_0(IAppBuilder idsrvApp) in C:\scratch\.net\IdentityServer3\is3-mvc\is3-mvc\Startup.cs:25
Owin.MapExtensions.Map(IAppBuilder app, PathString pathMatch, Action`1 configuration) +178
Owin.MapExtensions.Map(IAppBuilder app, String pathMatch, Action`1 configuration) +108
is3_mvc.Startup.Configuration(IAppBuilder app) in C:\scratch\.net\IdentityServer3\is3-mvc\is3-mvc\Startup.cs:23
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9963380
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I've also tried loading the cert using a different approach:
var stx = File.Open(#"c:\temp\idsrv3test.pfx", FileMode.Open);
using (BinaryReader br = new BinaryReader(stx))
{
return new X509Certificate2(br.ReadBytes((int)br.BaseStream.Length), "idsrv3test");
}
But this gives exactly the same error, so I dont think its a problem loading the file per se.
Has anyone encountered this problem? Seems others have had similar problems on SO before, but no exact solution has been posted that matches the above.
I'm guessing its not the actual locating of the file that is the problem here but something else, but I dont know what that could be...
Thanks
Rather than new X509Certificate2 file that is using
X509Certificate2 cert = new X509Certificate2(#"C:\Certificates\cert.pem");
use X509Certificate2 function methods. example
X509Certificate2 cert = X509Certificate2.CreateFromPemFile(#"C:\Certificates\cert.pem");
There are other inbuilt static methods for instantiating certificates. Check them out in metadata

Categories