LINQ Query to get Column Headers in Silverlight - c#

I am working on a Silverlight application using a WCF service where I need to get all the Column Headers from a specific table. I have been trying to write a LINQ query to do this, but so far I have not been able to get it to work correctly. I have not found very much information pertaining to this. I have found the following information, but I have had difficulties connecting to my data.
http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/4856/#ReadAndPostComment
So far I have tried the following...This will not compile due to DataContext needing a parameter and that is where I am stuck.
public List<string> GetColumnHeaders()
{
DataContext context = new DataContext();
List<string> columnList = new List<string>();
var dataModel = context.Mapping;
foreach (var r in dataModel.GetTables())
{
if (r.TableName.Equals("table1", StringComparison.InvariantCultureIgnoreCase))
{
foreach (var c in r.RowType.DataMembers)
{
columnList.Add(c.MappedName);
}
}
}
return columnList;
}
Instead of using DataContext context = new DataContext();
I tried the following, but I know the problem is the same.
var dataModel = new AttributeMappingSource()
.GetModel(
typeof(RepositoryBase<HBS_SondesEntities>
));

Here is my best attempt at a solution, its hard to really understand what you have tried/written.
public List<string> GetColumnHeaders(){
List<string> columnList = new List<string>();
using (SondesEntities context = new HBS_SondesEntities()){
foreach (var r in context.Mapping.GetTables()){
if (r.TableName
.Equals("table1", StringComparison.InvariantCultureIgnoreCase)) {
foreach (var c in r.RowType.DataMembers){
columnList.Add(c.MappedName);
}
}
}
}
return columnList;
}
Assuming I didn't fat finger something here is the same code using linq.
public List<string> GetColumnHeaders(){
List<string> columnList = new List<string>();
using (SondesEntities context = new HBS_SondesEntities()){
var query = (
context.Mapping.GetTables()
.Where(t=>t.TableName
.Equals(
"table1",
StringComparison.InvariantCultureIgnoreCase)
)
).SelectMany(x=>x.RowType.DataMembers);
columnList = query.Select(m=>m.MappedName).ToList()
}
return columnList;
}

This might help:
http://jesseliberty.com/2009/08/13/linq-for-silverlight-developers/
I'm not sure what you mean by table, but if its a datagrid, the link should help.

Related

Returning list basic c sharp

I am new to programming and been tasked to grab data from an API.
The issue I have is basic C# returning the contents of brakeparts. I'm passing the part id and obtaining a list of brake parts correctly. I need to assign the partid to the list, which seems to work when adding a breakpoint, however how do I return this list? Return brake parts doesn't work. They could be potentially many parts it returns whilst looping I need it to append to the Parts list. I know its probably something quite simple but I can't get my head around returning back the whole list. I've tried brakeparts.AddRange(brakeparts); This doesn't work too.
private static List<Parts> getBrakeparts(List<int> partids)
{
var restClient = new RestClient("https://example.example.net/api");
foreach (var partid in partids)
{
var returnreq = new RestRequest($"/brakeparts/{partid}/ ", Method.GET);
var res = restClient.Execute(returnreq);
Parts brakeparts = JsonConvert.DeserializeObject<Parts>(res.Content);
brakeparts.PartID = partid;
}
return brakeparts;
}
As I understand, you're simply trying to return a list of parts which you want to fill with the Parts breakparts that you deserialized from the Json response.
Simply create a List<Parts> instance and add the breakparts to it in the loop.
It could look like the following.
private static List<Parts> getBrakeparts(List<int> partids)
{
var restClient = new RestClient("https://example.example.net/api");
List<Parts> parts = new List<Parts>();
foreach (var partid in partids)
{
var returnreq = new RestRequest($"/brakeparts/{partid}/ ", Method.GET);
var res = restClient.Execute(returnreq);
Parts brakeparts = JsonConvert.DeserializeObject<Parts>(res.Content);
brakeparts.PartID = partid;
parts.Add(brakeparts);
}
return parts;
}

List of all different IfcEntities in IfcFile

Summary
i have an ifc file with different IfcEntities like IfcWall, IfcBeam, IfcColumn etc.
i'm struggling to find a way to list all different entities in this ifc file
the list should contain every ifcentity occurence just once {"IfcWall", "IfcColumn", "IfcBeam", ...}
debugged also the code to see if there was any property which held the value i was searching for
My Code:
i've used the xbim Essential quick start guide
googled also
looked through the issues on github
using (var model = IfcStore.Open(_FilePath))
{
var allInstances = model.Instances;
var testList = model.Instances.OfType<IIfcBuildingElement>();
var nameList = new List<string>();
var objTypeList = new List<string>();
foreach (var item in testList)
{
var objType = item.IsTypedBy;
var firstObjType = objType.ElementAt(0);
var relType = firstObjType.RelatingType;
var name = item.Name;
nameList.Add(name);
}
}
What i expect:
simple list with all IfcEntities
like {"IfcWall", "IfcColumn", "IfcBeam", ...}
Would appreciate any help
thanks to #martin1cerny
the answer was quite simple:
var testList = model.Instances.OfType<IIfcBuildingElement>().GroupBy(e => e.GetType());
issue/question on github

