Logging Response bodies in action filters - asp.net-mvc

I have the following code in a class that implements IAsyncActionFilter using .Net Core.
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
await next.Invoke();
using (var reader = new StreamReader(context.HttpContext.Response.Body))
{
var responseBodyText = await reader.ReadToEndAsync();
var messageObjToLog = new
{
responseBody = responseBodyText,
statusCode = context.HttpContext.Response.StatusCode
};
_logger.LogInformation(JsonConvert.SerializeObject(messageObjToLog));
context.HttpContext.Response.Body.Seek(0, SeekOrigin.Begin);
}
}
This line:
using (var reader = new StreamReader(context.HttpContext.Response.Body))
produces the following error
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLFBE2K7NSD3", Request id "0HLFBE2K7NSD3:00000001": An
unhandled exception was thrown by the application.
System.ArgumentException: Stream was not readable. at
System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean
detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
at System.IO.StreamReader..ctor(Stream stream) at
Adapter.Logging.Middleware.LogResponseFilter.d__2.MoveNext()
in C:\src\Adapter\Logging\Middleware\LogRequestResponseFilter.cs:line
56
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,
Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.d__2.MoveNext()
My question is:
What do I need to do in order to safely reset the response stream?
I have another implementation of IAsyncActionFilter for logging:
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
using (var reader = new StreamReader(context.HttpContext.Request.Body))
{
var requestBodyText = await reader.ReadToEndAsync();
context.HttpContext.Request.EnableRewind();
context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
var messageObjToLog = new
{
scheme = context.HttpContext.Request.Scheme,
host = context.HttpContext.Request.Host,
path = context.HttpContext.Request.Path,
queryString = context.HttpContext.Request.Query,
requestBody = requestBodyText
};
_logger.LogInformation(JsonConvert.SerializeObject(messageObjToLog));
}
await next.Invoke();
}

Probably put "await next.Invoke();" at the end of the method.

Related

TikaOnDotNet with .NET Core 3.1 / .NET 5 fails with Method not found: 'Void System.IO.FileStream..ctor

With .NET Core 3.1 and .NET 5 I tried to reference the TikaOnDotNet NuGet package.
Sample code is as follows.
using System;
using System.IO;
using TikaOnDotNet.TextExtraction;
namespace tika
{
class Program
{
static void Main(string[] args)
{
var textExtractor = new TextExtractor();
var original = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), #"pptexamples.ppt"));
var wordDocContents = textExtractor.Extract(original.FullName);
}
}
}
In the textExtractor.Extract method it throws below exception.
TikaOnDotNet.TextExtraction.TextExtractionException: "Extraction of text from the file '/Users/serhatonal/Projects/tika/tika/bin/Debug/netcoreapp3.1/pptexamples.ppt' failed." ---> TikaOnDotNet.TextExtraction.TextExtractionException: "Extraction failed." ---> System.MissingMethodException: "Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'."
at Java_java_io_FileDescriptor.open(String name, FileMode fileMode, FileAccess fileAccess)
at java.io.FileDescriptor.open(String , FileMode , FileAccess )
at java.io.FileDescriptor.open(String , Int32 , Int32 )
at java.io.FileDescriptor.openReadOnly(String )
at Java_java_io_RandomAccessFile.open0(Object _this, String name, Int32 mode, FileDescriptor fd, Int32 O_RDWR)
at java.io.RandomAccessFile.open0(String , Int32 )
at java.io.RandomAccessFile.open(String , Int32 )
at java.io.RandomAccessFile..ctor(File file, String mode)
at java.util.zip.ZipFile..ctor(File file, Int32 mode, Charset charset)
at java.util.zip.ZipFile..ctor(File file, Int32 mode)
at java.util.jar.JarFile..ctor(File file, Boolean verify, Int32 mode)
at java.util.jar.JarFile..ctor(String name)
at IKVM.NativeCode.ikvm.runtime.AssemblyClassLoader.lazyDefinePackages(ClassLoader _this)
at ikvm.runtime.AssemblyClassLoader.lazyDefinePackages()
at ikvm.runtime.AssemblyClassLoader.lazyDefinePackagesCheck()
at ikvm.runtime.AssemblyClassLoader.getPackage(String name)
at java.lang.Package.getPackage(Class )
at java.lang.Class.getPackage()
at org.apache.tika.mime.MimeTypesFactory.create(String coreFilePath, String extensionFilePath, ClassLoader classLoader)
at org.apache.tika.mime.MimeTypes.getDefaultMimeTypes(ClassLoader classLoader)
at org.apache.tika.config.TikaConfig.getDefaultMimeTypes(ClassLoader )
at org.apache.tika.config.TikaConfig..ctor()
at org.apache.tika.config.TikaConfig.getDefaultConfig()
at org.apache.tika.parser.AutoDetectParser..ctor()
at TikaOnDotNet.TextExtraction.Stream.StreamTextExtractor.Extract(Func`2 streamFactory, Stream outputStream)
--- End of inner exception stack trace ---
at TikaOnDotNet.TextExtraction.Stream.StreamTextExtractor.Extract(Func`2 streamFactory, Stream outputStream)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](Func`2 streamFactory, Func`3 extractionResultAssembler)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](String filePath, Func`3 extractionResultAssembler)
--- End of inner exception stack trace ---
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](String filePath, Func`3 extractionResultAssembler)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract(String filePath)
at tika.Program.Main(String[] args) in /Users/serhatonal/Projects/tika/tika/Program.cs:16
Even though I found out that issue "System.MissingMethodException: "Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'."" is considered fixed with the .NET 5 release according to below issue. But the problem still persists.
https://github.com/dotnet/runtime/issues/30435
Anyone having the same issue?
IMVM the basis of the library, as this is a java port, is not dotnet
core compatible.
https://github.com/KevM/tikaondotnet/issues/136#issuecomment-583695410
Unfortunately, this is why.

