Error in asp.net while testing web services - c#

I have a web service that should pull about 80 records from SQL database. However recently it started giving me out of memory error.
When I debug it - it shows me the web service on the list, once I run it - get the error below.
webmethod:
[WebMethod(Description = "Getting Weekly Events by Facility, future events from sunday", CacheDuration = 600)]
public List<EventViewModel> GetWeeklyEvents(string facilityNumber, DateTime StDate)
{
var db = new DS_AIMDataContext();
var eventList = from evt in db.GetPublishedEventsFromSundayByFacility(facilityNumber, StDate)
select new EventViewModel
{
EventName = evt.ActName,
EventNameSpanish = evt.ActNameSp,
EventDescription = evt.ActDescription,
EventDescrSpanish = evt.ActDescrSp,
StDate = evt.EventStart.Value,
EndDate = evt.EventEnd.Value,
EventCategory = evt.CategoryName,
EventCatID = evt.ActCategID.Value,
EventType = evt.ActType,
EventLocation = evt.LocName,
EventLeader = evt.LeaderName,
EventCategorySp = evt.CategoryNameSp,
EventTypeSp = evt.ActTypeSp,
EventRecurrenceRule = evt.RecurrenceRule,
EventPhoto1 = evt.Photo1 == null ? null : evt.Photo1.ToArray(),
EventPhoto2 = evt.Photo2 == null ? null : evt.Photo2.ToArray(),
EventPhoto3 = evt.Photo3 == null ? null : evt.Photo3.ToArray()
};
return eventList.ToList();
}
The function itself:
public IEnumerable<tblEventsWithRecurr> GetPublishedEventsFromSundayByFacility(string facN, DateTime StDate)
{
var eventList = from evt in this.tblEventsWithRecurrs
orderby Convert.ToDateTime(evt.EventStart.ToString()).Day, Convert.ToDateTime(evt.EventStart.ToString()).Hour, Convert.ToDateTime(evt.EventStart.ToString()).Minute
where (evt.FacN == facN && evt.EventStatus == "Final" && evt.EventStart >= StDate && evt.EventStart <= StDate.AddDays(31))
select evt;
return eventList;
}
Error that I'm getting is below:
Server Error in '/' Application.
Exception of type 'System.OutOfMemoryException' was thrown.
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.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.IO.MemoryStream.set_Capacity(Int32 value) +93
System.IO.MemoryStream.EnsureCapacity(Int32 value) +90
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +326
Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +61
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9641608
System.Web.HttpResponse.FilterOutput() +104
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +58
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

Couple of things:
First, how big are your Photo files - you have 3 photo's you're sending back. It would not be difficult to imagine a dozen very large photos on all of your results to max out whatever memory you have going on.
Secondly:
You may want to consider disposing of your datacontext.
Currently you have:
var db = new DS_AIMDataContext();
And this is never explicitly disposed, meaning the GC will eventually get to it, where you could instruct it to be disposed of the moment you are finished with it.
So try that line to:
using (DS_AIMDataContext db = new DS_AIMDataContext()){
// all of your eventList projection
// and your return statement
}
This will call Dispose as soon as your method completes and will hopefully free up memory.

Related

EF Core 7 Task Cancellation exception

