Newline in Constant Error and Syntax error, ',' expected - asp.net

I am currently working through this tutorial- https://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/introduction-and-overview
Everything is working except one page is filled with errors when I copy and paste it in there. This tutorial is done in Visual Studio 2013 and I am in 2015 but I didn't think that would make that big of difference, I made the assumption that the syntax would stay the same. Here is the code that when I paste in fills with 446 errors-
using System.Collections.Generic;
using System.Data.Entity;
namespace WingtipToys.Models
{
public class ProductDatabaseInitializer :
DropCreateDatabaseAlways<ProductContext>
{
protected override void Seed(ProductContext context)
{
GetCategories().ForEach(c => context.Categories.Add(c));
GetProducts().ForEach(p => context.Products.Add(p));
}
private static List<Category> GetCategories()
{
var categories = new List<Category> {
new Category
{
CategoryID = 1,
CategoryName = "Cars"
},
new Category
{
CategoryID = 2,
CategoryName = "Planes"
},
new Category
{
CategoryID = 3,
CategoryName = "Trucks"
},
new Category
{
CategoryID = 4,
CategoryName = "Boats"
},
new Category
{
CategoryID = 5,
CategoryName = "Rockets"
},
};
return categories;
}
private static List<Product> GetProducts()
{
var products = new List<Product> {
new Product
{
ProductID = 1,
ProductName = "Convertible Car",
Description = "This convertible car is fast! The engine is
powered by a neutrino based battery (not included)." +
"Power it up and let it go!",
ImagePath="carconvert.png",
UnitPrice = 22.50,
CategoryID = 1
},
new Product
{
ProductID = 2,
ProductName = "Old-time Car",
Description = "There's nothing old about this toy car,
except it's looks. Compatible with other old toy cars.",
ImagePath="carearly.png",
UnitPrice = 15.95,
CategoryID = 1
},
new Product
{
ProductID = 3,
ProductName = "Fast Car",
Description = "Yes this car is fast, but it also floats in
water.",
ImagePath="carfast.png",
UnitPrice = 32.99,
CategoryID = 1
},
new Product
{
ProductID = 4,
ProductName = "Super Fast Car",
Description = "Use this super fast car to entertain guests.
Lights and doors work!",
ImagePath="carfaster.png",
UnitPrice = 8.95,
CategoryID = 1
},
new Product
{
ProductID = 5,
ProductName = "Old Style Racer",
Description = "This old style racer can fly (with user
assistance). Gravity controls flight duration." +
"No batteries required.",
ImagePath = "carracer.png",
UnitPrice = 34.95,
CategoryID = 1
},
new Product
{
ProductID = 6,
ProductName = "Ace Plane",
Description = "Authentic airplane toy. Features realistic
color and details.",
ImagePath="planeace.png",
UnitPrice = 95.00,
CategoryID = 2
},
new Product
{
ProductID = 7,
ProductName = "Glider",
Description = "This fun glider is made from real balsa
wood.Some assembly required.",
ImagePath="planeglider.png",
UnitPrice = 4.95,
CategoryID = 2
},
new Product
{
ProductID = 8,
ProductName = "Paper Plane",
Description = "This paper plane is like no other paper
plane.Some folding required.",
ImagePath="planepaper.png",
UnitPrice = 2.95,
CategoryID = 2
},
new Product
{
ProductID = 9,
ProductName = "Propeller Plane",
Description = "Rubber band powered plane features two
wheels.",
ImagePath="planeprop.png",
UnitPrice = 32.95,
CategoryID = 2
},
new Product
{
ProductID = 10,
ProductName = "Early Truck",
Description = "This toy truck has a real gas powered
engine.Requires regular tune ups.",
ImagePath= "truckearly.png",
UnitPrice = 15.00,
CategoryID = 3
},
new Product
{
ProductID = 11,
ProductName = "Fire Truck",
Description = "You will have endless fun with this one
quarter sized fire truck.",
ImagePath= "truckfire.png",
UnitPrice = 26.00,
CategoryID = 3
},
new Product
{
ProductID = 12,
ProductName = "Big Truck",
Description = "This fun toy truck can be used to tow other
trucks that are not as big.",
ImagePath="truckbig.png",
UnitPrice = 29.00,
CategoryID = 3
},
new Product
{
ProductID = 13,
ProductName = "Big Ship",
Description = "Is it a boat or a ship. Let this floating
vehicle decide by using its " +
"artifically intelligent computer brain!",
ImagePath="boatbig.png",
UnitPrice = 95.00,
CategoryID = 4
},
new Product
{
ProductID = 14,
ProductName = "Paper Boat",
Description = "Floating fun for all! This toy boat can be
assembled in seconds.Floats for minutes!" +
"Some folding required.",
ImagePath="boatpaper.png",
UnitPrice = 4.95,
CategoryID = 4
},
new Product
{
ProductID = 15,
ProductName = "Sail Boat",
Description = "Put this fun toy sail boat in the water and
let it go!",
ImagePath="boatsail.png",
UnitPrice = 42.95,
CategoryID = 4
},
new Product
{
ProductID = 16,
ProductName = "Rocket",
Description = "This fun rocket will travel up to a height
of 200 feet.",
ImagePath="rocket.png",
UnitPrice = 122.95,
CategoryID = 5
}
};
return products;
}
}
}

