how do I parse the http response object coming from asmx - asp.net

$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.

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"
};
}
}

SaveChangesAsync() getting stuck

I have problem and i think its a deadlock and i cant resolve the problem. I know there simular problem discuse but i need help. When i try to saveChange on productReposotory it stuck and dont execute the other code.
Here is my controller:
public IActionResult All(string type)
{
var viewModel = new AllFireplaceViewModel
{
Fireplaces =
this.fireplaceService.GetAllFireplaceAsync<IndexFireplaceViewModel>(type).Where(x => x.TypeOfChamber == type),
};
return this.View(viewModel);
}
My IFireplaceService:
using System.Collections.Generic;
using System.Threading.Tasks;
using KaminiCenter.Web.ViewModels.Fireplace;
public interface IFireplaceService
{
Task AddFireplaceAsync(FireplaceInputModel fireplaceInputModel);
IEnumerable<T> GetAllFireplaceAsync<T>(string type);
T GetByName<T>(string name);
}
And this is my implementation of the interface:
public async Task AddFireplaceAsync(FireplaceInputModel model)
{
var typeOfChamber = Enum.Parse<TypeOfChamber>(model.TypeOfChamber);
if (model.Power == null ||
model.Size == null ||
model.Chimney == null)
{
throw new ArgumentNullException("Cannot safe null or whitespace values!");
}
await this.productService.AddProductAsync(model.Name, model.Group);
var productId = this.productService.GetIdByNameAndGroup(model.Name, model.Group);
var groupId = this.groupService.FindByGroupName(model.Group).Id;
var fireplace = new Fireplace_chamber
{
Id = Guid.NewGuid().ToString(),
Power = model.Power,
Size = model.Size,
Chimney = model.Chimney,
Price = model.Price,
Description = model.Description,
ImagePath = model.ImagePath.ToString(),
TypeOfChamber = typeOfChamber,
ProductId = productId,
GroupId = groupId,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};
await this.fireplaceRepository.AddAsync(fireplace);
await this.fireplaceRepository.SaveChangesAsync();
}
This is the productService.AddProductAsync:
public async Task AddProductAsync(string name, string groupName)
{
var group = this.groupService.FindByGroupName(groupName);
if (group == null)
{
await this.groupService.CreateAsync(groupName);
}
var product = new Product
{
// TO Check for Id Initializesion
Id = Guid.NewGuid().ToString(),
Name = name,
GroupId = group.Id,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};
await this.productRepository.AddAsync(product);
await this.productRepository.SaveChangesAsync();
}
And my Add Action
public IActionResult Add()
{
var createFireplaceInputModel = new FireplaceInputModel();
return this.View(createFireplaceInputModel);
}

ASP.NET Cloudinary getting response

