LinqToTwitter I can't catch tweets - twitter

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

Related

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.

Exception on Fetch/Clone/Pull with custom transport

I wrote a custom smarttransport. After fetch, pull or clone I get valid data but the method throws LibGit2Sharp Exception with "error reading from the zlib stream".
Transport with upload-pack read->write->read->write works.
READ:
00fc5daa747d4ca7905ff8996f770ef74d1b894be3d2 HEAD multi_ack thin-pack
side-band side-band-64k ofs-delta shallow deepen-since deepen-not
deepen-relative no-progress include-tag multi_ack_detailed
symref=HEAD:refs/heads/master agent=git/2.18.0.windows.1
003f5daa747d4ca7905ff8996f770ef74d1b894be3d2 refs/heads/master
003e5daa747d4ca7905ff8996f770ef74d1b894be3d2 refs/heads/test2 0000
WRITE:
0074want 5daa747d4ca7905ff8996f770ef74d1b894be3d2
multi_ack_detailed side-band-64k include-tag thin-pack ofs-delta
0032want 5daa747d4ca7905ff8996f770ef74d1b894be3d2 00000009done
READ:
0008NAK 0023Enumerating objects: 9, done. Counting objects: 100%
(9/9), done. Compressing objects: 100% (6/6), done. 002bTotal 9
(delta 0), reused 0 (delta 0) 02e7PACK òx£ì-1-0
+=»+ÄälºNc !6Ìß$NAé+­x-m763[AÁ+sª$C+!7eì[å$í¦Àn÷^A&ã:Cÿ+-T#&Ö+BfàªäëKê+Úg_·µ»}+²i¨yi·¦Ò+ï«gÅÉä+Ç
\Ú¤þ}¹©]ks_.k8¬òx£ì-=-0#ß=º+ÄäþºÄäþpº
ZéZszûÀ}z¦ëÏ\KpêÈUqòÉk+=-Ç U8O
àú¨­&oÁëÿ=óª=d+AÊ4qóÏÇ:+ã-áß»>ãf´cÌÝe>zٳƾ2*/WÙó?«ô-hOÇ
ªÄu}¬- -¿ýj~Ç#9[ÿ
x£ì-1-0#Ð=º­ÄäLLöTBê¡þpmÀDñDj-²¦#¦³7}¯¦#°nël8eÔR-ª¿ëSûY'UM%IÓƒ+¹c_vx,g_3ý+¦p{--ûé4d©DÊÎÁ¦¦ G¿¯Ûò[8
Ë-õ¿x£343
¢Éd¸¦åîUFzÜ--£+²Ê½2.Þr³ê]ÙdhfbóPöÜÿÆø¬WRQ-ã»Ã¤J¦_Ðß¾ØKMº¥à
3Sã¦x£-¦-,+L¦QH+¤--,I,NIa.-à-3©îí+ §Ó-¿x£343
¢Éd¸¦åîUFzÜ--£+²Ê½2.Þr³ê]ÙdhfbóPöÜÿÆø¬WRQ-­=âìBnï§+=ƒ º=¦|[c
N+ô¦x£-¦-,+L¦QH+¤--,I,NIa.-ò
+®*ªx£340031Q(JML+Mi+®(a+§u¦sQ?-§î¦O´¢¹¦,²Û+. H>x£-¦-,+L¦QH+¤--, )-öP¸ãyô
WRITE:
0000
Exception:
An unhandled exception of type 'LibGit2Sharp.LibGit2SharpException'
occurred in LibGit2Sharp.dll
Additional information: error reading from the zlib stream
Callstack:
bei LibGit2Sharp.Core.Ensure.HandleError(Int32 result) in
C:\projects\libgit2sharp\LibGit2Sharp\Core\Ensure.cs:Zeile 136. bei
LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteHandle remote,
IEnumerable1 refSpecs, GitFetchOptions fetchOptions, String
logMessage) in
C:\projects\libgit2sharp\LibGit2Sharp\Core\Proxy.cs:Zeile 2268. bei
LibGit2Sharp.Commands.Fetch(Repository repository, String remote,
IEnumerable1 refspecs, FetchOptions options, String logMessage) in
C:\projects\libgit2sharp\LibGit2Sharp\Commands\Fetch.cs:Zeile 76.
bei GitFunction.Test.Beta2.button1_Click(Object sender, EventArgs e)
in
C:\TFS\DS\ThomasZ\BeckhoffGitAdsService\GitAdsServicePackage\GitFunction.Test\Beta2.cs:Zeile
62. bei System.Windows.Forms.Control.OnClick(EventArgs e) bei System.Windows.Forms.Button.OnClick(EventArgs e) bei
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) bei
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) bei
System.Windows.Forms.Control.WndProc(Message& m) bei
System.Windows.Forms.ButtonBase.WndProc(Message& m) bei
System.Windows.Forms.Button.WndProc(Message& m) bei
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) bei
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) bei
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) bei
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) bei
System.Windows.Forms.Application.Run(Form mainForm) bei
GitFunction.Test.Program.Main() in
C:\TFS\DS\ThomasZ\BeckhoffGitAdsService\GitAdsServicePackage\GitFunction.Test\Program.cs:Zeile
19. bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) bei
System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args) bei
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) bei
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) bei
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) bei
System.Threading.ThreadHelper.ThreadStart()
Versions:
git version 2.18.0.windows.1
Win 10 x64
LibGit2Sharp 0.24.0.0
LibGit2Sharp 0.25.0.0
FYI:
UTF8Encoding and Encoding.Utf8 are not equal. Encoding.Utf8 adds UTF8 BOM (Byte-order Mark). This leads to this error. Setting all encodings to UTF8Encoding in my code fixed my problem.

Logging Response bodies in action filters

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.

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