ASP.NET MVC get list of database entries with a certain property

I am trying to get a list of all entries in my database that a certain one of their bool properties is false. I used a foreach loop to get the list but I was hoping to find a more optimized way to do this.
this is the controller code I used:
private DataBaseEntities db = new DataBaseEntities();
public ActionResult ApproveUsersList()
{
List<ApproveUserViewModel> unapprovedUsers = new List<ApproveUserViewModel>();
foreach (User dbUser in db.Users)
{
if (!dbUser.Approved)
{
ApproveUserViewModel model = new ApproveUserViewModel();
unapprovedUsers.Add(model);
}
}
return View(unapprovedUsers.ToList());
}
Why not Linq?
var _unapprovedUsers= unapprovedUsers.Where(m => !m.Approved).ToList();
var found = db.Users.Where(w => !w.Approved).Select(s => new ApproveUserViewModel { Approved = s.Approved,... }).ToList();
unapprovedUsers.AddRange(found);

Printing useful output with Log4net in Application_Error and LINQ queries

I'm new to this stuff but what I'm trying to do is filter the log4net log I've bungled into Application_Error by some particular bits of information, such as HTTP_USER_AGENT REQUEST TYPE CONTENT_TYPE HTTP_REFERER.
The code I have so far is:
string[] vars = {"IP address", "X-Forwarded-For", "HTTP_USER_AGENT","REQUEST TYPE","CONTENT_TYPE","HTTP_REFERER"};
var param = Request.Params;
var paramEnum = param.GetEnumerator();
while (paramEnum.MoveNext())
{
foreach (var paramVar in vars.Where(paramVar => paramVar == paramEnum.Current.ToString()))
{
Log.Error("\nparam:" + paramVar);
}
}
But it looks ugly and moreover I think I'm not on the right track in terms of a succinct LINQ query, especially using both a while and foreach loop.
I'm new to LINQ as I say and resharper created the LINQ for me - if you feel I'm lacking in certain areas please let me know what I'd need to further my understanding of collections/querying.
Is this the most performant way of doing things, or am I on the wrong track altogether?
It's better to iterate through vars instead
foreach (var paramVar in vars)
{
var value = Request.Params.Get(paramVar);
if (!string.IsNullOrEmpty(value))
{
Log.Error("\nparam:" + paramVar);
}
}
or using LINQ
var query = from paramVar in vars
let value = Request.Params.Get(paramVar)
where !string.IsNullOrEmpty(value)
select paramVar;
foreach (var paramVar in query)
{
Log.Error("\nparam:" + paramVar);
}

List<DataRow> to custom List<Model>

I have used the following code:
ManageUser userObj = new ManageUser();
List<StoreUserList> storeList = new List<StoreUserList>();
StoreUserList sl = new StoreUserList();
foreach (var items in userObj.GetStoreUserList(Username, Password))
{
sl.UserName = items[0].ToString();
sl.EmailId = items[1].ToString();
sl.FirstName = items[2].ToString();
sl.LastName = items[3].ToString();
sl.BadLoginCount = Convert.ToInt32(items[4]);
sl.ManagerName = items[5].ToString();
storeList.Add(sl);
}
StoreUserList is my Model in which i have defined all the properties.
ManagerUser is the class which will return the data in the form of List<DataRow>.
So, i order to populate the a generic list of my model type i have used the above code, to do it.
But, as you can see i have hard-coded all the values to bind the model and then added that model to the list. I just wanted to know that is there some other way to do it or some magic way to do it in easy?
If you can modify ManageUser.GetStoreUserList a little to return DataTable instead of List<DataRow>, then you can use Automapper, which can map IDataReader implementations to a collection of objects.
Suppose you have this entity type:
class User
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can convert DataTable to the List<User> this way:
// sample data table
var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Rows.Add(1, "John");
dataTable.Rows.Add(2, "Mary");
dataTable.Rows.Add(3, "Peter");
dataTable.Rows.Add(4, "Sarah");
// fill users list
using (var reader = dataTable.CreateDataReader())
{
var users = Mapper.Map<IDataReader, List<User>>(reader);
}
You can use automapper project for this. See more details here:
How to use AutoMapper to map a DataRow to an object in a WCF service?
And here: Map RowDataCollection to DTO using AutoMapper
I think your code will not add multiple StoreUserList object in the list but will add only 1 object with the value as last datarow. What you need to do is
ManageUser userObj = new ManageUser();
List<StoreUserList> storeList = new List<StoreUserList>();
StoreUserList sl = null;
foreach (var items in userObj.GetStoreUserList(Username, Password))
{
sl = new StoreUserList();
sl.UserName = items[0].ToString();
sl.EmailId = items[1].ToString();
sl.FirstName = items[2].ToString();
sl.LastName = items[3].ToString();
sl.BadLoginCount = Convert.ToInt32(items[4]);
sl.ManagerName = items[5].ToString();
storeList.Add(sl);
}
Otherwise i dont see any problem in your code.

Categories