jqGrid weird exception upon calling databind - c#

I have been using the latest MVC dll from Trirand and I am using the JqGrid.Databind() function to get data from the controller. Here is the code that I have written:
var listToBind = gridDataTable.Cast<IDictionary>().ToDataSource();
gridModel.ResourcePlanningGrid.DataSource = null;
JsonResult returnObject;
try
{
returnObject = gridModel.ResourcePlanningGrid.DataBind(listToBind.AsQueryable());
}
catch(Exception ex)
{
//Unknown Exception: delete the current session that holds the grid and
//restart the whole page
this.Session["ResourcePlanningGrid"] = null;
return FilterData();
}
Intermittently it throws an exception on the .DataBind() call that says that it parses a string that is not a valid Boolean. Has anyone encountered this before? Is there an existing fix for this? or should I find another way to pass values from a list to bind?
Here is the the exception stack trace.
at System.Boolean.Parse(String value)
at System.Convert.ToBoolean(String value)
at Trirand.Web.Mvc.JQGrid.get_AjaxCallBackMode()
at Trirand.Web.Mvc.JQGrid.DataBind()
at Trirand.Web.Mvc.JQGrid.DataBind(Object dataSource)
at Cormant.OrangeReports.Web.Controllers.ResourcePlanningController.FilterData(Nullable`1 customerID, Nullable`1 projectID, Nullable`1 startDate, Nullable`1 endDate, String employeeID) in e:\Projects\OrangeReports\Cormant.OrangeReports.Web\Controllers\ResourcePlanningController.cs:line 175
Thanks in Advance

Related

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.

Value does not fall within the expected range exception when redirecting to a different URL

I am trying to redirect to a different URL in case that the original URL is not found, but there is a mapping to a different URL available and I need to redirect to.
public class RedirectRequestHandler:ExecuteRequest
{
private string _host { get; set; }
private HttpContext _context { get; set; }
public RedirectRequestHandler()
{
_context = HttpContext.Current;
_host = _context.Request.Url.Host;
}
protected override void RedirectOnItemNotFound(string url)
{
Database siteCoreContext = Context.Database;
try
{
Uri redirectedUrl;
if (GetRedirectedUrl($"{_host}{_context.Request.RawUrl}",out redirectedUrl))
{
var uri = redirectedUrl.AbsoluteUri;
_context.Response.RedirectPermanent(uri);
}
}
catch (Exception exception)
{
base.RedirectOnItemNotFound(url);
}
_context.Response.End();
}
}
The code throws an exception:
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Web.Hosting.IIS7WorkerRequest.SendStatus(Int32 statusCode, Int32 subStatusCode, String statusDescription)
at System.Web.HttpResponse.UpdateNativeResponse(Boolean sendHeaders)
at System.Web.HttpResponse.Flush(Boolean finalFlush, Boolean async)
at System.Web.HttpResponse.End()
at System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)
at WolfGreenfield.Classes.RedirectRequestHandler.RedirectOnItemNotFound(String url) in C:\Code\wgf-website\src\website\classes\RedirectRequestHandler.cs:line 31
and the message is that:
Value does not fall within the expected range
I am not sure how I can resolve this? I simply want to redirect to a different page and send a 301 HTTP status code back to the browser.
The problem is that I used the same context (_context) throughout my code. Also, to redirect permanently, I used the following code:
var context = HttpContext.Current;
Item item = GetItemFromUrl(redirectedUrl);
context.Response.RedirectPermanent(LinkManager.GetItemUrl(item),true);
If you are also facing the above issue and the suggested solution doesn't work for you and your Sitecore installation is still showing above error, I would suggest checking the residual files that have been created by that failed Sitecore installation and try to restart your website there in the IIS, if you are able to see above index error, then try with another instance name probably with another identifier.
In my machine, it was getting created like "sc901.dev..xconnect" and "sc901.dev..sc.local"
I just edited my install script to change the instance name.

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.

C# error "Not all code paths return a value"

