How do I grab something like Name using the ID?
Code:
//PROPRIEDADES
public int Id
{
get { return id; }
set
{
if (value < 0)
throw new Exception("ID inválido");
id = value;
}
}
public string Username { get; set; }
public string Password { get; set; }
public string Nome_Completo { get; set; }
public string Email { get; set; }
...
CollectionBase:
public string idToName(int id)
{
foreach (Pessoa p in this.List)
{
if (p.Id == id)
{
return p.Nome_Completo;
}
}
return null;
}
Final result:
TABLE A: https://imgur.com/a/NuHG0sN NEED TO GET THE NOME_COMPLETO
TABLE B: https://imgur.com/a/xrf1GAU
Me trying to get the NAME FROM ID:
private void LoadListView()
{
lstvEncomendas.Items.Clear();
foreach (Encomenda en in brain.encomendas)
{
string[] subitems = new string[] { en.Id.ToString(), brain.pessoas.idToName(en.PessoaID)/*en.PessoaID.ToString()*/, en.Morada, en.Telefone, en.Descricao, en.Attachfile.ToString(), en.VoluntarioID.ToString(), en.Estado};
ListViewItem lviItem = new ListViewItem(subitems);
lstvEncomendas.Items.Add(lviItem);
}
}
Related
I have an error
Severity Code Description Project File Line Suppression State Error CS0161 'RateController.GetRateById(long)': not all code paths return a value shenoywebapi D:\shenoystudio\shenoywebapi\Controllers\RateController.cs 192 Active
[Route("api/rate/getrate/{id}")]
public Rate GetRateById(long id)
{
var result = new Rate();
var dsRate = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateById", new SqlParameter("#Id", id));
if (dsRate.Tables[0].Rows.Count > 0)
{
DataRow row = dsRate.Tables[0].Rows[0];
result = new Rate
{
Id = Convert.ToInt64(row[0]),
wefDate = Convert.ToDateTime(row[1]),
//ProductRates =new List<ProductRate>() { new ProductRate() { Rate = Convert.ToInt64(row[2])} }
};
}
var ProductRatesList = new List<ProductRate>();
var dsRateDetails = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateDetailsById", new SqlParameter("#RateId", id));
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
}
This is my rate model
{
public class Rate
{
public long Id { get; set; }
public DateTime wefDate { get; set; }
public IList<ProductRate> ProductRates { get; set; }
}
}
This is my ProductRate Model
namespace shenoywebapi.Models
{
public class ProductRate
{
public long Id { get; set; }
public string SerialNumber { get; set; }
public long ProductId { get; set; }
public string ProductName { get; set; }
public string Unit { get; set; }
public decimal Rate { get; set; }
}
}
Only on this part you have a return statement:
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
if the code goes not to this if statement, there is no return statement
if (dsRateDetails.Tables[0].Rows.Count > 0)
you should add this before the last curly brace of the method:
return result;
We are two classes :
First class is:
public class Team
{
public Team()
{
UsersMyTeam = new List<User>();
ID = "";
}
public string ID { set; get; }
public string NameTeam { set; get; }
public List<User> UsersMyTeam { set; get; }
public override string ToString()
{
return "Team";
}
}
Second class is :
public class User
{
public string ID { get; set; }
public string Name { get; set; }
public string LName { get; set; }
public string IsActive { get; set; }
public string Date { get; set; }
public string TeamID { get; set; }
public override string ToString()
{
return "User";
}
}
I use of class by code:
protected void btnTest_Click(object sender, EventArgs e)
{
DALTableIO DTIO = new DALTableIO();
List<Team> listUser = new List<Team>();
Team myTeam = new Team();
myTeam.ID = "426f63a7-7f42-485f-8407-67c680f9e358";
foreach (object item in DTIO.GetAll(myTeam))
{
listUser.Add((Team)item);
}
}
I have a class named DALTableIO that get values from database and Put them into object of class:
public class DALTableIO:DALBase
{
public List<object> GetAll(object MyClass)
{
SqlDataReader re = ExecuteReader(CommandType.StoredProcedure, string.Concat("GetAll", MyClass.ToString()), new SqlParameter[]{
});
List<object> list = new List<object>();
try
{
while (re.Read())
{
Type t=MyClass.GetType();
// creat new Class
object item = Activator.CreateInstance(t);
// start Fill Class
foreach (PropertyInfo property in MyClass.GetType().GetProperties())
{
//when we have property of list<object>
if (property.PropertyType.Name.ToLower() == "list`1")
{
//how can i create list<users>
//how can i create user
//how can i do list<users> =getAll(user);
//how can i do property=list<users>;
continue;
}
if (property.PropertyType.Name.Substring(0, 3) == "Int")
item.GetType().GetProperty(property.Name).SetValue(item, int.Parse(re[property.Name].ToString()));
else
switch (property.PropertyType.Name)
{
case "String":
item.GetType().GetProperty(property.Name).SetValue(item, re[property.Name].ToString());
break;
case "Decimal":
item.GetType().GetProperty(property.Name).SetValue(item, decimal.Parse(re[property.Name].ToString()));
break;
}
}
list.Add(item);
}
if (!re.IsClosed)
re.Close();
re.Dispose();
SqlConnection.ClearAllPools();
return list;
}
catch (Exception err)
{
throw new Exception( err.Message);
}
}
Tell me how can I fill users list<>. I want send one class user to getAll() for give all users. thanks.
Try the following code, it may help you.
if (property.PropertyType.Name.ToLower() == "list`1")
{
if (property.PropertyType.Name.ToLower() == "list`1")
{
var type = property.PropertyType;
var it = type.GetGenericArguments()[0];
var users = Activator.CreateInstance(type); // list of user
var user = Activator.CreateInstance(it); //user
user.GetType().GetProperty("ID").SetValue(user, 1, null);
user.GetType().GetProperty("Name").SetValue(user, "Name1", null);
var add = type.GetMethod("Add");
add.Invoke(users, new[] { user });
}
}
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}
Hello I have one List of data and I want to remove a data from list but my code return a error when I am deleting a value one time here is my code and classes
The error is
Collection was modified; enumeration operation may not execute. removing list item
boko_data_json ListAvailableData = Newtonsoft.Json.JsonConvert.DeserializeObject<boko_data_json>(json);
foreach (var item in ListAvailableData.data)
{
string PDFPath = item.downloadpdfpath;
string filename = lastPart.Split('.')[0];
int result = obj.getfile(filename);
if (result == 1)
{
ListAvailableData.data.Remove(item);
}
}
listnameAvailable.ItemsSource = ListAvailableData.data;
} public class boko_data_json
{
// public string Type { get; set; }
public List<Book> data{ get; set; }
public string downloadpdfpath { get; set; }
public string book_name { get; set; }
}
public class Book
{
public int book_id { get; set; }
public string book_name { get; set; }
public string issue_date { get; set; }
public string description { get; set; }
public string status { get; set; }
public string month { get; set; }
public int price { get; set; }
private string forprice { get { return "TL"; } }
public string showprice { get { return price +" "+forprice; } }
private string staticpath { get { return "http://dergiapp.net/"; } }
public string book_image { get; set;}
public string imagepath {get {return staticpath+book_image; }}
public string pdf_path { get; set; }
public string staticpdfpath { get { return "http://dergiapp.net/mobile/test.php?file="; } }
public string downloadpdfpath { get { return staticpdfpath + pdf_path; } }
private string Privewpadf1 { get { return "http://dergiapp.net/zip/p"; } }
private string Privewpadf2 { get { return ".zip"; } }
public string privewpdf { get { return Privewpadf1 + book_id + Privewpadf2; } }
public string download_status { get; set; }
}
You should use the List.RemoveAll() method to remove all the elements that match a particular predicate, as this code snippet illustrates:
List<string> strList = new List<string>()
{
"One",
"Two",
"RemoveMe",
"Three",
"Four"
};
strList.RemoveAll(element => element == "RemoveMe");
This removes all elements matching "RemoveMe".
If the predicate is quite complicated, you can put it into a separate method, like so:
strList.RemoveAll(shouldBeRemoved);
...
private static bool shouldBeRemoved(string element)
{
// Put whatever complex logic you want here,
// and return true or false as appropriate.
return element.StartsWith("Remove");
}
You can't remove an item from your list while your looping through its items. You're modifying the content of collection while there's a loop to enumerate it.
This is the reason of Collection was modified; enumeration operation may not execute. removing list item.
You should do the following:
boko_data_json copyList = ListAvailableData;
foreach (var item in ListAvailableData.data)
{
string PDFPath = item.downloadpdfpath;
string filename = lastPart.Split('.')[0];
int result = obj.getfile(filename);
if (result == 1)
{
copyList.data.Remove(item);
}
}
listnameAvailable.ItemsSource = copyList.data;
Another approach would be this:
boko_data_json itemsToRemove = new boko_data_json();
foreach (var item in ListAvailableData.data)
{
string PDFPath = item.downloadpdfpath;
string filename = lastPart.Split('.')[0];
int result = obj.getfile(filename);
if (result == 1)
{
itemsToRemove.data.Add(item);
}
}
foreach (var itemToRemove in itemsToRemove)
{
ListAvailableData.data.Remove(itemToRemove);
}
I am new on Dapper.NET kinda stuck on this. I am trying to fill a class which has another class from multirow result set.
# DATABASE SP >
SELECT b.BuildingId, b.BuildingName, b.Wood, b.Food, b.Stone, b.Gold FROM UserBuildings ub, Buildings b WHERE b.BuildingId = ub.BuildingId AND UserId = #UserId
# CODE >
using (IDbConnection connection = OpenConnection())
{
List<Building.Building> buildings = new List<Building.Building>();
var multi = connection.QueryMultiple<Building.Building, Resource.Resource>("UserBuildingGet", new { UserId = UserId }, commandType: CommandType.StoredProcedure).ToList();
building.Resource = multi.Read<Resource.Resource>().Single();
return building;
}
# CLASSES >
public class Building
{
private int _BuildingId;
private string _BuildingName;
private Resource.Resource _Resource;
public int BuildingId
{
get { return _BuildingId; }
set { _BuildingId = value; }
}
public string BuildingName
{
get { return _BuildingName; }
set { _BuildingName = value; }
}
public Resource.Resource Resource
{
get { return _Resource; }
set { _Resource = value; }
}
public Building(int BuildingId, string BuildingName, Resource.Resource Resource)
{
this.BuildingId = BuildingId;
this.BuildingName = BuildingName;
this.Resource = Resource;
}
}
public class Resource
{
private int _Wood;
private int _Food;
private int _Stone;
private int _Gold;
public int Wood
{
get { return _Wood; }
set { _Wood = value; }
}
public int Food
{
get { return _Food; }
set { _Food = value; }
}
public int Stone
{
get { return _Stone; }
set { _Stone = value; }
}
public int Gold
{
get { return _Gold; }
set { _Gold = value; }
}
public Resource(int Wood, int Food, int Stone, int Gold)
{
this.Wood = Wood;
this.Food = Food;
this.Stone = Stone;
this.Gold = Gold;
}
}
Your code needs to define what separates the data. Use the splitOn parameter of GridReader.Read
var buildings = new List<Building.Building>();
using (IDbConnection connection = OpenConnection())
{
using(var reader = connection.QueryMultiple("UserBuildingGet",
new { UserId = UserId },
commandType: CommandType.StoredProcedure))
{
var building = reader.Read<Building.Building,
Resource.Resource,
Building.Building>
((b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
return buildings;
See: Is there a way of using MultiMapping and QueryMultiple together in Dapper?
Sample:
public class Building
{
public int BuildingId { get; set; }
public string BuildingName { get; set; }
public Resource Resource { get; set; }
public override string ToString()
{
return string.Format("Id: {0} Name: {1} Resource: {2}", BuildingId, BuildingName, Resource);
}
}
public class Resource
{
public int Wood { get; set; }
public int Food { get; set; }
public int Stone { get; set; }
public int Gold { get; set; }
public override string ToString()
{
return string.Format("Wood: {0} Food: {1} Stone {2} Gold {3}", Wood, Food, Stone, Gold);
}
}
var sql = #"SELECT 1 AS BuildingId, 'tower' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold
UNION ALL
SELECT 2 AS BuildingId, 'shed' AS BuildingName, 1 AS Wood, 1 AS Food, 1 AS Stone, 1 AS Gold";
var buildings = new List<Building>();
using(var connection = GetOpenConnection())
{
using(var reader = connection.QueryMultiple(sql))
{
var building = reader.Read<Building, Resource, Building>(
(b, r) => { b.Resource = r; return b; }, splitOn: "Wood");
buildings.AddRange(building);
}
}
foreach(var building in buildings)
{
Console.WriteLine(building);
}