How to find out the parent page Id from IPageStructure? (Composite C1) - c#

Is this the best way to get the parentId of a page from the IPageStructure in Composite C1 within a UserControl ?
string pPageId = SitemapNavigator.CurrentPageId.ToString();
Guid parentId = connection.Get<IPage>().Where(p => p.Id == new
Guid(pPageId)).First().GetParentId();
I do use the present pageId as a string, which helps in the above case seeing as .First() can't be used on Guid.

Take a look at the SitemapNavigator instance class you can grab from DataConnection - when you get the data bound instance it gives you access to the current page in form of a PageNode class from which you can access parent, child pages. You also have access to titles, descriptions etc.
// General (verbose) example - getting parent page ID
using (var connection = new DataConnection())
{
var currentPageNode = connection.SitemapNavigator.CurrentPageNode;
var parentPageNode = currentPageNode.ParentPage;
var parentPageId = parentPageNode.Id;
}
If you are doing this from a Razor Function there is already a data connection available (this.Data) so the above can be written like this:
// Razor example - getting parent page ID
var parentPageId = Data.SitemapNavigator.CurrentPageNode.ParentPage.Id;

One option is just to rely 100% on the standard asp.net way using the SiteMapProvider functionality.
Get a specific node like this: var node = SiteMap.CurrentProvider.FindSiteMapNodeByKey("...").
Get the Parent node like this: var parentNode = node.ParentNode.
Get its id like this: var id = parentNode.Key

Related

How to set List child element with for each If it is empty initially?

I have Ilist to get all Offer from repository using entity framework core. Also I have service model OfferResponseModel which includes
OfferRequestModel as reference. I used mapster to bind entity model to service model. However it only set first child. Now I want to bind it manually. I created "offers" with the size of "Offer". When I try to use foreach loop, I cannot set "offers" child element.Because it has no elements. So, I can I solve this.
var offer = await _unitOfWork.Offers.GetAllOffer();
if (offer == null)
throw ServiceExceptions.OfferNotFound;
var results = new List<OfferResponseModel>(offer.Count);
results.ForEach(c => { c.Offer = new OfferRequestModel(); });
int i = 0;
foreach(var result in results)
{
result.Offer.User = Offer[i].User.Adapt<UserResponseModel>();
result.Offer.Responsible = Offer[i].Responsible.Adapt<EmployeeResponseModel>();
result.CreatedDate = Offer[i].CreatedDate;
result.ModifiedBy = Guid.Parse(Offer[i].UpdatedBy);
result.Active = Offer[i].Status;
result.Offer = Offer[i].Offer;
result.Offer.User.Company = Offer[i].Company.Adapt<CompanyModel>();
i++;
}
I created "offers" with the size of "Offer".
No, you created it with that capacity. It's still an empty list. It's not clear to me why you're trying to take this approach at all - it looks like you want one OfferResponseModel for each entry in offer, directly from that - which you can do with a single LINQ query. (I'm assuming that offer and Offer are equivalent here.)
var results = Offer.Select(o => new OfferResponseModel
{
Offer = new OfferRequestModel
{
User = o.User.Adapt<UserResponseModel>(),
Responsible = o.Responsible.Adapt<EmployeeResponseModel>()
},
CreatedDate = o.CreatedDate,
ModifiedBy = Guid.Parse(o.UpdatedBy),
Active = o.Status
}).ToList();
That doesn't set the Offer.User.Company in each entry, but your original code is odd as it sets the User and Responsible properties in the original Offer property, and then replaces the Offer with Offer[i].Offer. (Aside from anything else, I'd suggest trying to use the term "offer" less frequently - just changing the plural to "offers" would help.)
I suspect that with the approach I've outlined above, you'll be able to work out what you want and express it more clearly anyway. You definitely don't need to take the "multiple loops" approach of your original code.
One thing you have left out is the type of the offer variable that is referenced in the code. But I am thinking you need to do something along these lines:
if (offer == null)
throw ServiceExceptions.OfferNotFound;
var results = offer.Select(o => new OfferResponseModel
{
Offer = new OfferRequestModel
{
User = o.User.Adapt<UserResponseModel>(),
Responsible = o.Responsible.Adapt<EmployeeResponseModel>(),
...
}
}).ToList();
Select basically loops through any items in offer and "converts" them to other objects, in this case OfferResponseModel. So inside select you simply new up an OfferResponseModel and directly sets all the properties you need to set.
You need using System.Linq; for Select to be available.