ASP.NET Core on Linux problem with itextsharp

We have a small ASP.NET Core 3.1 web app. We use itextsharp library (5.5.13) for generating a simple PDF and exporting it.
All works well in debug (and on Windows server), but when published on a Linux server (Debian 10) there is an error generating the PDF:
Error: The document has no pages.
Stack trace:
at iTextSharp.text.pdf.PdfPages.WritePageTree()
at iTextSharp.text.pdf.PdfWriter.Close()
at iTextSharp.text.pdf.PdfDocument.Close()
at iTextSharp.text.Document.Close()
at eDov.Web.Helpers.Reports.Dovolilnice.GetPdfTest() in C:\*\Reports\Dovolilnica.cs:line 173
at eDov.Web.Controllers.DovolilniceController.TestPdf(Int32 id) in C:\*\Controllers\DovolilniceController.cs:line 184
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
The code from the controller that is called to generate the PDF:
public IActionResult TestPdf(int id)
{
var file = new Dokument
{
Naziv = string.Format("Dovolilnica - {0}.pdf", id.ToString()),
Extension = ".pdf",
ContentType = "application/pdf",
};
//this is the line that the error from stack trace is referring
file.Contents = Helpers.Reports.Dovolililnice.GetPdfTest();
return File(file.Contents, file.ContentType, file.Naziv);
}
and the code that generates the PDF:
public static byte[] GetPdfTest()
{
byte[] result = null;
// custom velikost nalepke
// 1 inch = 72px
var pgSize = new iTextSharp.text.Rectangle(176f, 135f);
MemoryStream pdfData = new MemoryStream();
iTextSharp.text.Document document = new iTextSharp.text.Document(pgSize, 7.5f, 7.5f, 7.5f, 7.5f);
PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdfData);
pdfWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
document.Open();
document.Add(new Paragraph("Create test Pdf Document"));
pdfWriter.CloseStream = false;
document.Close();
//this is the line that the error from stack trace is referring
pdfData.Position = 0;
result = pdfData.ToArray();
pdfData.Dispose();
return result;
}
Has anyone used itextsharp (lower than version 7) successfully when publishing on Linux?
We couldn't get this working on Linux so we tried using iTextSharp.LGPLv2.Core port of the itextsharp library (see: https://github.com/VahidN/iTextSharp.LGPLv2.Core) and it works.
It's also available in Nuget PM.

LinqToTwitter I can't catch tweets