There seems to be a problem while you copied the code as it split the description field into multiple lines, which is why you are seeing the error.
You could try like this and it will still allow multiple lines
Description = #"This convertible car is fast! The engine is
powered by a neutrino based battery (not included).
Power it up and let it go!"

In case someone else needs this. When pasting it in it put the description on two lines. If you put the description on one line it works fine.

Related

Flask restx api model not showing model data

I have a model as follows:
class Menu(db.Model):
itemId = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(255),index=True)
price = db.Column(db.Numeric)
description = db.Column(db.String(255),index=True)
image = db.Column(db.LargeBinary)
restaurantId = db.Column(db.Integer, db.ForeignKey('restaurants.id'))
createdOn = db.Column(db.DateTime,server_default=db.func.now())
status = db.Column(db.Integer,server_default="1")
orders = db.relationship('Orders', backref='menu', lazy='dynamic')
def __repr__(self):
return '<Menu of restaurant id {}>'.format(self.restaurantId)
And I have the following api model corresponding to it:
menu_model = api.model('Menu',
{'itemId':fields.Integer(),
'name':fields.String(),
'price':fields.Float(),
'description':fields.String(),
'restaurantId':fields.Integer(),
'createdOn:':fields.DateTime(),
'status':fields.Integer()})
The problem is that even though the createdOn values are correctly generated on DB side, the response shows the createdOn field as null. What could be the reason?
"menu":
{
"itemId": 1,
"name": "Menu item",
"price": 30.0,
"description": "Menu item description",
"restaurantId": 1,
"createdOn:": null,
"status": 1
}
this will accept the desired output. The first parameter is a label, not part of the json
menus = api.model(
"menu_item",
{
'itemId':fields.Integer(),
'name':fields.String(),
'price':fields.Float(),
'description':fields.String(),
'restaurantId':fields.Integer(),
'createdOn:':fields.DateTime(),
'status':fields.Integer()
},
)
menu_model = api.model(
"Menu",
{
"menu": Nested(menus),
},
)

ElasticSearch 7 nest 7 return attribute from result all result