How do I get all elements of a certain category, type and familiy in revit

I have a function where I would like to get all elements belonging to a certain category, type and family. I have their names as strings and would like to obtain the actual elements that meet the criteria.
I have tried a bit with the following:
internal static void getElemetWithId(Document doc,string catName, string famname, string symbname)
{
Category category=null;
foreach (var cat in doc.Settings.Categories){
if (((Category)cat).Name.Contains(catName))
{
category = (Category)cat;
break;
}
}
HashSet<Element> elements = new HashSet<Element>();
elements.AddRange(GetFilteredElementCollector(doc, new ElementRetrievalOptions())
.OfCategory(category).WhereElementIsElementType(famname).ToElements());
}
However this doesn't work as OfCategory does not accept a Category as a argument (it does work for a builtInCategory) and WhereElementIsElementType does not seem to accept any argument.
A possible input for this function would be document, "Doors" , "M_Single-Flush" , "0915 x 2134mm"
You should look at the Revit SDK, http://usa.autodesk.com/adsk/servlet/index?siteID=123112&id=16777469, and go through some of the sample code. You can also look at Jeremy's page: http://thebuildingcoder.typepad.com, and Harry's page: https://boostyourbim.wordpress.com for more sample code.
You should use the FilteredElementCollector Class to find all the Elements you'd be looking for:
FilteredElementCollector allInstances = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)‌​).Where(q => (q as FamilyInstance).Symbol.Name == symbname);
You can get all the elements belonging to the certain category using FilteredElementCollector class. Pass the name of the certain family name in the query and you will get all the elements of required family and type. I have tried this on Revit 2019 recently.
List<Element> listOfElements = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).WhereElementIsElementType()
.ToElements().Where(e => e.Name == elementName).ToList<Element>();
ElementId symbolId = listOfElements[0].Id;
FamilyInstanceFilter familyInstanceFilter= new FamilyInstanceFilter(doc, symbolId);
IList<Element> familyInstances = new FilteredElementCollector(doc).WherePasses(familyInstanceFilter).ToElements();

Getting Href property with anglesharp linq query

