I create an new Contractor object "gc" that calls a method GetContractor() to return all the properties. The results it is returning is correct, however the "gc" object shows all "NULL". I assume I doing something incorrectly in my aspx.cs page?
aspx.cs
protected void fvWasteCollected_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert")){
ValidationSummaryWasteDetail.ValidationGroup = "WasteReceivedDetail";
if (IsValid) {
odsMRWWasteCollectedDetail.InsertParameters["WasteTypeId"].DefaultValue = ddlWasteCollectedType.SelectedValue;
odsMRWWasteCollectedDetail.InsertParameters["DisposalMethodId"].DefaultValue = ddl_disposalMethod.SelectedValue;
Contractor gc = new Contractor();
gc.GetContractor(2);
var contractorName = gc.MRWContractorName;
}
}
}
.cs
public class Contractor
{
public Contractor GetContractor(int MRWContractorId)
{
using (DataAccessLINQDataContext db = new DataAccessLINQDataContext())
{
var result = db.MRWContractors.Where(c => c.MRWContractorId == MRWContractorId).Select(c => new Contractor
{
MRWContractorId = c.MRWContractorId,
MRWContractorName = c.MRWContractorName,
MRWContractorAddress = c.MRWContractorAddress,
MRWContractorCity = c.MRWContractorCity,
MRWContractorStateCode = c.MRWContractorStateCode,
MRWContractorZipCode = c.MRWContractorZipCode,
MRWContractorPhone = c.MRWContractorPhone,
MRWContractorFax = c.MRWContractorFax,
MRWContractorEmail = c.MRWContractorEmail
}).SingleOrDefault();
return result;
}
}
public int MRWContractorId { get; set; }
public string MRWContractorName { get; set; }
public string MRWContractorAddress { get; set; }
public string MRWContractorCity { get; set; }
public string MRWContractorStateCode { get; set; }
public int? MRWContractorZipCode { get; set; }
public string MRWContractorPhone { get; set; }
public string MRWContractorFax { get; set; }
public string MRWContractorEmail { get; set; }
}
You are loosing the value of gc when you dont assign it to something.
Try this instead:
var contractor = gc.GetContractor(2);
var contractorName = contractor.MRWContractorName;
You are creating one empty instance of the object that is only used to call the GetContractor method. The GetContractor method creates another instance that contains data, which is returned, but you just throw that instance away and expect the data to be available in the first instance that never got populated.
Make the GetContractor method static so that you don't need an instance to call it:
public static Contractor GetContractor(int MRWContractorId)
Now you can call the method to get that instance that contains the data, without first creating an empty instance:
Contractor gc = Contractor.GetContractor(2);
string contractorName = gc.MRWContractorName;
Related
I am trying to make my code more compromised, and use overall less, however currently I'm running into the problem of not being able to send a list of Objects sorted by linq as a parameter.
the problem is in this part of the code:
List<Afspraken> dataAfspraken = new List<Afspraken>();
public Form1()
{
InitializeComponent();
fillListsForLinq();
loadReceptionData();
}
private void fillListsForLinq()
{
dataAfspraken = data.getAfsprakenData();
//here it fills the list with Afspraken objects
}
private void loadReceptionData()
{
private void loadReceptionGrid
var receptionToFinnish =
(from AFspraken in dataAfspraken
where Afspraken.factuur_betaald == true && Afspraken.volledig_afgerond == false
join Users in dataUsers on Afspraken.gekoppelde_klant equals Users.id
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
}).ToList();
changeDataviewReception(receptionToFinnish);
}
private void changeDataviewReception(List<Object> listData)
{
dgvReceptionData.DataSource = listData
}
the Afspraken class looks like this
public class Afspraken
{
public int id { get; set; }
public bool bevestigd { get; set; }
public DateTime datum { get; set; }
public int gekoppelde_klant { get; set; }
public int gekoppelde_monteur { get; set; }
public string benodigde_hadelingen { get; set; }
public decimal totaalprijs { get; set; }
public bool klaar { get; set; }
public bool factuur_betaald { get; set; }
public bool volledig_afgerond { get; set; }
public string opmerkingen { get; set; }
}
How do I get receptionToFinnish as a parameter into changeDataviewReception?
receptionToFinnish will be a list full of objects of an anonymous type. But your method requires a List<object>. This is now allowed since a list is not a variant type.
Say for example that you have a list of bananas and want to give it to someone that wants a list of fruits. This will not work since that other person might try to add an orange to the list of bananas.
To fix this, cast the values to object explicitly, for example:
select new
{
Id = Afspraken.id,
Klant = Users.gebruikersnaam,
Betaald = Afspraken.factuur_betaald,
Afgerond = Afspraken.volledig_afgerond
} as object
This is my first ever post to SO and am very new to C# with most of my IT experience in databases. I am starting to look at some of our code and would like to understand how I would use this class and it methods for resusability purposes.
public class FileCreator
{
public string Territory { get; set; }
public string CV { get; set; }
public string AdDate { get; set; }
public string Category { get; set; }
public string Advertiser { get; set; }
public string Brand { get; set; }
public decimal SumOfSpend { get; set; }
public decimal SumOfVolume { get; set; }
public string Spots { get; set; }
public string PageNumber { get; set; }
internal static List<FileCreator> Create(DataSet data)
{
var result = new List<FileCreator>();
if (data.Tables.Count > 0)
{
result = Create(data.Tables[0]);
}
return result;
}
public static List<FileCreator> Create(DataTable dataTable)
{
var result = new List<FileCreator>();
foreach (DataRow row in dataTable.Rows)
{
result.Add(Create(row));
}
return result;
}
private static FileCreator Create(DataRow row)
{
var fileCreator = new FileCreator();
fileCreator.Territory = (row["Territory"].ToString());
fileCreator.CV = row["CV"].ToString();
fileCreator.AdDate = row["Ad_date"].ToString();
fileCreator.Category = row["Category"].ToString();
fileCreator.Advertiser = row["Advertiser"].ToString();
fileCreator.Brand = row["Brand"].ToString();
fileCreator.SumOfSpend = Convert.ToDecimal(row["SumOfSpend"].ToString());
fileCreator.SumOfVolume = Convert.ToDecimal(row["SumOfVolume"].ToString());
fileCreator.Spots = row["Spots"].ToString();
fileCreator.PageNumber = row["Page Number"].ToString();
return fileCreator;
}
}
Why not just create a new instance of a datatable i.e. var dt = new Datatable()?
I must be missing the point of this approach. How will I benefit from this approach when I normally just create multiple datatables?
Go easy. It's my first post 🙂
Thank you
The point of this is get a strongly typed class instead of relying on hard-coded strings to get the data out and then casting everything to the type you are expecting. Instead, its taking data from the Datatable and transforming it to a "Dto" (Data Transfer Object) where you know all the properties (columns) that exist and their types because they are explicitly declared. There is no guessing! :)
While the given approach here works, I hope it is more for legacy sake. It is more efficient to simply create this Dto class directly instead of creating a Datatable and then mapping it.
i have 2 model classes
public class ProductOptionRequest
{
public string Name { set; get; }
public List<ProductValuesRequest> productValues { get; set; }
}
public class ProductValuesRequest
{
public string ValueName { get; set; }
}
public class ProductOptionValue
{
public int OptionId { get; set; }
public String ValueName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and wrote one bs method and passing parameter value as value names. but I'm unable to get those values in a list object as productValues. May I know the solution, please.
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
request.productValues = new List<ProductValuesRequest>();
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOptionValue res = new ProductOptionValue();
res.ValueName = valueRequest.ValueName;
object response = await productOptionValueRepository.InsertAsync(res, true);
}
}
In the first line of your method, you are replacing the productValues property of request object with a new empty list, :
request.productValues = new List<ProductValuesRequest>();
Therefore, in foreach loop, you are iterating on an empty list.
Remove the first line and see if you still have any issues.
You are assigning an emplty list to productValues as
request.productValues = new List() and trying to iterate the empty list.
I want to Find Username by userId
this code snippet working
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,
and this once not working in following controller class
Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,
this is my model classes
public class DiscussionVM
{
public int Disussion_ID { get; set; }
public string Discussion_Title { get; set; }
public string Discussion_Description { get; set; }
public Nullable<System.DateTime> Discussion_CreateDate { get; set; }
public string Discussion_CreateBy { get; set; }
public string Comment_User { get; set; }
public IEnumerable<CommentVM> Comments { get; set; }
}
public class CommentVM
{
public int Comment_ID { get; set; }
public Nullable<System.DateTime> Comment_CreateDate { get; set; }
public string Comment_CreateBy { get; set; }
public string Comment_Description { get; set; }
}
this is whole controller class
public ActionResult Discussion_Preview()
{
int Discussion_ID = 1;
var discussion = db.AB_Discussion.Where(d => d.Discussion_ID == Discussion_ID).FirstOrDefault();
var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID);
DiscussionVM model = new DiscussionVM()
{
Disussion_ID = discussion.Discussion_ID,
Discussion_Title = discussion.Discussion_Name,
Discussion_Description = discussion.Discussion_Name,
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,
Discussion_CreateDate = discussion.CreatedDate,
Comments = comments.Select(c => new CommentVM()
{
Comment_ID = c.Comment_ID,
Comment_Description = c.Comment_Discription,
Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,
Comment_CreateDate = c.CreatedDate
})
};
return View(model);
}
Getting following error
Method 'Project.Models.AspNetUser Find(System.Object[])' declared on type 'System.Data.Entity.DbSet1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery1[Project.Models.AspNetUser]'
Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName
Works because discussion is an in-memory object because you are executing a query by calling FirstOrDefault on it:
var discussion = db.AB_Discussion.Where(d => d.Discussion_ID == Discussion_ID).FirstOrDefault();
On the other hand in the following statement:
db.AspNetUsers.Find(c.CreatedBy).UserName
c is not queried yet because
db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID)
returns an IQueriable and not the actual collection of comments
The easiest way to fix it is to bring all your comments into memory (since you are anyway need them all) :
var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID).ToList();
In my common.cs class I have the below declarations for a list based on a class:
public static List<edbService> edb_service;
public class edbService
{
public string ServiceID { get; set; }
public string ServiceName { get; set; }
public string ServiceDescr { get; set; }
public string ServiceInterval { get; set; }
public string ServiceStatus { get; set; }
public string ServiceUrl { get; set; }
public string SourceApplication { get; set; }
public string DestinationApplication { get; set; }
public string Function { get; set; }
public string Version { get; set; }
public string userid { get; set; }
public string credentials { get; set; }
public string orgid { get; set; }
public string orgunit { get; set; }
public string customerid { get; set; }
public string channel { get; set; }
public string ip { get; set; }
}
I have a public method to populate the list from xml data files declared like this in the same class (common.cs):
#region PublicMethods
public List<edbService> populateEDBService(string xmlDataFile)
{
try
{
XElement x = XElement.Load(global::EvryCardManagement.Properties.Settings.Default.DataPath + xmlDataFile);
// Get global settings
IEnumerable<XElement> services = from el in x.Descendants("Service")
select el;
if (services != null)
{
edb_service = new List<edbService>();
foreach (XElement srv in services)
{
edbService edbSrv = new edbService();
edbSrv.ServiceID = srv.Element("ServiceID").Value;
edbSrv.ServiceName = srv.Element("ServiceName").Value;
edbSrv.ServiceDescr = srv.Element("ServiceDescr").Value;
edbSrv.ServiceInterval = srv.Element("ServiceInterval").Value;
edbSrv.ServiceStatus = srv.Element("ServiceStatus").Value;
edbSrv.ServiceUrl = srv.Element("ServiceUrl").Value;
foreach (XElement ServiceHeader in srv.Elements("ServiceHeader"))
{
edbSrv.SourceApplication = ServiceHeader.Element("SourceApplication").Value;
edbSrv.DestinationApplication = ServiceHeader.Element("DestinationApplication").Value;
edbSrv.Function = ServiceHeader.Element("Function").Value;
edbSrv.Version = ServiceHeader.Element("Version").Value;
foreach (XElement ClientContext in ServiceHeader.Elements("ClientContext"))
{
edbSrv.userid = ClientContext.Element("userid").Value;
edbSrv.credentials = ClientContext.Element("credentials").Value;
edbSrv.orgid = ClientContext.Element("orgid").Value;
edbSrv.orgunit = ClientContext.Element("orgunit").Value;
edbSrv.customerid = ClientContext.Element("customerid").Value;
edbSrv.channel = ClientContext.Element("channel").Value;
edbSrv.ip = ClientContext.Element("ip").Value;
}
}
edb_service.Add(edbSrv);
}
}
}
catch (Exception ex)
{
/* Write to log */
Common.logBuilder("CustomerCreate : Form --> CustomerCreate <--", "Exception", Common.ActiveMQ,
ex.Message, "Exception");
/* Send email to support */
emailer.exceptionEmail(ex);
}
return edb_service;
}
but the problem is, in my calling class when I try to have a list returned from this method, it is not found - I get a compile error that an object reference is required.
I am trying to call it like this:
Common.edbService edb_service = Common.populateEDBService("CardUpdate.xml");
and I get the below error:
An object reference is required for the non-static field, method, or property 'EvryCardManagement.Common.populateEDBService(string)'
What am I doing wrong?
I would like to have a generic method that can be called from several classes (which run async after being instantiated by background workers on my form)
You can try making your method as static.
public static List<edbService> populateEDBService(string xmlDataFile)
{
//Your code here
....
}
Now you can call this method from all the other classes by using common.populateEDBService();
You need either to create the class static, or to create an object to call it.
class edbService { }
public static void Main() {
//this is error
edbService.populateEDBService("");
//this is correct
edbService s = new edbService();
s.populateEDBService("");
}
The last line in my example shows the object reference required by the compiler. The s variable here is the object reference.
Are there any missing values in your XML? The.Value property won't work if the value is missing. So if ServiceID is missing then srv.Element("ServiceID").Value; will cause an error. You can get it to return an empty string for missing values, for example, by instead using (string)srv.Element("ServiceID");