Why am I getting Http error 500 when I return too many rows as json in my ajax call? - asp.net

Here is my code:
var context = _contextFactory.Create(GetClient());
var r = from p in context.MyTable.ToList()
select p;
int tot;
var firstPageData = PagedResult(r, 0, 200000, rows => new { rows.Id }, true, out tot);
return Json(new { result = "ok", rows = firstPageData }, JsonRequestBehavior.AllowGet);
The first and second parameter to PagedResult() (0 and 200000) are the pagenumber and number of rows to return. This is returning http error 500.
But when I change the 2nd parameter to PagedResult() to return only 20 rows, it's working fine. Like this:
var context = _contextFactory.Create(GetClient());
var r = from p in context.MyTable.ToList()
select p;
int tot;
var firstPageData = PagedResult(r, 0, 20, rows => new { rows.Id }, true, out tot);
return Json(new { result = "ok", rows = firstPageData }, JsonRequestBehavior.AllowGet);
Is it I am getting this error because I am returning too many rows that http can't handle? Or are there configurations I need to make so I can return these too many rows?
Thanks,

use a custom JsonResult Class for ASP.Net MVC to avoid MaxJsonLength Exceeded Exception.
public class LargeJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public LargeJsonResult()
{
MaxJsonLength = 1024000;
RecursionLimit = 100;
}
public int MaxJsonLength { get; set; }
public int RecursionLimit { get; set; }
public override void ExecuteResult( ControllerContext context )
{
if( context == null )
{
throw new ArgumentNullException( "context" );
}
if( JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals( context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase ) )
{
throw new InvalidOperationException( JsonRequest_GetNotAllowed );
}
HttpResponseBase response = context.HttpContext.Response;
if( !String.IsNullOrEmpty( ContentType ) )
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if( ContentEncoding != null )
{
response.ContentEncoding = ContentEncoding;
}
if( Data != null )
{
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
response.Write( serializer.Serialize( Data ) );
}
}
}
and use it as
return new LargeJsonResult { Data = Your Data, JsonRequestBehavior = `System.Web.Mvc.JsonRequestBehavior.AllowGet };`

Related

Why Restsharp request object won't be renewed in every call

This is my RestClientService :
public class RestClientService : IRestClientService
{
protected readonly RestClient _restClient;
protected readonly RestRequest _restRequest;
public RestClientService()
{
_restClient = new RestClient();
_restRequest = new RestRequest();
}
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
_restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
_restRequest.Method = Method.Post;
_restRequest.RequestFormat = DataFormat.Json;
_restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await _restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}
I have a list of comments and list of products that I iterate over them and call SendComment method from RestClientService class. The problem is in first time SendComment method called _restRequest object will be get JsonBody and everything is okay but next time this method calls in loop _restRequest object has old data and won't be renewed.
In DI Container I added (Transient) RestClientService
builder.Services.AddTransient<IRestClientService,RestClientService>();
Here is where I used SendComment method in another service.
public async Task<MessageDTO> CreateSendCommentJob(SendCommentConfiguration config)
{
var updatedConfig = await _sendCommentConfigurationRepository.Get(config.Id);
var ConfigDetails = JsonConvert.DeserializeObject<SendCommentConfigurationDetailsDTO>(updatedConfig.Configuration);
var mappedWebsite = _mapper.Map<Websites>(ConfigDetails.WebsiteInfo);
if (ConfigDetails.CommentType == "blog")
{
var comments = await _uCommentService.GetCommentsByGroupId(ConfigDetails.CommentGroupId);
var commentCount = 0;
for (int postCount = 0; postCount < ConfigDetails.ProductPerSendCount; postCount++)
{
var postId = ConfigDetails.Ids[postCount];
while (commentCount < ConfigDetails.CommentsPerProductCount)
{
var random = new Random();
var index = random.Next(comments.Count);
var result = await _restClientService.SendComment(mappedWebsite, comments[index], postId);
if (result.Status == "Created")
{
Console.WriteLine($"Comment Index ({index}) at Id ({postId}) submited successfuly...");
commentCount++;
}
else
{
Console.WriteLine($"{postId} - {result.Status} - {result.Message}");
}
}
ConfigDetails.Ids.Remove(postId);
commentCount = 0;
}
}
var newConfig = new SendCommentConfiguration
{
Id = config.Id,
Configuration = JsonConvert.SerializeObject(ConfigDetails)
};
await _sendCommentConfigurationRepository.Edit(newConfig);
return new MessageDTO
{
Status = "200",
Message = "Comments Successfuly Sent "
};
}
_restClientService.SendComment is called in a loop on the same service instance. As the request instance is a field of the service instance, the same request instance is reused for each call.
As each apple performs a distinct request, each request must use a distinct instance of RestRequest, like :
public class RestClientService : IRestClientService
{
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
//Each call, new instances
var restClient = new RestClient();
var restRequest = new RestRequest();
restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
restRequest.Method = Method.Post;
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}

Insert data in Value Object Table

Inserting Data By POSTMAN, but some error occurred.
My Code is given below:
public async Task<BusinessProfile> Save(string ID,bool Status,string Logo,string TaxNumber,string StateRegisterNumber,string StreetName,string Number
,string Complement,string PostalCode,string Neighborhood,string City,string State,string AreaCode,string Department
,string PhoneNo,string Type,string Website,string EDepartment,string EmailAddress)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = ID, Status = Status, Logo = Logo, TaxNumber = TaxNumber, StateRegisterNumber = StateRegisterNumber, Website = Website };
businessProfile.AssignAddress(new Address(StreetName, Number, Complement, PostalCode, Neighborhood, City, State));
businessProfile.AssignPhones(new Phones(Convert.ToString(EnumPhoneNumber), AreaCode, PhoneNo, Department));
businessProfile.AssignEmail(new Emails(EmailAddress, EDepartment));
//_db.Add(businessProfile);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
// _db.SaveChanges();
//await _db.BusinessProfiles.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch(Exception ex)
{
throw ex;
}
}
Output (Error:):
An unhandled exception occurred while processing the request.
InvalidOperationException: The entity of type BusinessProfile is sharing the table BusinessProfiles with entities of type Address, but there is no entity of this type with the same key value that has been marked as Added. Consider using DbContextOptionsBuilder.EnableSensitiveDataLogging to see the key values.
public async Task Save(BusinessProfile bp)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = bp.ID, IsActive = bp.IsActive, Logo = bp.Logo, TaxNumber = bp.TaxNumber, StateRegisterNumber = bp.StateRegisterNumber, Website = bp.Website };
businessProfile.Address = new Address(bp.Address.StreetName, bp.Address.Number, bp.Address.Complement, bp.Address.PostalCode, bp.Address.Neighborhood, bp.Address.City, bp.Address.State);
businessProfile.Phones = new Phones(Convert.ToString(EnumPhoneNumber), bp.Phones.AreaCode, bp.Phones.PhoneNumber, bp.Phones.Department);
businessProfile.Emails = new Emails(bp.Emails.EmailAddress, bp.Emails.Department);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch (Exception ex)
{
throw ex;
}
}