I am trying to understand how to use anglesharp.
I made this code based on the example (https://github.com/AngleSharp/AngleSharp):
// Setup the configuration to support document loading
var config = Configuration.Default.WithDefaultLoader();
// Load the names of all The Big Bang Theory episodes from Wikipedia
var address = "http://store.scramblestuff.com/";
// Asynchronously get the document in a new context using the configuration
var document = await BrowsingContext.New(config).OpenAsync(address);
// This CSS selector gets the desired content
var menuSelector = "#storeleft a";
// Perform the query to get all cells with the content
var menuItems = document.QuerySelectorAll(menuSelector);
// We are only interested in the text - select it with LINQ
var titles = menuItems.Select(m => m.TextContent).ToList();
var output = string.Join("\n", titles);
Console.WriteLine(output);
This works as expected but now I want to access the Href property but I am unable to do this:
var links = menuItems.Select(m => m.Href).ToList();
When I look in the debugger I can see in results view that the HtmlAnchorElement enumerable object has a Href property but I am obviously not trying to access it right.
None of the examples in the documentation show a property being accessed so I guess it's something so simple that doesn't need to be shown but I am not seeing how to do it.
Can anyone show me how I should be accessing a html property with angle sharp?
edit:
This works when I cast it to the correct type
foreach (IHtmlAnchorElement menuLink in menuItems)
{
Console.WriteLine(menuLink.Href.ToString());
}
How would I write that as a Linq statement like the titles variable?
Alternative to har07's answer:
var menuItems = document.QuerySelectorAll(menuSelector).OfType<IHtmlAnchorElement>();
You can cast to IHtmlAnchorElement as follow :
var links = menuItems.Select(m => ((IHtmlAnchorElement)m).Href).ToList();
or using Cast<IHtmlAnchorElement>() :
var links = menuItems.Cast<IHtmlAnchorElement>()
.Select(m => m.Href)
.ToList();
im a bit late to this topic, but you can use
string link = menuItem.GetAttribute("href");
or this if its a list of items
List<string> menuItems = LinkList.Select(item => item.GetAttribute("href")) .ToList();

Create a query using LINQ to entities with 1:N relation

I know it's not something unusual to make such kind of queries but I think I get lost so I seek help. I have to tables with relation 1:N and to make it more clear I'll post a print screen from the management studio :
I am working on a asp.net mvc 3 project and I need to make a view where all Documents will be shown (and some filter and stuff, but I think that is irrelevant for this case). I need the data from the table Documents and only one specific record for each document from the DocumentFields table. This record is the record holding the name of the Document and it's uniqueness is DocumentID == Docmuents.Id, DocumentFields.RowNo == 1 and DocumentsFields.ColumnNo == 2. This is unique record for every Document and I need to get the FieldValue from this record which actually holds the Name of the Document.
I am not very sure how to build my query (maybe using JOIN) and I also would like to make my view strongly typed passing a model of type Documents but I'm not sure if it's possible, but I think depending on the way the query is build will determine the type of the model for the view.
I believe what you want is something like this:
var results =
from d in dbContext.Documents
join df in dbContext.DocumentFields
on new { d.Id, RowNo = 1, ColumnNo = 2 } equals
new { Id = df.DocumentId, df.RowNo, df.ColumnNo }
select new
{
Document = d,
DocumentName = df.FieldValue
};
Of course if you set up navigation properties, you can just do this:
var results =
from d in dbContext.Documents
let df = d.DocumentFields.First(x => x.RowNo == 1 && x.ColumnNo == 2)
select new
{
Document = d,
DocumentName = df.FieldValue
};

How do I extract this LinqToSql data into a POCO object?

with my Repository classes, I use LinqToSql to retrieve the data from the repository (eg. Sql Server 2008, in my example). I place the result data into a POCO object. Works great :)
Now, if my POCO object has a child property, (which is another POCO object or an IList), i'm trying to figure out a way to populate that data. I'm just not too sure how to do this.
Here's some sample code i have. Please note the last property I'm setting. It compiles, but it's not 'right'. It's not the POCO object instance .. and i'm not sure how to code that last line.
public IQueryable<GameFile> GetGameFiles(bool includeUserIdAccess)
{
return (from q in Database.Files
select new Core.GameFile
{
CheckedOn = q.CheckedOn.Value,
FileName = q.FileName,
GameFileId = q.FileId,
GameType = (Core.GameType)q.GameTypeId,
IsActive = q.IsActive,
LastFilePosition = q.LastFilePosition.Value,
UniqueName = q.UniqueName,
UpdatedOn = q.UpdatedOn.Value,
// Now any children....
// NOTE: I wish to create a POCO object
// that has an int UserId _and_ a string Name.
UserAccess = includeUserIdAccess ?
q.FileUserAccesses.Select(x => x.UserId).ToList() : null
});
}
Notes:
Database.Files => The File table.
Database.FilesUserAccess => the FilesUserAccess table .. which users have access to the GameFiles / Files table.
Update
I've now got a suggestion to extract the children results into their respective POCO classes, but this is what the Visual Studio Debugger is saying the class is :-
Why is it a System.Data.Linq.SqlClient.Implementation.ObjectMaterializer<..>
.Convert<Core.GameFile> and not a List<Core.GameFile> containing the POCO's?
Any suggestions what that is / what I've done wrong?
Update 2:
this is what i've done to extract the children data into their respective poco's..
// Now any children....
UserIdAccess = includeUserIdAccess ?
(from x in q.FileUserAccesses
select x.UserId).ToList() : null,
LogEntries = includeUserIdAccess ?
(from x in q.LogEntries
select new Core.LogEntry
{
ClientGuid = x.ClientGuid,
ClientIpAndPort = x.ClientIpAndPort,
// ... snip other properties
Violation = x.Violation
}).ToList() : null
I think that all you need to do is to put another Linq query in here:
q.FileUserAccesses.Select(x => x.UserId).ToList()
i.e. You want to select data from the FileUserAccess records - which I'm assuming are Linq to SQL classes, so to do this you can have something like:
(from fua in q.FileUserAccesses
select new PocoType
{
UserID = fua.UserID,
Name = fua.User.UserName // Not sure at this point where the name comes from
}).ToList()
That should get you pointed in the right direction at least.
What is the type of UserIdAccess? How is it not 'right'? Are you getting the 'wrong' data? if so have you checked your database directly to make sure the 'right' data is there?

Categories