I have a piece code written in an ASP Core 7 API, with EF Core 7, using MSSQL for the database. The below code is where the repository loads some data for the dashboard.
public async Task<ResponseResult<DashboardPendingBillsDto>> PendingBillDetails(CancellationToken token)
{
var venderInvoicelQuery = _context.Set<VendorInvoice>().AsQueryable();
var pendingBillsQuery = venderInvoicelQuery.Where(a => !a.IsBilled);
var today = DateTimeOffset.UtcNow;
var fourthDay = today.AddDays(-3);
var seventhDay = today.AddDays(-7);
var pendingBillsData = await pendingBillsQuery.Select(s => new
{
BetweenOneToFiveDays = pendingBillsQuery
.Where(a => fourthDay.Date < a.CreatedOn.Date && a.CreatedOn.Date <= today.Date).Count(),
BetweenSixToTenDays = pendingBillsQuery
.Where(a => seventhDay.Date < a.CreatedOn.Date && a.CreatedOn.Date <= fourthDay.Date).Count(),
AboveTenDays = pendingBillsQuery
.Where(a => a.CreatedOn.Date <= seventhDay.Date).Count()
}).FirstOrDefaultAsync(token);
var dashboardPendingBillsDto = new DashboardPendingBillsDto
{
BetweenZeroToThreeDays = pendingBillsData?.BetweenOneToFiveDays ?? 0,
BetweenFourToSevenDays = pendingBillsData?.BetweenSixToTenDays ?? 0,
AboveSevenDays = pendingBillsData?.AboveTenDays ?? 0,
};
return new ResponseResult<DashboardPendingBillsDto>(dashboardPendingBillsDto);
}
The above code returns the desired data as well as shown below
The problem is, if the HTTP request was cancelled, then the TaskCanceledException exception is thrown and it gives an error An error occurred using the connection to database 'test-db-12-jan-2023' on server 'DESKTOP-xxx. But i already passed the cancelation token into the FirstOrDefaultAsync(token) as such. it happens only if the http request was cancelled. Any help please.
update 29-jan-2023
I have a middle ware to handle exceptions globally and it is the first middle ware of the pipeline
And here is how the middleware handles the exceptions. i have only 2 exceptions here, TaskCanceledException and Exception
private Task ConvertException(HttpContext context, Exception exception)
{
var activityId = Activity.Current?.Id ?? "N/A";
_telemetry.TrackException(exception);
ErrorResponse errorResponse = new() { TraceId = activityId };
int httpStatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
var result = string.Empty;
switch (exception)
{
case TaskCanceledException:
//if client closes the connection
httpStatusCode = StatusCodes.Status200OK;
result = JsonConvert.SerializeObject(new ResponseResult<string>("Client closed the connecion"));
break;
case Exception:
httpStatusCode = StatusCodes.Status500InternalServerError;
errorResponse.Errors.Add(new KeyValuePair<string, IEnumerable<string>>(nameof(HttpStatusCode.InternalServerError), new[] { "Something went wrong, please try again" }));
result = JsonConvert.SerializeObject(errorResponse);
LogError(exception, activityId);
break;
}
context.Response.StatusCode = httpStatusCode;
return context.Response.WriteAsync(result);
}
Below is the exception message i get from the middleware
A task was cancelled
Below is the the stack trace from the exception which i can get from the middleware
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.<OpenInternalAsync>d__70.MoveNext()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.<OpenInternalAsync>d__70.MoveNext()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.<OpenAsync>d__66.MoveNext()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.<ExecuteReaderAsync>d__19.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.<InitializeReaderAsync>d__21.MoveNext()
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.<MoveNextAsync>d__20.MoveNext()
at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.GetResult()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.<SingleOrDefaultAsync>d__15`1.MoveNext()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.<SingleOrDefaultAsync>d__15`1.MoveNext()
at VPMS.Persistence.Repositories.Dashboard.DashboardRepository.<PendingBillDetails>d__3.MoveNext() in C:\Projects\Legacy HealthCare - Vendor Payment Management System\VPMS\VPMS.Persistence\Repositories\DashboardRepository\DashboardRepository.cs:line 162
at VPMS.Application.DashBoard.Services.DashboardService.<GetPendingBillsAsync>d__3.MoveNext() in C:\Projects\Legacy HealthCare - Vendor Payment Management System\VPMS\VPMS.Application\DashBoard\Services\DashboardService.cs:line 25
at VPMS.Api.Controllers.Dashboard.DashboardController.<GetPendingBills>d__2.MoveNext() in C:\Projects\Legacy HealthCare - Vendor Payment Management System\VPMS\VPMS.Api\Controllers\DashBoardController.cs:line 30
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.<Execute>d__0.MoveNext()
at System.Threading.Tasks.ValueTask`1.get_Result()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeNextActionFilterAsync>g__Awaited|10_0>d.MoveNext()
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 ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeFilterPipelineAsync>g__Awaited|20_0>d.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeAsync>g__Logged|17_1>d.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeAsync>g__Logged|17_1>d.MoveNext()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<<Invoke>g__AwaitRequestTask|6_0>d.MoveNext()
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.<Invoke>d__9.MoveNext()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.<Invoke>d__5.MoveNext()
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.<Invoke>d__4.MoveNext()
at VPMS.Api.Middleware.ExceptionHandlerMiddleware.<Invoke>d__3.MoveNext() in C:\Projects\Legacy HealthCare - Vendor Payment Management System\VPMS\VPMS.Api\Middleware\ExceptionHandlerMiddleware.cs:line 25
But i have serilogged configured and it gives an exception which does not hit the middle ware which is the real problem in here which is
An error occurred using the connection to database 'test-db-12-jan-2023' on server 'DESKTOP-xxx
The above error message is logged to the serilog but it never reaches the middleware and this is the exception i want to avoid. this is the problem here.

GetToastCollectionManager crash

I already have Toast Notifications working, but I need to create a collection for them.
Following the code example in : https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/toast-collections
I get a crash on the GetToastCollectionManager call.
System.Exception
HResult=0x80070490
Message=Element not found. (0x80070490)
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
This exception was originally thrown at this call stack:
WpfApp1.MainWindow.CreateToastCollection() in MainWindow.xaml.cs
I'm not sure if I'm missing something obvious , but I cannot find examples or tutorials on Toast Notifications.
Any Ideas ?
public async void CreateToastCollection()
{
ToastNotificationManagerForUser defaultManager = ToastNotificationManager.GetDefault();
ToastCollectionManager collectionManager = defaultManager.GetToastCollectionManager();
string displayName = "Is Potato";
string launchArg = "NavigateToPotato";
System.Uri iconURI = new System.Uri("ms-appx:///Assets/icon.png");
ToastCollection licensingManagerToastCollection = new ToastCollection(
"MyToastCollection",
displayName,
launchArg,
iconURI);
// Calls the platform to create the collection
await collectionManager.SaveToastCollectionAsync(licensingManagerToastCollection);
}

Web API system out of memory exception

I know there are a lot of questions regarding this issue. But I am unable to solve my problem.
API Flow
It accepts two parameters meter serial number and date time.
After the parameters are passed the API call is made
The API will search for the sent meter serial number in two databases.
After the record is fetched it should give the output.
Code
Below is my code
public HttpResponseMessage GetDetails(string msn, DateTime dt)
{
try
{
var prodDetails = mdcEntitites.tj_xhqd.Where(m => m.sjsj >= dt)
.Select(x => new { MSN = x.zdjh, PingDateTime = x.sjsj, PingValue = x.xhqd })
.ToList();
var mainDetails = kesc.tj_xhqd.Where(m => m.sjsj >= dt)
.Select(x => new { MSN = x.zdjh,PingDateTime= x.sjsj,PingValue = x.xhqd })
.ToList();
var res = prodDetails.Concat(mainDetails).ToList();
return Request.CreateResponse(HttpStatusCode.OK, new {details = res });
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
In above call, I am accepting a date time. When a meter is dispatched to field staff the date time is marked in the system, so the above date is that date time.
It will search all the records of that serial number after this date time.
Error
Using Postman when I try to run the API with current date time it gives me the following result
{
"details": [
{
"MSN": "002998002523",
"PingDateTime": "2018-06-21T08:38:12",
"PingValue": "26"
},
{
"MSN": "002998001286",
"PingDateTime": "2018-06-21T08:38:13",
"PingValue": "18"
},
.
.
.
.
.
]
}
But when I try to run the API with date time less than current date time it gives me below exception
Exception of type 'System.OutOfMemoryException' was thrown.
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.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.IO.MemoryStream.set_Capacity(Int32 value) +89
System.IO.MemoryStream.EnsureCapacity(Int32 value) +90
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +326
Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +62
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9746340
System.Web.HttpResponse.FilterOutput() +104
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +58
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +71
How can I get rid of this issue?
Any help would be highly appreciated.
As dlxeon points out, the PageInspector might be the cause of your exception. However you have a potential problem anyway: you are not limiting the number of search results that you are returning, and that might be an issue in the future when your database grows. You could do something like that:
Add an optional page parameter to your API call, and add something like .Skip((page-1)*PageSize).Take(PageSize) to your database query, right after the .Where. This is assuming that pages start at 1 and you have a PageSize constant defined.1
Include paging information in your response as needed by the client, e.g:
{
"pageSize": 10,
"currentPage": 1,
"details: "[
...
]
}
1In your case it will be a bit more complex since you are doing two database queries, but you get the idea.

Selfhosted Nancy: NullReferenceException occurred in Nancy.Authentication.Forms.dll When correct user/password is entered

I am trying to create a form auth with self hosted Nancy.To make it simple there is no db for user data, it is stored in a List.We have two users:
U: admin P: passowrd
U: user P: password
I am using:
Nancy.1.4.4
Nancy.Authentication.Forms.1.4.1
Nancy.Hosting.Self.1.4.1
Nancy.Viewengines.Razor.1.4.3
Microsoft.AspNet.Razor.2.0.30506.0
My login module:
Get["/login"] = x =>
{
Model.login = new LoginModel() { Error = this.Request.Query.error.HasValue, ReturnUrl = this.Request.Url };
return View["login", Model];
};
Post["/login"] = x =>
{
var userGuid = MyUserMapper.ValidateUser((string) this.Request.Form.Username,
(string) this.Request.Form.Password);
if (userGuid == null)
{
return Context.GetRedirect("~/login?error=true&username=" +
(string) this.Request.Form.Username);
}
DateTime? expiry = null;
if (this.Request.Form.RememberMe.HasValue)
{
expiry = DateTime.Now.AddDays(7);
}
return this.LoginAndRedirect(userGuid.Value, expiry);
When a wrong user/password is entered everything is ok.When a correct user/password is entered NullReferenceException occurs at LoginAndRedirect:
return this.LoginAndRedirect(userGuid.Value, expiry);
An exception of type 'System.NullReferenceException' occurred in Nancy.Authentication.Forms.dll but was not handled in user code
Call Stack:
> NancyLinuxTest.exe!NancyLinuxTest.Models.MainModule..ctor.AnonymousMethod__16(dynamic x) Line 49 C#
Stack Trace:
Nancy.Authentication.Forms.FormsAuthentication.EncryptAndSignCookie(String cookieValue, FormsAuthenticationConfiguration configuration)\r\n at Nancy.Authentication.Forms.FormsAuthentication.BuildCookie(Guid userIdentifier, Nullable`1 cookieExpiry, FormsAuthenticationConfiguration configuration)\r\n at Nancy.Authentication.Forms.FormsAuthentication.UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, Nullable`1 cookieExpiry, String fallbackRedirectUrl)\r\n at Nancy.Authentication.Forms.ModuleExtensions.LoginAndRedirect(INancyModule module, Guid userIdentifier, Nullable`1 cookieExpiry, String fallbackRedirectUrl)\r\n at NancyLinuxTest.Models.MainModule.<.ctor>b__16(Object x) in d:\\prototype-prices\\for_delete\\#proto\\NancyFormAuthTest\\NancyFormAuthTest\\Modules\\MainModule.cs:line 55\r\n at CallSite.Target(Closure , CallSite , Func`2 , Object )\r\n at Nancy.Routing.Route.<>c__DisplayClass4.<Wrap>b__3(Object parameters, CancellationToken context)
userGuid.Value is not null.
Full source here
Found my problem, I was calling the wrong Bootstrapper :).
private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
{
var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue);
var hmacBytes = GenerateHmac(encryptedCookie, configuration);
var hmacString = Convert.ToBase64String(hmacBytes);
return String.Format("{1}{0}", encryptedCookie, hmacString);
}
The only line that can trigger NRE (in v.1.4.1) is the configuration deference. If you look in the code this is set by calling Enable. Start you investigation there, see when Enable is called, check what configuration gets passed in.
Disclaimer: I have no idea what Nancy is, nor do I care. This is basic code debugging you should be doing. Is all open source. Just step through it.