I am trying to fetch tweets using the example on GitHub, but I get an error "The underlying connection was closed: An unexpected error occurred in a submission". I can not understand. At first, I created the application on Twitter and took the keys generated by Twitter and added it to the application. I had doubts about 2 attributes that I don't know what they will be used for, and I don't know if they are causing problems:
1 - Website URL - I created a website on Wix to fill this field, but I didn't understand its use, since I just want to read tweets in a desktop application.
2 - Callback URL - Initially I didn't put anything, then I saw in a post that it was to put http://127.0.0.1/ I ran the application with this information, but again I don't know what it is for, because I'm going to get tweets from a desktop application .
Here are the code used and the error received!
using System;
using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
MainAsync().Wait();
}
static async Task MainAsync()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore()
{
ConsumerKey = "MyConsumerKey",
ConsumerSecret = "MyConsumerSecret",
OAuthToken = "MYOAuthToken",
OAuthTokenSecret = "MYOAuthTokenSecret"
}
};
var twitterCtx = new TwitterContext(auth);
var searchResponse = await (from search in twitterCtx.Search
where search.Type == SearchType.Search
&& search.Query == "flamengo"
select search).SingleOrDefaultAsync();
if (searchResponse != null && searchResponse.Statuses != null)
searchResponse.Statuses.ForEach(tweet =>
Console.WriteLine(
"User: {0}, Tweet: {1}",
tweet.User.ScreenNameResponse,
tweet.Text));
}
}
}
System.AggregateException was unhandled
HResult=-2146233088
Message=Um ou mais erros.
Source=mscorlib
StackTrace:
em System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
em System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
em System.Threading.Tasks.Task.Wait()
em ConsoleApplication3.Program.Main() na C:\Danilo\Docs\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:linha 12
em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
em System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233088
Message=Ocorreu um erro ao enviar a solicitação.
Source=mscorlib
StackTrace:
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em LinqToTwitter.Net.GetMessageHandler.<SendAsync>d__4.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em LinqToTwitter.TwitterExecute.<QueryTwitterAsync>d__48 1.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em LinqToTwitter.TwitterContext.<ExecuteAsync>d__136 1.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em LinqToTwitter.TwitterQueryProvider.<ExecuteAsync>d__8 1.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em LinqToTwitter.TwitterExtensions.<SingleOrDefaultAsync>d__5 1.MoveNext()
--- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---
em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
em ConsoleApplication3.Program.<MainAsync>d__1.MoveNext() na C:\Danilo\Docs\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:linha 29
InnerException:
HResult=-2146233079
Message=A conexão subjacente estava fechada: Erro inesperado em um envio.
Source=System
StackTrace:
em System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
em System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
InnerException:
HResult=-2146232800
Message=Não é possível ler os dados da conexão de transporte: Foi forçado o cancelamento de uma conexão existente pelo host remoto.
Source=System
StackTrace:
em System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
em System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
em System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
InnerException:
ErrorCode=10054
HResult=-2147467259
Message=Foi forçado o cancelamento de uma conexão existente pelo host remoto
NativeErrorCode=10054
Source=System
StackTrace:
em System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
em System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
InnerException:
This looks similar to the question we resolved here, where the problem was needing to set to TLS 1.2 because it was an older .NET version:
Visual Studio 2015 - Debug with HTTP connection problems

Neo4jClient System.NullReferenceException

