Find node id by name in Umbraco Razor - razor

I have a site with structure like Home -> News -> Year -> Month -> Day -> Article and need a query to find the id of the Day folder where the name of the folder matches a specified Year, Month and Day.
For example for 12th May 2003 it would be something like:
#something().where("Year.name = 2003").where("Month.name = May").where("Day.name = 12")

Depending on your preference, you can construct a query using either the dynamic DynamicPublishedContent or the strongly-typed IPublishedContent API.
The query will be different depending on where it's used, so assuming you want to run this query and display the results in the "News" page, you need something like the following:
var year = CurrentPage.Years.Where("Name == #1", "2013").First();
var month = year.Months.Where("Name == #1", "May").First();
var day = month.Days.Where("Name == #1", "12").First();
var dayId = day.Id;
Alternatively, you can try the strongly typed version:
var day = Model.Content
.Descendants("Year").First(y => y.Name == "2013")
.Descendants("Month").First(m => m.Name == "May")
.Descendants("Day").First(d => d.Name == "12").Id;
I've used First() for brevity but in reality you might want to check if the page exists before getting its descendants. Also, you might want to have a look at the documentation and come up with a query that's better suited to your scenario.

Related

Indesign - Is it possible to update value in cell when I know ID of the product?

I have a question, my colleague is creating product catalog in our company (in Indesign)
He is updating a version from last year, because we have not much new products BUT all the prices (~7000) are new.
I have never worked with Indesign before, so my question is, is it somehow possible to update OLD prices to NEW prices using ID of products, and the price is always located in the cell next to ID? Please check screenshots.
This is the table with new Prices, in csv file.
THANKS for any help.
Nikol
Possible workaround is:
read CSV line by line and store current ID and current price
use current ID for doc.findText() method
the parent of 1st found element should be an IDcell
odlPriceCell should be a current table's cell with index +1
use current price for new odlPriceCell contents
sample code:
var
mDoc = app.activeDocument,
mSource = File("~/Desktop/prices.csv"),
// mTarget = mDoc.stories.everyItem().tables.everyItem(),
cLine, cID, cPrice,
cFound, oldID_Cell, target_Cell,
separator = ",";
app.findTextPreferences = null;
mSource.open("r");
do {
cLine = mSource.readln().split(separator);
cID = cLine[0];
cPrice = cLine[1];
if (!cID.match(/^\d+-\d+/)) continue;
app.findTextPreferences.findWhat = cID;
cFound = mDoc.findText();
if (!cFound.length) continue;
oldID_Cell = cFound[0].texts[0].parent;
if (oldID_Cell.constructor.name !="Cell") continue;
target_Cell = oldID_Cell.parent.cells.item(oldID_Cell.index + 1);
target_Cell.texts[0].contents = cPrice;
} while (!mSource.eof);
mSource.close();
Notice mSource path to modify

BigCommerce Stencil - Product Variant Stock Levels

A client wants to set up A/B testing on the Product Detail Page related to the stock_level of a product's variants. Once the user selects their options, if the quantity is less than 5, I'd show something like "Hurry, only 3 more in stock"...
I believe I have the correct Inventory settings enabled, because I can retrieve the stock_level of a product without options.
Has anyone had success pulling variant SKU stock_levels in stencil?
Thanks
This can be done using javascript in the assets/js/theme/common/product-details.js file. On initial page load and each time a product option is changed, there is a function updateView(data) that is called. The data parameter contains all the info you need for the selected variation.
Starting on line 285, replace this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
this.showMessageBox(data.stock_message || data.purchasing_message);
with this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
if(data.stock < "5") {
data.stock_message = "Hurry, only " + data.stock + " left!";
}
this.showMessageBox(data.stock_message || data.purchasing_message);

Entity framework updates several records when FirstOrDefault() is used

I have a rather strange problem which is scratching my head at the moment. I am using EF together with MySQL for a project and when I want to update a record on the database like this
using (var context = new MyDbContext())
{
var record = (from d in context.Dictionary where d.CompanyName == companyName && d.Name == "Logo" select d).FirstOrDefault();
record.Value = _path;
context.SaveChanges();
}
Then every record that has d.Name == "Logo" gets updated for some reason, which means that it ignores the d.CompanyName == companyName part. Anyone who has experienced the same problem or know how to solve it?
Thanks in advance.
Actually I don't use EF Provider for MySQL often but I suppose it works.
The problem can be splitted in 2 parts, a select and an update. The select is fine, if you need to see what is the query you can split the select statement like this
var query = (from d in context.Dictionary where d.CompanyName == companyName && d.Name == "Logo" select d);
var record = query.FirstOrDefault();
and have a look to query variable (just point it in debug mode).
About your issue the only reason that I can immagine is that you did not configure the Dictionary class in the right way.
I mean, when you run context.SaveChanges an Update query is generated using the Key definition of Dictionary (the Where part of the query). If the key definition is wrong, the where clause will be wrong.
Use this I hope this will help you.
using (var context = new MyDbContext())
{
var record = context.Dictionary.Where(x=> x.CompanyName == companyName && x.Name == "Logo").FirstOrDefault();
record.Value = _path;
context.SaveChanges();
}

Include nested entity details but don't group by then when grouping by other fields