What causes a System.Runtime.InteropServices.COMException at BackgroundAudioPlayer.get_Position()?

Sometimes I'm getting an exception when trying to get the position of the BackgroundAudioPlayer.Instance. It's happening very rarely, but I've been able to get a StackTrace. The strange thing is, this code is executed every second while playing a track. What could be the cause of this error?
I'm getting this StackTrace.
System.SystemException: HRESULT = 0xC00D36C4 ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0xC00D36C4 at
Microsoft.Phone.BackgroundAudio.Interop.IAudioPlaybackManager.get_CurrentPosition() at
Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.get_Position() --- End of inner exception stack trace --- at
Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.get_Position() at
MC.PodCast.Common.ViewModel.PlayerViewModel.UpdateTrackPosition() at
MC.PodCast.Common.ViewModel.PlayerViewModel.ReactToBackgroundAudioPlayer() at
MC.PodCast.Common.ViewModel.PlayerViewModel.Initialize() at
MC.PodCast.Common.ViewModel.PlayerViewModel.<<get_InitializeCommand>b__5>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
Of course the code I'm using is just plain simple.
public void UpdateTrackPosition()
{
if (_backgroundAudioPlayer != null && _backgroundAudioPlayer.Track != null)
{
Position = _backgroundAudioPlayer.Position;
}
else
{
Position = null;
}
}
That code is linked to MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED but I'm guessing that you do have sound.
I have found that the BackgroundAudioPlyer can be very weird. I wrap most of my calls with a "Safe" extension method.
Example
public static PlayState PlayerStateSafe(this BackgroundAudioPlayer source)
{
PlayState state;
try
{
state = source.PlayerState;
}
catch (InvalidOperationException)
{
state = PlayState.Unknown;
}
return state;
}

Categories

Resources