ASP.net MVC Entity Data Model Class Serialize Problem - asp.net

I want to serialize my Entity Data Model Class I try to change ICollection to List and HashSet to List but didn't work i can't fix it.
public partial class Product
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Product()
{
this.OrderDetails = new HashSet<OrderDetail>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Here is my asmx code
public class VisualWebService : System.Web.Services.WebService
{
[WebMethod]
public Product AddNewProduct(Product _product)
{
try
{
ProductDb productDb = new ProductDb();
_product = productDb.AddNewProduct(_product);
return _product;
}
catch (Exception)
{
throw;
}
}
}
}

Related

asp.net core does not respect case sensitivity

i have this controller method that return an array of objects
public async Task<ActionResult<List<AllClientsDataModelDb>>> GetAll()
{
var ReturnValue = new List<AllClientsDataModelDb>();
ReturnValue = await Clda.GetClients(new { cm = 1 });
return (ReturnValue);
}
here is the code of AllClientsDataModelDb class
public class AllClientsDataModelDb
{
public long IDCLIENT { get; set; }
public string CL_CODE { get; set; }
public string CL_NOM { get; set; }
public string CL_ADRESSE { get; set; }
public string CL_CODEPOS { get; set; }
public string CL_VILLE { get; set; } = null;
public int CL_ETATCOMPTE { get; set; }
public int CL_AlerteCompta { get; set; }
}
but the result of that method (in browser) does not respect the case sensitivity of the class properties
Example :
[{"idclient":1,"cL_CODE":"1","cL_NOM":"EUROPEQUIPEMENTMysql","cL_ADRESSE":"ModifSoft","cL_CODEPOS":"44","cL_VILLE":"STDENIS","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
{"idclient":2,"cL_CODE":"2","cL_NOM":"A UTOMATISMES-SERVICESzzzz","cL_ADRESSE":null,"cL_CODEPOS":"97420","cL_VILLE":"LEPORT","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
what i'm doing wrong ?
You need to create your own Json Profile Formatter by inheriting from JsonOutputFormatter.
public class PascalCaseJsonProfileFormatter : JsonOutputFormatter
{
public PascalCaseJsonProfileFormatter() : base(new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }, ArrayPool<char>.Shared)
{
SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse
("application/json;profile=\"https://en.wikipedia.org/wiki/PascalCase\""));
}
}
Then modify your Startup.cs file's ConfigureServices Method like this.
services.AddMvc()
.AddMvcOptions(options =>
{
options.OutputFormatters.Add(new PascalCaseJsonProfileFormatter());
});
Try this, it should work.

Getting computed column filled in EF Core on every call to entity

I am using code first with Entity Framework in my ASP.NET Core application. I am using a generic repository for crud operations.
I have a base audit class which is inherited by all entities in my dbcontext.
public class Audit_base
{
public int AddedUserId { get; set; }
public int ModifiedUserId { get; set; }
// I'd like to have it filled every time I query
[NotMapped]
public String AddedUsername { get; set; }
[NotMapped]
public String EditedUserName { get; set; }
}
And I have a User class in the dbcontext
public class UserMaster
{
public int Id { get; set; }
public int FullName { get; set; }
}
All my tables (about 70) inherit from the Audit_base class.
public class Book : Audit_base
{
public int Id { get; set; }
public String BookName { get; set; }
public virtual UserMaster CreatedByUser { get; set; }
public virtual UserMaster ModifiedByUser { get; set; }
}
And this is the part of generic repository class where I query these tables
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
protected readonly ApplicationContext _context;
public GenericRepository(ApplicationContext context)
{
_context = context;
}
public IEnumerable<T> Find(Expression<Func<T, bool>> expression)
{
return _context.Set<T>().Where(expression);
}
public IEnumerable<T> GetAll()
{
return _context.Set<T>().ToList();
}
public T GetById(int id)
{
return _context.Set<T>().Find(id);
}
}
Is there a way that I can get the user name corresponding to the created and modified userid when I query it, like a computed column?

How to use mutiple models for one dbset

NET MVC expetrts!
I'm new in asp.NET MVC 4, so I got a simple problem not to know how to solve!
so this is my NotActivatedUsers model :
public class NotActivatedUser
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DefaultValue(false)]
public bool isActive { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string email { get; set; }
[Required]
public string activeCode { get; set; }
public DateTime createDate { get; set; }
}
and here is my SignUp model :
public class SignUpModel
{
[Key]
public int id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email!")]
public string email { get; set; }
}
and this in my dbset:
public class Context : DbContext
{
public DbSet<NotActivatedUser> notActivatedUser { get; set; }
}
My problem is " How to use my SignUp model to insert into NotActivatedUsers Dbset?
I tried this :
public class AccountController : Controller
{
private Context db = new Context();
[HttpPost]
[AllowAnonymous]
public ActionResult SignUp(SignUpModel signUpModel)
{
if (ModelState.IsValid)
{
db.notActivatedUser.Add(signUpModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(signUpModel);
}
[AllowAnonymous]
public ActionResult SignUp()
{
return View();
}
}

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!

Using ComplexType with ToList causes InvalidOperationException

I have this model
namespace ProjectTimer.Models
{
public class TimerContext : DbContext
{
public TimerContext()
: base("DefaultConnection")
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<ProjectTimeSpan> TimeSpans { get; set; }
}
public class DomainBase
{
[Key]
public int Id { get; set; }
}
public class Project : DomainBase
{
public UserProfile User { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IList<ProjectTimeSpan> TimeSpans { get; set; }
}
[ComplexType]
public class ProjectTimeSpan
{
public DateTime TimeStart { get; set; }
public DateTime TimeEnd { get; set; }
public bool Active { get; set; }
}
}
When I try to use this action I get the exception The type 'ProjectTimer.Models.ProjectTimeSpan' has already been configured as an entity type. It cannot be reconfigured as a complex type.
public ActionResult Index()
{
using (var db = new TimerContext())
{
return View(db.Projects.ToList);
}
}
The view is using the model #model IList<ProjectTimer.Models.Project>
Can any one shine some light as to why this would be happening?
Your IList<ProjectTimeSpan> property is not supported by EF. A complex type must always be part of another entity type, you cannot use a complex type by itself. If you absolutely need to have ProjectTimeSpan as a complex type, you will need to create a dummy entity type that only contains a key and a ProjectTimeSpan, and change the type of Project.TimeSpans to a list of that new type.

Resources