I translated this part of the code from vb to c# and giving me this error message. "Not all code paths return a value". What is the problem? Thanks in advance.
public DataSet LoadSearchDataSet(string strConnection, string strSQL)
{
//The purpose of this function is to create and populate a data
//set based on a SQL statement passed in to the function.
try
{
DataSet dsData = new DataSet();
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
//return the data set to the calling procedure
return dsData;
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
}
You are missing the return value in the case the code throws an exception.
public DataSet LoadSearchDataSet(string strConnection, string strSQL)
{
//The purpose of this function is to create and populate a data
//set based on a SQL statement passed in to the function.
DataSet dsData = new DataSet();
try
{
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
//return the data set to the calling procedure
return dsData;
}
If an exception occurs in your try block before the return statement, the catch is executed and that does not return anything, because you did not tell it to.
You can do one of these:
Return a value from the catch block. Do this only if it makes sense and you have a sensible value you can return. Be aware that returning null is a usual source of bugs and there are patterns out there to avoid just that.
Re-throw the exception that occurred, if you cannot do anything at this point about it (and return an object that makes sense). You can do this by adding a line that says: throw;
Throw a different error - You can package the original exception in a new one, providing extra details about the context, if necessary.
You need to add a return statement after your catch clause!
In case of an exception inside your try catch clause, you won't return a value. And that's exactly what your error is indicating.
This is a common error message in functions, as functions are designed to return some value. If your code passes the catch section, it will reach the end of the function without returning anything, thats where you need to return the value.
rewrite like this:
DataSet dsData = null;
try
{
//call the table in the local dataset "results" since the values
//may be coming from multiple tables.
string strTableName = "Results";
bool blnRunStoredProc = false;
dsData = PopulateDataSetTable(strConnection, strTableName, strSQL, blnRunStoredProc, dsData);
WriteSampleDataToOutputWindow(dsData);
}
catch
{
//error handling goes here
UnhandledExceptionHandler();
}
//return the data set to the calling procedure
return dsData;
You can resolve this issue by :
change the function return to VOID (if you does not return something)
give return keyword with variable name before end function
This is because in the case of any exception occurs,the exception will thrown to the catch, in that case the code will not return any value. so you have to return some value from the catch to avoid this issue
Replace the catch with this:
catch
{
//error handling goes here
UnhandledExceptionHandler();
return new DataSet();
}
It is must to return proper value in any case. so try to maintain try catch block with return value or outside of try/catch block if nothing to return in try / catch block.

ASP.Net Code block not returning data

I have a code block that does not return the expected data values.
protected void Page_Load(object sender, EventArgs e)
{
corpEmployee.Employee editEmp = new corpEmployee.Employee();
editEmp.EmployeeID = PatientCustomerID.Value;
corpCustomerMgr.GetEmployeeRecord(editEmp);
tboxFirstName.Text = editEmp.EmpFirstName.ToString();
tboxLastName.Text = editEmp.EmpLastName.ToString();
tboxCity.Text = editEmp.EmpCity.ToString();
tboxAddress.Text = editEmp.EmpAddrLine1.ToString();
}
public static void GetEmployeeRecord(corpEmployee.Employee QueryData)
{
try
{
List<corpEmployee.Employee> empRecord = new List<corpEmployee.Employee>();
corpCustomerDAL.GetEmployeeData(empRecord, QueryData);
}
catch (Exception ex)
{
LogAppError(ex.ToString());
}
}
When corpCustomerDAL.GetEmployeeData(empRecord, QueryData); is executed, empRecord is returned with the Employee object with correct property values. However, when the code comes back to corpCustomerMgr.GetEmployeeRecord(editEmp); the employee object has null values.
How can I get the Employee object values back to the Page_Load routine?
You could either return the object back in the GetEmployeeRecord static method or you could include ref in front of your arguments so that you are passing the employee in as a reference instead of copying the variable.
I would recommend returning your data back vs using ref as your method name seems misleading, among other reasons.
Based on your comments, it looks like you are populating empRecord with the employee data you require. The simplest option is to return the populated record from GetEmployeeRecord:
public static corpEmployee.Employee GetEmployeeRecord(corpEmployee queryData)
{
List<corpEmployee.Employee> empRecord = new List<corpEmployee.Employee>();
corpCustomerDAL.GetEmployeeData(empRecord, QueryData);
return empRecord.Count == 0 ? null : empRecord[0]; //or empRecord.FirstOrDefault()
}
You should then change the start of your Page_Load handler to:
corpEmployee.Employee queryEmp = new corpEmployee.Employee();
queryEmp.EmployeeID = PatientCustomerID.Value;
corpeEmployee.Employee editEmp = corpCustomerMgr.GetEmployeeRecord(queryEmp);
Two immediate thoughts occur:
Your exception handling needs work. You shouldn't be catching Exception, and you shouldn't be silently swallowing exceptions at all. It could well be that an exception is being thrown, and that's why you're not getting the data.
You've got a Get*** method - that should be returning data. It appears you're expecting the results to be put into an object... that's a confusing way of getting data out of a method. It would be clearer if your method signature were something like:
public static Employee GetEmployeeRecord(string employeeId)
Most likely what's happening is that your employee object that you're passing in is being copied, and is destroyed when the function terminates.
To better illustrate, I've added some comments:
public static void GetEmployeeRecord(corpEmployee.Employee QueryData)
{
//QueryData is a newly created Employee here, and is NOT the same one that was passed in.
try
{
List<corpEmployee.Employee> empRecord = new List<corpEmployee.Employee>();
corpCustomerDAL.GetEmployeeData(empRecord, QueryData);//
//QueryData now contains the data you want your original object to contain
}
catch (Exception ex)
{
LogAppError(ex.ToString());
}
} //when this function terminates, QueryData ceases to exist.
In order to fix it, pass the employee by reference (use the ref keyword) instead of passing it by value, which is what you're doing right now.

Categories

Resources