how can i add memorycache in this method ?
this is a section of my code that i want to set memory cache on it.
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
ViewBag.Groups = _productService.GetAllGroup();
ViewBag.Tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
ViewBag.size = _productService.GetSizes().ToList();
ViewBag.pageId = pageId;
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}
private readonly IMemoryCache _memoryCache;
public Constructor (IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public IActionResult Index(int pageId = 1, string filter = "",
int startPrice = 0, int endPrice = 0, string getType = "", string orderByType = "date",
List<int> selectedGroups = null, List<int> selectedBrand = null, List<int> selectedTags = null
, List<int> selectedsize = null , string Discount = "")
{
ViewBag.selectedGroups = selectedGroups;
ViewBag.selectedTags = selectedTags;
ViewBag.selectedsize = selectedsize;
ViewBag.Discount = Discount;
ViewBag.getType = getType;
var groups = new List<Group>();
if (_memoryCache.TryGetValue("groups", out groups)
{
ViewBag.Groups = groups;
}
else
{
groups = _productService.GetAllGroup();
_memoryCache.Set("groups", groups);
ViewBag.Groups = groups;
}
var tags = new List<Tag>();
if (_memoryCache.TryGetValue("tags", out tags)
{
ViewBag.Tags = tags;
}
else
{
tags = _productService.GetTags().Where(c => c.ActiveRow).ToList();
_memoryCache.Set("tags", tags);
ViewBag.Tags = tags;
}
var sizes = new List<Size>();
if (_memoryCache.TryGetValue("sizes", out sizes)
{
ViewBag.size = sizes;
}
else
{
sizes = _productService.GetSizes().ToList();
_memoryCache.Set("sizes", sizes);
ViewBag.size = sizes;
}
var pageId = null;
if (_memoryCache.TryGetValue("pageId", out pageId))
{
ViewBag.pageId = pageId;
}
else
{
_memoryCache.Set("pageId", pageId);
ViewBag.pageId = pageId;
}
return View(_productService.GetProducttype(pageId, filter, startPrice, endPrice, getType, orderByType, selectedGroups, selectedBrand, 24, selectedTags, selectedsize, Discount));
}
Related
I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.
[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
if (id == 0 || patchNoteDTO == null)
return BadRequest();
var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
if (note == null)
return NotFound();
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
patchNoteDTO.ApplyTo(createNoteDTO, ModelState);
if (!ModelState.IsValid)
return BadRequest(ModelState);
Note updateNote = _mapper.Map<Note>(createNoteDTO);
updateNote.ID = id;
updateNote.ChangedDate = DateTime.Now;
_db.Update(updateNote);
if (!field.ToLower().Equals("category"))
_db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
_db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
_db.SaveChanges();
return NoContent();
}
My ApplicationDBContext looks like this:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
modelBuilder.Entity<Note>()
.HasOne(e => e.Category)
.WithMany(e => e.Notes)
.HasForeignKey(e => e.FKCategory)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Note>()
.HasMany(n => n.Tags)
.WithMany(t => t.Notes)
.UsingEntity(j => j
.ToTable("NoteTag")
.HasData
(
new { NotesID = 1, TagsTagID = 1 },
new { NotesID = 2, TagsTagID = 2 }
));
modelBuilder.Entity<Category>().HasData
(
new Category
{
CategoryID = 1,
CategoryName = "testCategory1",
CreatedDate = DateTime.Now
},
new Category
{
CategoryID = 2,
CategoryName = "testCategory2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Tag>().HasData
(
new Tag
{
TagID = 1,
TagName = "testTag1",
CreatedDate = DateTime.Now
},
new Tag
{
TagID = 2,
TagName = "testTag2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Note>().HasData
(
new Note
{
ID = 1,
Title = "testTitle1",
Description = "testDescription1",
FKCategory = 1,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
},
new Note
{
ID = 2,
Title = "testTitle2",
Description = "testDescription2",
FKCategory = 2,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
}
);
}
}
Any suggestions?
Thanks in advance.
Initially I tried without the following if condition:
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
But I got a different error:
I wanted to remove a tag form the following object using a PATCH request:
Note Object
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
Yify Movies class:-
It's the JSON from the above API converted int0 dart.
class YifyMovies {
String status;
String statusMessage;
Data data;
YifyMovies({this.status, this.statusMessage, this.data});
YifyMovies.fromJson(Map<String, dynamic> json) {
status = json['status'];
statusMessage = json['status_message'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['status_message'] = this.statusMessage;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Data {
int movieCount;
int limit;
int pageNumber;
List<Movies> movies;
Data({this.movieCount, this.limit, this.pageNumber, this.movies});
Data.fromJson(Map<String, dynamic> json) {
movieCount = json['movie_count'];
limit = json['limit'];
pageNumber = json['page_number'];
if (json['movies'] != null) {
movies = new List<Movies>();
json['movies'].forEach((v) {
movies.add(new Movies.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['movie_count'] = this.movieCount;
data['limit'] = this.limit;
data['page_number'] = this.pageNumber;
if (this.movies != null) {
data['movies'] = this.movies.map((v) => v.toJson()).toList();
}
return data;
}
}
class Movies {
int id;
String url;
String imdbCode;
String title;
String titleEnglish;
String titleLong;
String slug;
int year;
double rating;
int runtime;
List<String> genres;
String summary;
String descriptionFull;
String synopsis;
String ytTrailerCode;
String language;
String mpaRating;
String backgroundImage;
String backgroundImageOriginal;
String smallCoverImage;
String mediumCoverImage;
String largeCoverImage;
String state;
List<Torrents> torrents;
String dateUploaded;
int dateUploadedUnix;
Movies(
{this.id,
this.url,
this.imdbCode,
this.title,
this.titleEnglish,
this.titleLong,
this.slug,
this.year,
this.rating,
this.runtime,
this.genres,
this.summary,
this.descriptionFull,
this.synopsis,
this.ytTrailerCode,
this.language,
this.mpaRating,
this.backgroundImage,
this.backgroundImageOriginal,
this.smallCoverImage,
this.mediumCoverImage,
this.largeCoverImage,
this.state,
this.torrents,
this.dateUploaded,
this.dateUploadedUnix});
Movies.fromJson(Map<String, dynamic> json) {
id = json['id'];
url = json['url'];
imdbCode = json['imdb_code'];
title = json['title'];
titleEnglish = json['title_english'];
titleLong = json['title_long'];
slug = json['slug'];
year = json['year'];
rating = json['rating'];
runtime = json['runtime'];
genres = json['genres'].cast<String>();
summary = json['summary'];
descriptionFull = json['description_full'];
synopsis = json['synopsis'];
ytTrailerCode = json['yt_trailer_code'];
language = json['language'];
mpaRating = json['mpa_rating'];
backgroundImage = json['background_image'];
backgroundImageOriginal = json['background_image_original'];
smallCoverImage = json['small_cover_image'];
mediumCoverImage = json['medium_cover_image'];
largeCoverImage = json['large_cover_image'];
state = json['state'];
if (json['torrents'] != null) {
torrents = new List<Torrents>();
json['torrents'].forEach((v) {
torrents.add(new Torrents.fromJson(v));
});
}
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['url'] = this.url;
data['imdb_code'] = this.imdbCode;
data['title'] = this.title;
data['title_english'] = this.titleEnglish;
data['title_long'] = this.titleLong;
data['slug'] = this.slug;
data['year'] = this.year;
data['rating'] = this.rating;
data['runtime'] = this.runtime;
data['genres'] = this.genres;
data['summary'] = this.summary;
data['description_full'] = this.descriptionFull;
data['synopsis'] = this.synopsis;
data['yt_trailer_code'] = this.ytTrailerCode;
data['language'] = this.language;
data['mpa_rating'] = this.mpaRating;
data['background_image'] = this.backgroundImage;
data['background_image_original'] = this.backgroundImageOriginal;
data['small_cover_image'] = this.smallCoverImage;
data['medium_cover_image'] = this.mediumCoverImage;
data['large_cover_image'] = this.largeCoverImage;
data['state'] = this.state;
if (this.torrents != null) {
data['torrents'] = this.torrents.map((v) => v.toJson()).toList();
}
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
class Torrents {
String url;
String hash;
String quality;
String type;
int seeds;
int peers;
String size;
int sizeBytes;
String dateUploaded;
int dateUploadedUnix;
Torrents(
{this.url,
this.hash,
this.quality,
this.type,
this.seeds,
this.peers,
this.size,
this.sizeBytes,
this.dateUploaded,
this.dateUploadedUnix});
Torrents.fromJson(Map<String, dynamic> json) {
url = json['url'];
hash = json['hash'];
quality = json['quality'];
type = json['type'];
seeds = json['seeds'];
peers = json['peers'];
size = json['size'];
sizeBytes = json['size_bytes'];
dateUploaded = json['date_uploaded'];
dateUploadedUnix = json['date_uploaded_unix'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['hash'] = this.hash;
data['quality'] = this.quality;
data['type'] = this.type;
data['seeds'] = this.seeds;
data['peers'] = this.peers;
data['size'] = this.size;
data['size_bytes'] = this.sizeBytes;
data['date_uploaded'] = this.dateUploaded;
data['date_uploaded_unix'] = this.dateUploadedUnix;
return data;
}
}
Any help, please? Tell me if any more info is required?
I'm trying to list all the movies and use them for tabview in flutter which can show them in listview as well as gridview. I'm using Bloc architecture for layouts so YifyMovie class is in hom_model and the code above is in home_provider.
Your YifyMovies class is already handling the parsing for you.
So your code should change from
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies();
movie.data.movies = [];
for (var json in decodedJson) {
movie.data.movies.add(Movies.fromJson(json));
}
return movie;
}
to
Future<YifyMovies> getData() async {
var res = await http.get("https://yts.lt/api/v2/list_movies.json");
var decodedJson = jsonDecode(res.body);
YifyMovies movie = YifyMovies.fromJson(decodedJson);
return movie;
}
I know how to build a simple lambda like x => x > 5:
int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> result1 = nbs.Where(x => x > 5);
ParameterExpression parameter = Expression.Parameter(typeof(int), "x");
ConstantExpression constant = Expression.Constant(5);
BinaryExpression expressionBody = Expression.GreaterThan(parameter, constant);
Expression<Func<int, bool>> expression = Expression.Lambda<Func<int, bool>>(expressionBody, parameter);
IEnumerable<int> result2 = nbs.Where(expression.Compile());
But, how do I create a more complex lambda like this p=>p.FindAttribute("Gender")?.Value == "Female" in the same style as above?
public class Person
{
public bool POI { get; set; } = false;
public string Name { get; set; }
public List<Car> Cars { get; set; }
public List<Attribute> Attributes { get; set; }
public bool PersonOfInterest()
{
return POI;
}
public Attribute FindAttribute(string name)
{
return Attributes.FirstOrDefault(a => a.Name == name);
}
}
public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
public Attribute(string name, string value) { Name = name; Value = value; }
}
public class Car
{
public string Make { get; set; }
public int Horsepowers { get; set; }
public string Fuel { get; set; }
}
Person p1 = new Person();
p1.Name = "Thom";
p1.POI = true;
p1.Attributes = new List<Attribute>() {new Attribute("Length", "Tall"), new Attribute("Hair", "Long hair")};
p1.Cars = new List<Car>()
{
new Car(){Horsepowers = 100, Make = "Toyota", Fuel = "Diesel"},
new Car(){Horsepowers = 200, Make = "Fiat", Fuel = "Diesel"},
new Car(){Horsepowers = 300, Make = "Audi", Fuel = "Diesel"},
new Car(){Horsepowers = 150, Make = "Ferrari", Fuel = "Petrol"}
};
Person p2 = new Person();
p2.POI = false;
p2.Attributes = new List<Attribute>() { new Attribute("Nationality", "English"), new Attribute("Gender", "Female") };
p2.Name = "Sophie";
p2.Cars = new List<Car>()
{
new Car(){Horsepowers = 500, Make = "McLaren", Fuel = "Diesel"},
new Car(){Horsepowers = 200, Make = "Volvo", Fuel = "Diesel"},
new Car(){Horsepowers = 300, Make = "Audi", Fuel = "Diesel"},
new Car(){Horsepowers = 400, Make = "Ferrari", Fuel = "Diesel"}
};
IEnumerable<Person> res = persons.Where(p=>p.FindAttribute("Gender")?.Value == "Female");
Of course I could always create a new method on Person like:
public bool HasAttributeWithValue(string name, string value)
{
return FindAttribute(name)?.Value == value;
}
But it's still of interest to me if it's possible to construct the complex lambda dynamically!
This piece of code does the job.
ParameterExpression parameter = Expression.Parameter(typeof(Person), "p");
ConstantExpression my_null_object = Expression.Constant(null);
ConstantExpression gender = Expression.Constant("Gender");
MethodCallExpression methodcall = Expression.Call(parameter, typeof(Person).GetMethod("FindAttribute"), gender);
BinaryExpression is_null = Expression.Equal(methodcall, my_null_object);
ConstantExpression constant = Expression.Constant("Female");
MemberExpression member = Expression.Property(methodcall, typeof(Attribute).GetProperty("Value"));
BinaryExpression expressionBody = Expression.Equal(member, constant);
BinaryExpression cond = Expression.AndAlso(Expression.IsFalse(is_null), expressionBody);
Maybe clearer this way
ParameterExpression parameter = Expression.Parameter(typeof(Person), "p");
ConstantExpression my_null_object = Expression.Constant(null);
MethodCallExpression methodcall = Expression.Call(parameter, typeof(Person).GetMethod("FindAttribute"), Expression.Constant("Gender"));
BinaryExpression cond = Expression.AndAlso(
Expression.IsFalse(Expression.Equal(methodcall, my_null_object)),
Expression.Equal(
Expression.Property(methodcall, typeof(Attribute).GetProperty("Value")),
Expression.Constant("Female")
)
);
Null-conditional operator is a language feature. It can be converted to this code:
var attribute = p.FindAttribute("Gender");
return attribute == null ? false : attribute.Value == "Female";
To build an expression tree you can use Expression.Block:
var p = Expression.Parameter(typeof(Person), "p");
var findAttribute = Expression.Call(p,
typeof(Person).GetMethod(nameof(Person.FindAttribute)),
Expression.Constant("Gender"));
var attribute = Expression.Parameter(typeof(Attribute), "attribute");
var body = Expression.Block(
new[] {attribute}, // local variables
new Expression[]
{
Expression.Assign(attribute, findAttribute),
Expression.Condition(
Expression.Equal(attribute, Expression.Constant(null)),
Expression.Constant(false),
Expression.Equal(
Expression.PropertyOrField(attribute, "Value"),
Expression.Constant("Female")))
}
);
var lambda = Expression.Lambda<Func<Person, bool>>(body, p);
public ActionResult update( int? id)
{
BusDetailsModel model = new BusDetailsModel();
using (var ent = new OnlineReservation.AddData.OnlineReservationEntities1())
{
var db = ent.BusDetails.FirstOrDefault(x=>x.busId ==id);
model.BusId = db.busId;
model.Busname = db.busname;
model.Busowner = db.busowner;
model.Bustype = db.busType;
model.Buscapacity = db.busCapacity;
}
return View(model);
}
Does anyone know why UsernameExists wont return True. I must have my syntax messed up somewhere.
[TestMethod()]
public void GenerateUsername_AppendTwoCharacters_ReturnUsernameWithTwoAppendedCharacters()
{
var usersRepository = MockRepository.GenerateStub<IUsersRepository>();
var target = new StudentsService(null, null, usersRepository, null, null, null, null);
usersRepository.Expect(q => q.UsernameExists("", null)).Return(true);
var actual = target.GenerateUsername("test", "student", "280000");
Assert.AreEqual("A", actual);
}
public string GenerateUsername(string firstName, string lastName, string studentNumber)
{
var originalusername = new StudentUsernameGenerator(firstName, lastName, studentNumber).Generate(2, 2, 4);
var username = originalusername;
if (!string.IsNullOrWhiteSpace(username))
{
decimal maxCharacters = 26;
var counter = 0;
var overflow = 1;
while (_usersRepository.UsernameExists(username, null))
{
counter++;
if (counter > maxCharacters)
{
overflow++;
counter = 1;
}
username = GetCharacterPaddingForDuplicateUsername(counter, overflow, originalusername);
}
}
return username;
}
I had to add IgnoreArguments
usersRepository.Stub(q => q.UsernameExists("", null)).IgnoreArguments().Return(true);