I'm using ElarsticSearch 7.7 & NEST 7.7 and on my web page, I'm getting 9 search result documents per page. Even I'm showing the first 9 results on the page, I need to return some property values from all the results for side filtration on the web page.
Eg: if I'm searching "LapTop", my page will show 9 results on the first page. Also, I need to show all the "Manufactures" from all the search results. Not only manufacturers in the first-page result. Then customers can filter by manufacture not only display on the first page.
I have tried GlobalAggregation but it returns categories and manufactures only items in selected page.
public SearchResult Search(SearchType searchType, string searchQuery, int storeId, int pageNumber = 1, int pageSize = 12, IList<SearchFilter> requestFilter = null, decimal? priceFrom = 0, decimal? priceTo = 100000000, string sortBy = null, int totalCount = 0)
{
var queryContainer = new QueryContainer();
var sorts = new List<ISort>();
sorts.Add(new FieldSort { Field = "_score", Order = SortOrder.Descending });
switch (sortBy)
{
case "z-a":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Descending });
break;
case "a-z":
sorts.Add(new FieldSort { Field = Field<ElasticIndexGroupProduct>(p => p.SortValue), Order = SortOrder.Ascending });
break;
}
var aggrigations = new AggregationDictionary
{
{"average_per_child", new
AverageAggregation("average_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"max_per_child", new MaxAggregation("max_per_child",Field<ElasticIndexGroupProduct>(d => d.Price))},
{"min_per_child", new MinAggregation("min_per_child", Field<ElasticIndexGroupProduct>(d => d.Price))},
{
"globle_filter_aggrigation", new GlobalAggregation("globle_filter_aggrigation")
{
Aggregations =new AggregationDictionary
{
{"category_flow", new TermsAggregation("category_flow"){Field = Field<ElasticIndexGroupProduct>(p => p.CategoryFlow)} },
{"manufacturers", new TermsAggregation("manufacturers"){Field = Field<ElasticIndexGroupProduct>(p => p.Manufacturer)} }
}
}
}
};
var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
{
Profile = true,
From = (pageNumber - 1) * pageSize,
Size = pageSize,
Version = true,
Sort = sorts,
//Scroll = Time.MinusOne,
Aggregations = aggrigations
};
var multiMatch = new QueryStringQuery
{
Query = searchQuery,
Fields = GetSearchFields(searchType),
Boost = 1.1,
Name = "named_query",
DefaultOperator = Operator.Or,
Analyzer = "standard",
QuoteAnalyzer = "keyword",
AllowLeadingWildcard = true,
MaximumDeterminizedStates = 2,
Escape = true,
FuzzyPrefixLength = 2,
FuzzyMaxExpansions = 3,
FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
Rewrite = MultiTermQueryRewrite.ConstantScore,
Fuzziness = Fuzziness.Auto,
TieBreaker = 1,
AnalyzeWildcard = true,
MinimumShouldMatch = 2,
QuoteFieldSuffix = "'",
Lenient = true,
AutoGenerateSynonymsPhraseQuery = false
};
searchRequest.Query = new BoolQuery
{
Must = new QueryContainer[] { multiMatch },
Filter = new QueryContainer[] { queryContainer }
};
var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
var categoryFlowsGlobe = new List<string>();
var allAggregations = searchResponse.Aggregations.Global("globle_filter_aggrigation");
var categories = allAggregations.Terms("category_flow");
foreach (var aggItem in categories.Buckets)
{
if (!categoryFlowsGlobe.Any(x => x == aggItem.Key))
{
categoryFlowsGlobe.Add(aggItem.Key);
}
}
}
This is the exact use case for Post filter - to run a search request that returns hits and aggregations, then to apply filtering to the hits after aggregations have been calculated.
For Manufacturers, these can be retrieved with a terms aggregation in the search request - you can adjust the size on the aggregation if you need to return all manufacturers, otherwise you might decide to return only the top x.

How to avoid Dupliate value in View

I have a ProductList with Product of different categorises.
I dont want my view to hold duplicate values.
ProductController.cs
public ActionResult ProductList()
{
IEnumerable<ProductListDTO> ProductList;
if (User.IsInRole("Admin"))
{
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
};
}
else
{
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
where a.username==User.Identity.Name
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
};
}
return View(ProductList);
You can use distinct() with the query syntax you have used.
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
}.Distinct();

How to create a breadcrumb for categories and subcategories using linq

How to create breadcumb for categories with unlimited subcategories which their parent specified with their parentid column?
Imagine the following table entries:
id name parentid
=========================
1 animal NULL
2 veg NULL
3 mineral NULL
4 doggie 1
5 kittie 1
6 horsie 1
7 gerbil 1
8 birdie 1
9 carrot 2
10 tomato 2
11 potato 2
12 celery 2
If a recursive function working on the full set is ok then the following should work.
I threw it together in LINQPad. The magic is the recursive function GetBreadcrumbs. I added a third level "boxer" under doggie.
void Main()
{
var list = new List<MyEntity>()
{
new MyEntity() { Id = 1, Name = "animal" },
new MyEntity() { Id = 2, Name = "veg" },
new MyEntity() { Id = 3, Name = "mineral" },
new MyEntity() { Id = 4, Name = "doggie", ParentId = 1 },
new MyEntity() { Id = 5, Name = "kittie", ParentId = 1 },
new MyEntity() { Id = 6, Name = "horsie", ParentId = 1 },
new MyEntity() { Id = 7, Name = "gerbil", ParentId = 1 },
new MyEntity() { Id = 8, Name = "birdie", ParentId = 1 },
new MyEntity() { Id = 9, Name = "carrot", ParentId = 2 },
new MyEntity() { Id = 10, Name = "tomato", ParentId = 2 },
new MyEntity() { Id = 11, Name = "potato", ParentId = 2 },
new MyEntity() { Id = 12, Name = "celery", ParentId = 2 },
new MyEntity() { Id = 13, Name = "boxer", ParentId = 4 },
};
var breadcrumbs = GetBreadcrumbs(list);
foreach (var breadcrumb in breadcrumbs)
Console.WriteLine(breadcrumb);
}
// This is where the Magic happens!
public IEnumerable<string> GetBreadcrumbs(IEnumerable<MyEntity> entities, int? parentId = null)
{
var parents = entities.Where(x => x.ParentId == parentId);
var children = entities.Where(x => x.ParentId != parentId);
foreach (var parent in parents)
{
yield return parent.Name;
foreach (var trail in GetBreadcrumbs(children, parent.Id))
yield return (parent.Name + " > " + trail);
}
}
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
}

