"System.Xml.XmlAttribute cannot be used as: 'xml element'." while running my asmx service - asp.net

I am trying to create a small asmx service with a method which will return some dummy data. I get the following error when I run the service:
"System.InvalidOperationException: System.Xml.XmlAttribute cannot be used as: 'xml element'."
My web method is as follows:
[WebMethod]
public SubmitCaseRequestResponse1 SubmitCaseRequest(SubmitCaseRequestRequest1 request)
{
var response = new SubmitCaseRequestResponse1
{
ResponseID = "456325898",
Success = true,
ValidationErrors = null
};
return response;
}
My SubmitCaseRequestResponse1 class:
public class SubmitCaseRequestResponse1
{
public string ResponseId { get; set; }
public bool Success { get; set; }
public ValidationError[] ValidationErrors { get; set; }
}
and the request class is :
public class SubmitCaseRequestRequest1
{
public AuthHeader AuthHeader { get; set; }
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}

I was supposed to serialize the complex type SubmitCaseRequestRequest1 and SubmitCaseRequestResponse1 . Needed to add [XmlElement] for the complex types and [XmlAttribute] for simple types
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://tempuri.org/")]
[Serializable]
public class SubmitCaseRequestRequest1
{
[XmlElement]
public AuthHeader AuthHeader { get; set; }
[XmlElement]
public SubmitCaseRequestRequest PostCaseDateRequest { get; set; }
}
[Serializable]
public class SubmitCaseRequestRequest
{
[XmlElement]
public Guid? RequestId { get; set; }
[XmlAttribute]
public string LCICourtNumber { get; set; }
[XmlAttribute]
public string CaseNumber { get; set; }
[XmlAttribute]
public string DebtorLastName { get; set; }
[XmlAttribute]
public string DateType { get; set; }
}

Related

postman error in POST - the field is required

Someone can help me, I'm trying send a POST requisition. But I dont undertand why it is not working.
this is my model:
public partial class LineModel : IModel
{
public LineModel()
{
UsersNavigation = new HashSet<UserModel>();
LineUsersNavigation = new HashSet<LineUserModel>();
}
public long Id { get; set; }
public string ProfitCenter { get; set; }
public string LineName { get; set; }
public string Customer { get; set; }
public long PlantId { get; set; }
public long TeamId { get; set; }
public virtual TeamModel TeamNavigation { get; set; }
public virtual PlantModel PlantNavigation { get; set; }
public virtual ICollection<UserModel> UsersNavigation { get; set; }
public virtual ICollection<LineUserModel> LineUsersNavigation { get; set; }
}
}
This is my controller:
[HttpPost]
public async Task<ActionResult<UserModel>> SaveUserAsync(UserModel user)
{
await _dbContext.Users.AddAsync(user);
await _dbContext.SaveChangesAsync();
return Ok();
}
and this is the print of my POSTMAN

Automapper missing type map configuration or unsupported mapping error

I am using Auto mapper and I am getting this error, I am getting this error within AddAsync() method. Please help me out to solve this issue.
Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nDepartmentsViewModel -> Departments\r\nEmployeeAttendanceApp.ViewModels.DepartmentsViewModel -> EmployeeAttendanceApp.Models.StaffManagement.Departments
My class
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
cfg.CreateMap<Departments, DepartmentsViewModel>();
});
return config.CreateMapper();
}
}
public class DepartmentsViewModel
{
[Key]
public int DepartmentId { get; set; }
[DisplayName("اسم القسم/ الادارة")]
[Required(ErrorMessage = "الرجاء ادخال اسم القسم")]
public string DepartmentName { get; set; }
[DisplayName("اضافة ملاحظات القسم")]
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
[DisplayName("عدد الموظفيين")]
[Required(ErrorMessage = " الرحاء إدخال عدد موظفيين القسم")]
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffViewModel> RegisterStaffs { get; set; }
}
public partial class Departments
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffs> RegisterStaffs { get; set; }
}
**I am getting the error in this method**
public async Task<bool> AddAsync(DepartmentsViewModel departmentsView)
{
try
{
var department = mapper.Map<DepartmentsViewModel, Departments>(departmentsView);
await context.Departments.AddAsync(department);
await context.SaveChangesAsync();
return true;
}
catch(Exception ex)
{
logger.LogError(ex, ex.Message);
return false;
}
}
//here is startup file where I have registered the services
services.AddSingleton<IMapperConfig, MapperConfig>();
services.AddTransient<IDepartmentManager, DepartmentManager>();
I have resolved this issue by adding .ReverseMap() inside MapperConfig class
cfg.CreateMap<Departments, DepartmentsViewModel>().ReverseMap();
but still I can't understand why it didn't work previously with out it because I have seen various examples never using ReverseMap()