how do I parse the http response object coming from asmx

$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({empid: $scope.eid});
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = response.data;
console.log($scope.Employee.fname);
console.log($scope.Employee);
var mydata = jQuery.parseJSON(JSON.stringify(response.data));
console.log(mydata);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
List<Employee> elist = new List<Employee>();
elist.Add(employee);
return new JavaScriptSerializer().Serialize(elist);
}
This is I got from the response
Object
d:"[{"empId":103,"fname":"sujith","city":"trichy","mobile":"56456456","country":"India"}]"
proto : Object
how do I parse angular js object. I want to access like this: $scop.Employee.empId,$scope.Employee.fname
Thanks & Regards
arun
Are you sure that the object you are receiving is starting and ending with " " (double quotes)
Change the following line
$scope.Employee = response.data;
with
$scope.Employee = response.data.d[0];
Try this. This should work :
$scope.Edit = function (id) { console.log("edit id : " + id); $scope.Employee = {}; $scope.eid = id; var data = JSON.stringify({empid: $scope.eid}); var url = "/services/EmployeeService.asmx/EditEmployee"; $http.post(url, data).then(function (response) {
$scope.Employee = response.data.d[0];
console.log($scope.Employee.fname);
console.log($scope.Employee); }, function (response) {
console.log(response.status);
console.log(response.statusText); });
}
$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({ empid: $scope.eid });
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = JSON.parse( response.data.d);
console.log("empid: " + $scope.Employee.empId);
console.log("fname: " + $scope.Employee.fname);
console.log("city: " + $scope.Employee.city);
console.log("country: " + $scope.Employee.country);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
enter code here
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
return new JavaScriptSerializer().Serialize(employee);
}
enter code here
thank you Vikas Thakur, Abhijeet Jaiswal, it helped me to solved it, now it is working, what mistake is in asmx webservice webmethod I should return Employee object as string, previously I wrongly add it to the list and return the list. the webmethod return type is string so it is not parsing. now it is parsing. thank you both of you helped me.

selec2 dropdown not working while running web-application in IIS(windows 7)