I have little problem with using Cloudinary, I can upload the images it works fine but I guess i cant get any response from Cloudinary. Suggestion? about required parameters
Handler
public async Task<Photo> Handle(Command request, CancellationToken cancellationToken)
{
var photoUploadResult = _photoAccessor.AddPhoto(request.File);
var photo = new Photo
{
Url = photoUploadResult.Url,
Id = photoUploadResult.PublicId
};
var success = await _context.SaveChangesAsync() > 0;
if (success) return photo;
throw new Exception("Problem saving changes");
}
Accessor
public PhotoUploadResult AddPhoto(IFormFile file)
{
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams
{
File = new FileDescription(file.FileName, stream)
};
uploadResult = _cloudinary.Upload(uploadParams);
}
}
if (uploadResult.Error != null)
throw new Exception(uploadResult.Error.Message);
return new PhotoUploadResult
{
PublicId = uploadResult.PublicId,
Url = uploadResult.SecureUri.AbsoluteUri
};
}
What do you get in response? Can you try:
string cloud_name = "<Cloud Name>";
string ApiKey = "<Api-Key>";
string ApiSecret = "<Api-Secret>";
Account account = new Account(cloud_name,ApiKey,ApiSecret);
Cloudinary cloudinary = new Cloudinary(account);
cloudinary.Api.Timeout = int.MaxValue;
var ImguploadParams = new ImageUploadParams()
{
File = new FileDescription(#"http://res.cloudinary.com/demo/image/upload/couple.jpg"),
PublicId = "sample",
Invalidate = true,
Overwrite = true
};
var ImguploadResult = cloudinary.Upload(ImguploadParams);
Console.WriteLine(ImguploadResult.SecureUri);

Use stored procedure for search method

I started with ASP.Net Core 2.0, I'm trying to rewrite a method GetAll by search use stored procedure. Here is method search:
public async Task<List<DepartmentTypeDto>> SearchDepartmentType()
{
EnsureConnectionOpen();
using (var command = CreateCommand("CM_DEPT_GROUP_Search", CommandType.StoredProcedure))
{
using (var dataReader = await command.ExecuteReaderAsync())
{
List<DepartmentTypeDto> result = new List<DepartmentTypeDto>();
while (dataReader.Read())
{
DepartmentTypeDto departmentTypeDto = new DepartmentTypeDto
{
GROUP_ID = dataReader["GROUP_ID"].ToString(),
GROUP_CODE = dataReader["GROUP_CODE"].ToString(),
GROUP_NAME = dataReader["GROUP_NAME"].ToString(),
NOTES = dataReader["NOTES"].ToString(),
RECORD_STATUS = dataReader["RECORD_STATUS"].ToString(),
MAKER_ID = dataReader["MAKER_ID"].ToString(),
CREATE_DT = Convert.ToDateTime(dataReader["CREATE_DT"]),
AUTH_STATUS = dataReader["AUTH_STATUS"].ToString(),
CHECKER_ID = dataReader["CHECKER_ID"].ToString(),
APPROVE_DT = Convert.ToDateTime(dataReader["APPROVE_DT"]),
AUTH_STATUS_NAME = dataReader["AUTH_STATUS_NAME"].ToString(),
RECORD_STATUS_NAME = dataReader["RECORD_STATUS_NAME"].ToString()
};
}
return result;
}
}
}
Here is the service:
public async Task<PagedResultDto<GetDepartmentTypeForView>> GetAll(GetAllDepartmentTypesInput input)
{
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType();
var query = (from o in filteredDepartmentTypes
select new GetDepartmentTypeForView() { DepartmentType = ObjectMapper.Map<DepartmentTypeDto>(o) });
var totalCount = await query.CountAsync();
var departmentTypes = await query
.OrderBy(input.Sorting ?? "departmentType.id asc")
.PageBy(input)
.ToListAsync();
return new PagedResultDto<GetDepartmentTypeForView>(totalCount, departmentTypes);
}
But I get an error:
Task<List<DepartmentTypeDto>> does not contain a definition for Select
Does anyone know what I should do? I work on Asp.Net Zero.
I changed my search method
public IQueryable<DepartmentTypeView> SearchDepartmentType(GetAllDepartmentTypesInput input, int top)
{
try
{
var GROUP_FILTER = input.Filter;
var GROUP_CODE = input.GROUP_CODEFilter;
var GROUP_NAME = input.GROUP_NAMEFilter;
var AUTH_STATUS = input.AUTH_STATUSFilter;
var result = Context.Query<DepartmentTypeView>().FromSql($"EXEC CM_DEPT_GROUP_Search #p_GROUP_FILTER = {GROUP_FILTER}, #p_GROUP_CODE={GROUP_CODE}, #p_GROUP_NAME={GROUP_NAME}, #p_AUTH_STATUS={AUTH_STATUS}, #p_TOP={top}");
return result;
}
catch
{
return null;
}
}
and in the service, I call that function
var filteredDepartmentTypes = _departmentTypeRepository.SearchDepartmentType(input,100);
I also create new class to keep the result and don't forget to map that class with DTO class
configuration.CreateMap<DepartmentTypeView, DepartmentTypeDto>();
It works for me.

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

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 };`

Resources