Parse Complex JSON to ASP.NET MVC 3 using jQuery

I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,

ASP.NET MVC5 custom json model binder with html content

I used the FromJsonAttribute (created by Steve Sanderson), it's quite great, but sadly it doesn't pay attention to the AllowHtml attribute. I have the following model:
public class HKNewsPaperViewModel
{
public int Id { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string RPublisher { get; set; }
public string REditor { get; set; }
public string Title { get; set; }
public bool IsDraft { get; set; }
public bool IsNew { get; set; }
public List<HKNewsItemViewModel> NewsItems { get; set; }
public HKNewsPaperViewModel()
{
NewsItems = new List<HKNewsItemViewModel>();
}
}
public class HKNewsItemViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Link { get; set; }
[AllowHtml]
public string Body { get; set; }
}
In my controller I receive data this way:
[HttpPost]
public ActionResult New([FromJson] HKNewsPaperViewModel model)
{
return View();
}
FromJson attribute looks like this:
public class FromJsonAttribute : CustomModelBinderAttribute
{
private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
}
My problem is that I can't pass html content where the AllowHtml attribute is there. Thanks a lot!

property is null when using xml serialization in webapi

I'm trying to send the below xml
<dataset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.uisol.com/model">
<extAlert SendFrom="SendFrom" Target="Target" OID="0" UrgentFlag="0" />
</dataset>
as a post to a webapi request
HttpResponseMessage Post([FromBody]SendNotificationRequest dataset)
with the classes defined as below
[XmlRoot(Namespace = "http://www.uisol.com/model",
ElementName = "dataset",
DataType = "string",
IsNullable = true)]
public class SendNotificationRequest
{
[XmlElement(
ElementName = "extAlert",
Namespace = "http://www.uisol.com/model")]
public DRMSAlertRequest ExtAlert { get; set; }
}
}
and
public class DRMSAlertRequest : IDRMSAlert
{
[XmlAttribute]
public string SendFrom { get; set; }
[XmlAttribute]
public string Target { get; set; }
[XmlAttribute]
public string SendTo { get; set; }
[XmlAttribute]
public string BlindTo { get; set; }
[XmlAttribute]
public string ReplyTo { get; set; }
[XmlAttribute]
public string FailureTo { get; set; }
[XmlAttribute]
public int OID { get; set; }
[XmlAttribute]
public string Subject { get; set; }
[XmlAttribute]
public string Message { get; set; }
[XmlAttribute]
public char UrgentFlag { get; set; }
}
i have also made the xmlmedia formatter as below
var formatter = new XmlMediaTypeFormatter {UseXmlSerializer = true};
config.Formatters.Add(formatter);
var xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xmlFormatter.UseXmlSerializer = true;
xmlFormatter.SetSerializer<SendNotificationRequest>(new XmlSerializer(typeof(SendNotificationRequest)));
xmlFormatter.SetSerializer<DRMSAlertRequest>(new XmlSerializer(typeof(DRMSAlertRequest)));
}
I'm receiving the ExtAlert as null on the webapi controller. What might be the reason?
httpRequest.ContentType = "application/x-www-form-urlencoded";
changed this to
httpRequest.ContentType = "application/xml";

Resources