I working with Database first C# MVC, EF6, LINQ and JSon to try and pass data to both Highcharts and Google Maps for some of my reporting.
If I could add an image I would show you the relevant portion of my model, but sadly I need more reputation to do that...
The portion of the Entity Model I'm concentrating on right now is based on a central Docket that contains a BuildingCode as part of a one-to-many relationship to a building with and address and further relationship to the buildings polygons (for mapping). Dockets are also classified by one or more DocketTypes and thus there is a many-to-many relationship between Dockets and DocketTypes, which is not directly exposed to through the EF.
As an example a Docket which represents an investigation, could be related to the theft of a mobile phone in building A located on Campus X, not only was the cellphone stolen but the assailant also assaulted the victim in order to steal the mobile phone. So there are 2 DocketTypes here 1. Theft of mobile phone and 2. assault. Note: this is fictitious and for illustration purposes only .
One of my fundamental reports requires that I count how many docketTypes affect each building and each campus in a given period. When I display this I also need to show what the DocketTypes are.
I have no end of nightmare trying to find a way to get this right, I keep running into circular reference errors and needing to use explicit conversions when trying to model the data with LINQ so that I can pass a single nested object through JSON to the client side where displaying will occur.
In the below code I am told I need an Explicit conversion:
Cannot implicitly convert type 'Campus_Investigator.ViewModels.DocketTypeViewModel' to 'System.Collections.Generic.IEnumerable<Campus_Investigator.ViewModels.DocketTypeViewModel>'. An explicit conversion exists (are you missing a cast?)
var currentDocketQuery = from d in db.Dockets
from dt in d.DocketTypes
from bp in d.BuildingDetail.BuildingPolygons
where d.OccurrenceStartDate >= datetime && d.BuildingDetail.CampusName == Campus
select new CampusBuildingDocketTypeViewModel()
{
BuildingCode = d.BuildingDetail.BuildingCode,
BuildingName = d.BuildingDetail.BuildingName,
//BuildingPolygons = d.BuildingDetail.BuildingPolygons,
DocketTypes = new DocketTypeViewModel()
{
Category = dt.Category,
SubCategory = dt.SubCategory,
ShortDescription = dt.ShortDescription
}
};
I appreciate any ideas on how I can explicitly convert this or is that a better method I can use and avoid the circular reference error?
You included some redundant part in your query (which performs some inner join). The from bp in d.BuildingDetail.BuildingPolygons is joined in but then is not shown in the result. So it totally does not make sense. There may be duplicated elements in the result due to that. The from dt in d.DocketTypes is wrong joined in, although you need it in the result but because the DocketTypes is output per d in db.Dockets, so it's just simply queried like this:
var currentDocketQuery = from d in db.Dockets
where d.OccurrenceStartDate >= datetime && d.BuildingDetail.CampusName == Campus
select new CampusBuildingDocketTypeViewModel()
{
BuildingCode = d.BuildingDetail.BuildingCode,
BuildingName = d.BuildingDetail.BuildingName,
//BuildingPolygons = d.BuildingDetail.BuildingPolygons,
DocketTypes = d.DocketTypes
};
In fact I can see the commented line //BuildingPolygons = d.BuildingDetail.BuildingPolygons, so if you want to include that, it should also work.
If the DocketTypes has different type of d.DocketTypes, then you need a simple projection like this:
var currentDocketQuery = from d in db.Dockets
where d.OccurrenceStartDate >= datetime && d.BuildingDetail.CampusName == Campus
select new CampusBuildingDocketTypeViewModel()
{
BuildingCode = d.BuildingDetail.BuildingCode,
BuildingName = d.BuildingDetail.BuildingName,
//BuildingPolygons = d.BuildingDetail.BuildingPolygons,
DocketTypes = d.DocketTypes.Select(e => new DocketTypeViewModel()
{
Category = e.Category,
SubCategory = e.SubCategory,
ShortDescription = e.ShortDescription
})
};
I managed to solve this one by using the below. The major hassle with this is the circular referencing that exists in the model. When JSON serializes these, everything falls apart so it takes a lot of transforming to make sure that I only extract what I need. In this case grouped campus and building data (below includes the polygons which where only half commented out in the above) and then the include the detail of the DocketTypes that occurred at each building.
var datetime = DateTime.Now.AddDays(-30);
var campusDocket = from d in db.Dockets
where d.OccurrenceStartDate >= datetime && d.BuildingDetail.CampusName == Campus
group d by new { d.BuildingDetail.CampusName, d.BuildingDetail.BuildingCode, d.BuildingDetail.BuildingName } into groupdata
select new CampusBuildingDocketTypeViewModel
{
BuildingCode = groupdata.Key.BuildingCode,
BuildingName = groupdata.Key.BuildingName,
CampusName = groupdata.Key.CampusName,
Count = groupdata.Count(),
BuildingPolygons = from bp in db.BuildingPolygons
where bp.BuildingCode == groupdata.Key.BuildingCode
select new BuildingPolygonViewModel
{
Accuracy = bp.Accuracy,
BuildingCode = bp.BuildingCode,
PolygonOrder = bp.PolygonOrder,
Latitude = bp.Latitude,
Longitude = bp.Longitude
},
DocketTypes = from doc in db.Dockets
from dt in doc.DocketTypes
where doc.OccurrenceStartDate >= datetime && doc.BuildingCode == groupdata.Key.BuildingCode
select new DocketTypeViewModel
{
Category = dt.Category,
SubCategory = dt.SubCategory,
ShortDescription = dt.ShortDescription
}
};
The Answer again is ViewModels. I'm finding ViewModels seem to solve a lot of problems...

How do I most efficiently narrow my selection of entities from a database?

I am using the following code to select every course from my a table with a bunch of courses - how would I change the code to narrow down the selection from every course to every course with the field db.Courses.myField = true?
var courses = from s in db.Courses
select s;
It's pretty simple ...
var courses = from s in db.Courses
where s.myField == true
select s;
Take a look at the data tutorials on asp.net.
Using Linq,
var courses = db.Courses.Where(s=>s.myField == true);