some times in Neo4jClient I got this error. I try to investigation whats the problem but I don't found any reason. Does any one have the same problem or can help me?
Thanks
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at
Neo4jClient.GraphClient.Neo4jClient.IRawGraphClient.ExecuteGetCypherResults[TResult](CypherQuery query) in D:\temp\9517fa3\Neo4jClient.Shared\GraphClient.cs:line 919\r\n at
Mandarim.Storage.Neo4j.Manager.ManagerBase1.GetNodesRelatedOrderBy(String match, String id, String relationNodeType, String propertyOrderBy, Int32 skip, Int32 take, Direction direction,
Boolean distinct, Expression1 where) in P:\Desenvolvimento\branchs\builder-3.0\Mandarim.Storage.Neo4j\Manager\ManagerBase.cs:line 2105\r\n at
Mandarim.Storage.Neo4j.Manager.ManagerBase1.GetNodesRelatedOrderBy(String id, Labels labelin, Labels labelout, String relationTypes, String propertyOrderBy, Int32 skip, Int32 take, Boolean
distinct, Expression1 where, Direction direction) in P:\Desenvolvimento\branchs\builder-3.0\Mandarim.Storage.Neo4j\Manager\ManagerBase.cs:line 900\r\n at
Mandarim.Factory.Base.FactoryBase1.GetNodesRelatedOrderBy(String id, Labels labelin, Labels labelout, String relationTypes, String propertyOrderBy, Int32 skip, Int32 take, Boolean distinct,
Expression1 where, Direction direction) in P:\Desenvolvimento\branchs\builder-3.0\Mandarim.Factory\Base\FactoryBase.cs:line 177\r\n at
PackDocs.Services.Storage.MandarimStorageServices1.GetNodesRelatedOrderBy(String id, Labels labelin, Labels labelout, String propertyOrderBy, Int32 skip, Int32 take, Boolean distinct,
Expression1 where, Direction direction, RelationTypes[] relationNodeType) in P:\Desenvolvimento\branchs\builder-3.0\Packdocs.Services.Storage\MandarimStorageServices.cs:line 292\r\n
at Mandarim.PackDocs.Services.ManagerObjects.ManagerProject.GetProjects(Int32 skip, Int32 take, String orderby, CreatedState state) in
P:\Desenvolvimento\branchs\builder-3.0\PackDocs.Services\ManagerObjects\ManagerProject.cs:line 116\r\n at PackDocs.OWIN.Services.Host.Controllers.ProjectsController.GetProjects(Int32
skip, Int32 take, String orderby, CreatedState state) in P:\Desenvolvimento\branchs\builder-3.0\Packdocs.OWIN.Services.Host\Controllers\v2\ProjectsController.cs:line 103\r\n at
lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[]
methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken
cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at
System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at
System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at
System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}
Update
ContainerBuilder _builder = new ContainerBuilder();
_builder
.Register<ITransactionalGraphClient>(context =>
{
try
{
var neo4jUri = GetNeo4jSettingValue("neo4jUri");
var user = GetNeo4jSettingValue("neo4jUser");
var pwd = GetNeo4jSettingValue("neo4jPassword");
ITransactionalGraphClient graphClient = new GraphClient(new Uri(neo4jUri), user, pwd);
graphClient.Connect();
graphClient.JsonConverters.Add(new DictionaryConverter());
graphClient.JsonConverters.Add(new DateTimeConverter());
graphClient.JsonConverters.Add(new CommonDeserializerMethods());
return graphClient;
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
throw e;
}
}).SingleInstance();
_container = _builder.Build();
Get Instance
try
{
_myGraphClient = _myGraphClient ?? AutofacNeo4j.Container.Resolve<ITransactionalGraphClient>();
if (_myGraphClient != null && !_myGraphClient.IsConnected)
_myGraphClient.Connect();
return _myGraphClient;
}
catch (Exception e)
{
Trace.TraceError(e.ToString());
_myGraphClient = _myGraphClient ?? AutofacNeo4j.Container.Resolve<ITransactionalGraphClient>();
_myGraphClient.Connect();
return _myGraphClient;
}
My query:
MyGraphClient.Cypher
.Match(match).Where((T a) => a.UUID == id)
.With("b")
.CurrentUser(CurrentUsername)
.WhereReadClause("b", GetDomainsClause("b"), CurrentUsername, CurrentRole, direction)
.Return(b => b.As<T>()).Results;
Second exception:
Neo4jClient.Transactions.TransactionManager.EnqueueCypherRequest(String commandDescription, IGraphClient graphClient, CypherQuery query) in D:\temp\9517fa3\Neo4jClient.Full\Transactions\TransactionManager.cs:line 229
at Neo4jClient.GraphClient.PrepareCypherRequest[TResult](CypherQuery query, IExecutionPolicy policy) in D:\temp\9517fa3\Neo4jClient.Shared\GraphClient.cs:line 871
at Neo4jClient.GraphClient.d__881.MoveNext() in D:\temp\9517fa3\Neo4jClient.Shared\GraphClient.cs:line 967
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Mandarim.Storage.Neo4j.Manager.ManagerBase`1.d__113.MoveNext() in P:\Desenvolvimento\branchs\builder-3.0\Mandarim.Storage.Neo4j\Manager\ManagerBase.cs:line 2067
The problem occurs when we use async api with multi-transaction here.
The [TreadStartic] on Neo4jClient code don't work very well with async method... so I change to use AsyncLocal.
More information can get here: https://github.com/Readify/Neo4jClient/pull/209

not able to get values in entity framework sometimes(i suspect there is issue with context creation)

I am getting null in the below statement sometimes.
public GlobalEnums.AuthenticationResults Authenticate(UserLoginDTO Login, bool skipPolicy = false, bool skipUpdateLastLoggedOn = false)
{
try
{
using (var context = new eNextDALEntities())
{
List<tblUser> lstUser = context.tblUsers
.Where(usr => (string.Compare(usr.UserName, Login.UserName, true) == 0))
.ToList();
Int32 userCnt = lstUser.Count;
}
}
catch (System.Exception ex)
{
throw ex;
}
}
so it results in throwing error "Object reference not set to an instance of an object. "
It rarely shows this behavior.
I am unable to understand this strange behavior. It would be helpful if someone explains me why and how of this behavior or else point me in the right direction of how I can avoid this situation.
I think it might be related to context creation but not sure though. Even if it is how should I solve it.
Calling Code -
public HttpResponseMessage Authenticate()
{
IEnumerable<string> headerValues;
string userName = "";
if (Request.Headers.TryGetValues("UserName", out headerValues))
{
userName = headerValues.First();
}
UserLoginDTO user = new UserLoginDTO();
user.UserName = userName;
if (userName == "")
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.Unauthorized, "Please provide the credentials.");
}
GlobalEnums.AuthenticationResults _login = _repository.Authenticate(user);
if (!_login.Equals(GlobalEnums.AuthenticationResults.Authenticated))
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.Unauthorized, _login.ToString());
}
else
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK);
}
}
Also the point that I am thinking is even if username is null or wrong and it doesnt get any data then also context.tblUsers
.Where(usr => (string.Compare(usr.UserName, Login.UserName, true) == 0))
.ToList();
will return empty list but it will not return null. It can return null only if there is some issue with context
STACK TRACE:
Stack Trace: at LoginRepository.Authenticate(UserLoginDTO Login)
at Controllers.LoginController.Authenticate()
at lambdamethod(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>cDisplayClass10.b9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ApiControllerActionInvoker.d0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ExceptionFilterResult.d_0.MoveNext()

Resources