Routing issue in asp.net mvc 3. Displays items by category, but doesn't display all items

I want to display items by categories. I use linq and everything works except of that I can't display all items regardless category. Probably routing issue, cause I've already asked question about linq expression that i use, and it should be fine. Anyway, here is my code:
public ViewResult Content(string category, int page = 1)
{
var model = new StoreContentViewModel
{
Items = _itemsRepository.GetItems()
.Where(i => i.Product.Category == null ||
i.Product.Category != null && i.Product.Category == category)
.OrderBy(i => i.ItemId)
.Skip((page - 1) * PageSize)
.Take(PageSize)
.Select(i => i),
}
}
And the RegisterRouts method's contents:
// without categories
routes.MapRoute(
null,
"Store/Content/Page{page}",
new { controller = "Store", action = "Content", category = (string)null},
new { page = #"\d+" });
// with categories
routes.MapRoute(
null,
"Store/Content/{category}/Page{page}",
new { controller = "Store", action = "Content" },
new { page = #"\d+" });
// Default route
routes.MapRoute(
null,
"{controller}/{action}",
new { controller = "Home", action = "Index"});
I'm confused of the order of "with and without categories" routs.
The thing is when I enter URL:
~/Store/Content
or:
~/Store/Content/Page1 // or Page2
items are not displayed. But if I enter:
~/Store/Content/Man's-Shoes/Page1
the items that are associated with "Man's-Shoes" category are displayed.
So, do this issue has something to do with routs or mabby there is another problem??
p.s. I've been takling this issue for the last 2 days, so any help would be appropriate.
Edited:
And also there is this unit test that fails. Probably it is badly written. Check it also.
In my model I have Items entity that "contains" Products and Shipping entities:
[TestMethod]
public void Can_Filter_Content()
{
//Arrange
private Mock<IItemsRepository> _itemsMock = new Mock<IItemsRepository>();
private Mock<IProductRepository> _productsMock = new Mock<IProductRepository>();
private Mock<IShippingRepository> _shippingMock = new Mock<IShippingRepository>();
_itemsMock.Setup(i => i.GetItems()).Returns(new[]
{
new Item { ItemId = 1, ProductId = 1, ShippingId = 1},
new Item { ItemId = 2, ProductId = 2, ShippingId = 2},
new Item { ItemId = 3, ProductId = 3, ShippingId = 3},
new Item { ItemId = 4, ProductId = 4, ShippingId = 4}
});
_productsMock.Setup(p => p.GetProducts()).Returns(new[]
{
new Product { ProductId = 1, Category = "shoes"},
new Product { ProductId = 2, Category = "shoes"},
new Product { ProductId = 3, Category = "superShoes"},
new Product { ProductId = 4, Category = "shoes"}
});
var controller = new StoreController(_itemsMock.Object,
_productsMock.Object, _shippingMock.Object) {PageSize = 2};
// Act
Item[] result = ((StoreContentViewModel) controller.Content(null).Model).Items.ToArray();
ViewResult viewResult = controller.Content(null);
// Assert
Assert.IsTrue(result[0].ItemId == 1 && result[1].ItemId == 2);
Assert.AreEqual(result.Length, 2);
Assert.AreEqual("", viewResult.ViewName);
}
Mabby this helps
Should this:
.Where(i => i.Product.Category == null ||
i.Product.Category != null && i.Product.Category == category)
Be this:
.Where(i => category == null ||
i.Product.Category != null && i.Product.Category == category)
When category is null, the original condition says where the product category is not null, and that category matches null, which will never work. The new condition says if the category is null, don't evaluate the condition; otherwise, match on the category ("Man's-Shoes").

Resources