Im completed my asp.net web-application by using VisulaStudio2013 in which all controls are working fine. After that i copied published files in IIS-7 pc(OS:Windows 7) then select2 dropdown not loading its data's properly.
please chek my codes given below:-
searchType = "Name";
$("#CustomerId").select2({
placeholder: 'Search options',
minimumInputLength: 0,
ajax: {
url: "/ProductEnquiry/GetCustomerMobileNumbers",
dataType: 'json',
quietMillis: 250,
data: function (term, page, type) {
return {
q: term, //search term
page: page, // page number
type: searchType
};
},
results: function (data, page) {
alert(data);
alert(JSON.stringify(data));
data = JSON.parse(data);
var more = (page * 30) < data.total_count; // whether or not there are more results available
return { results: data.items, more: more };
}
}
});
In that alert box shows 'null' values..
public JsonResult GetCustomerMobileNumbers(string q, int page, string type)
{
try
{
HttpCookie _UserInfoCookies = Request.Cookies["UserInfo"];
string UserId = _UserInfoCookies["UserId"];
string BranchId = _UserInfoCookies["BranchId"];
var branchDetails = branchService.GetBranchDetailsByBranchId(Convert.ToInt32(BranchId));
var list = customerService.GetAllCustomerMobileNumbersBySearch(q, 30 * (page - 1), 30, Convert.ToInt32(branchDetails.CompanyId), type);
SelectDropDownViewModel dummy = new SelectDropDownViewModel()
{
id = 0,
text = "no data found",
};
IEnumerable<SelectDropDownViewModel> Data = new List<SelectDropDownViewModel>();
if (type == "Name")
{
Data = list.Select(c => new SelectDropDownViewModel { id = c.CustomerId, text = c.CustomerName }).AsEnumerable();
}
else if (type == "Mobile")
{
Data = list.Select(c => new SelectDropDownViewModel { id = c.CustomerId, text = c.Mobile }).AsEnumerable();
}
return Json(JsonConvert.SerializeObject(new { success = true, results = Data, items = Data, total_count = Data.Count() }), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ErrorLogs errorLog = new ErrorLogs() { Source = "ProductEnquiry", Message = ex.Message, InnerException = Convert.ToString(ex.InnerException), HelpLink = ex.HelpLink, TimeOccured = DateTime.UtcNow, StackTrace = ex.StackTrace };
errorLogService.AddItem(errorLog);
return null;
}
}
Im already installed .net frame work 4.0 & 4.5 in that pc for running IIS-local host.
Please help me resolve this issue;

How to implement ordering in DataTables jqueryPlugin?

#RequestMapping(value = "/CustomerData", method = RequestMethod.GET)
public #ResponseBody String customerData(
HttpServletRequest request,HttpServletResponse response,Model model,
#RequestParam(value = "order",required = false, defaultValue = "ASC") String order,
#RequestParam(value = "orderBy",required = false, defaultValue = "customerId") String orderBy) throws IOException {
//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/10)+1;
//Fetch search parameter
String searchParameter = request.getParameter("sSearch");
String orderByVal = request.getParameter("iSortCol_0");
String orderVal = request.getParameter("sSortDir_0");
if(!Employee.isEmptyString(orderByVal))
{
if(!Employee.isEmptyString(orderVal))
{
order = orderVal;
}
else
{
order = "desc";
}
if(orderByVal.equalsIgnoreCase("0"))
orderBy = "customerId";
else if(orderByVal.equalsIgnoreCase("1"))
orderBy = "customerName";
else if(orderByVal.equalsIgnoreCase("2"))
orderBy = "phoneNo";
else if(orderByVal.equalsIgnoreCase("3"))
orderBy = "area";
else if(orderByVal.equalsIgnoreCase("4"))
orderBy = "city";
else
{
orderBy = "customerId";
order = "desc";
}
}
//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));
Integer record = (pageNumber-1)*pageDisplayLength;
//Create page list data
List<Customer> customerList = customerService.getCustomerList(record,pageDisplayLength);
customerList = getCustomerListBasedOnSearchParameter(searchParameter, customerList);
customerList = getSortedCustomer(customerList, order,orderBy);
response.setContentType("application/Json");
Integer count= null;
if(customerList != null && customerList.size() > 0){
count=customerList.size();
}else{
count=customerService.count();
customerList = customerService.getCustomerList(record,pageDisplayLength);
}
model.addAttribute("order", order);
model.addAttribute("orderBy", orderBy);
CustomerJsonObject customerJson=new CustomerJsonObject();
//Set Total display record
customerJson.setiTotalDisplayRecords(count);
//Set Total record
customerJson.setiTotalRecords(count);
customerJson.setAaData(customerList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(customerJson);
return json;
}
//The above code is my controller code.
But it is not performing in my project.
Can you please say me the changes in my controller if any wrong.I have tried doing it but its not possible my me.Can i know the solution for it .
//I have implemented in the below way but i dont know how to send these values to jsp through json object.
public List<Customer> getSortedCustomer(List<Customer> customerList,
final String order, final String orderBy) {
final boolean desc = order.equals("DESC");
final int sortDirection=desc ? -1:1;
Collections.sort(customerList, new Comparator<Customer>() {
#Override
public int compare(Customer c1, Customer c2) {
if (orderBy.equals("customerId")) {
return c1.getCustomerId().compareTo(c2.getCustomerId()) * sortDirection;
} else if (orderBy.equals("customerName")) {
return c1.getCustomerName().compareTo(c2.getCustomerName()) * sortDirection;
} else if (orderBy.equals("phoneNo")) {
return c1.getPhoneNo().compareTo(c2.getPhoneNo()) * sortDirection;
} else if (orderBy.equals("email_Id")) {
return c1.getEmail_Id().compareTo(c2.getEmail_Id()) * sortDirection;
} else if (orderBy.equals("area")) {
return c1.getArea().compareTo(c2.getArea()) * sortDirection;
}else if (orderBy.equals("city")) {
return c1.getCity().compareTo(c2.getCity()) * sortDirection;
}
return 0;
}
});
return customerList;
}

Resources