Error inserting data from many method return lists to a database in c# - winforms

I need help here with part of my code so here it is:
I have 6 methods as you can see below that parse incoming data and then returns it as a list, so my issue is to send that list data to my database table SerialNumber, each method of the lists is a separate field that will fill a database column.
So for example the parse material will fill the database materiallookupcode column and the same for the others.
Here is an image of the database table
Here is the code of all 5 methods that reads the data and then returns it and I need this data send to my database
private List<string> ParseMaterial()
{
var materialList = new List<string>();
foreach (var material in _connection.GetBarcodeList())
{
materialList.Add(material.Substring(10, 5));
}
return materialList;
}
private List<string> ParseLot()
{
var lotList = new List<string>();
var establishmentList = GetEstablishmentCode();
foreach (var lot in _connection.GetBarcodeList())
{
if (establishmentList.Contains("038"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LoganSport038Property);
}
if (establishmentList.Contains("072"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LouisaCounty072Property);
}
if (establishmentList.Contains("086"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Madison086Property);
}
if (establishmentList.Contains("089"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Perry089Property);
}
if (establishmentList.Contains("069"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.StormLake069Property);
}
if (establishmentList.Contains("088"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Waterloo088Property);
}
if (establishmentList.Contains("265"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.GoodLetsVille265Property);
}
if (establishmentList.Contains("087"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.CouncilBluffs087Property);
}
if (establishmentList.Contains("064"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Sherman064Property);
}
}
return lotList;
}
private List<string> ParseSerialNumber()
{
var serialNumberList = new List<string>();
foreach (var serialNumber in _connection.GetBarcodeList())
{
serialNumberList.Add(serialNumber.Substring(36, 10));
}
return serialNumberList;
}
public List<string> ParseNetWeight()
{
var netWeightList = new List<string>();
foreach (var netWeight in _connection.GetBarcodeList())
{
netWeightList.Add(netWeight.Substring(22, 4));
}
return netWeightList;
}
public List<string> ParseGrossWeight()
{
var grossWeightList = new List<string>();
foreach (var grossWeight in _connection.GetBarcodeList())
{
grossWeightList.Add(grossWeight.Substring(22, 4));
}
return grossWeightList;
}
public List<string> FullBarcode()
{
var receiveFullBarcodeList = new List<string>();
foreach (var fullBarcode in _connection.GetBarcodeList())
{
receiveFullBarcodeList.Add(fullBarcode);
}
return receiveFullBarcodeList;
}
public List<string> GetEstablishmentCode()
{
var establishmentList = new List<string>();
foreach (var establishmentCode in _connection.GetBarcodeList())
{
establishmentList.Add(establishmentCode.Substring(36, 3));
}
return establishmentList;
}
The issue is here the button when clicking will read all 5 methods and send it to the database, I am sure the part where I making the list of variables to a string and the separator part is wrong so I need how is the correct way to add those list to each column of the database
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methodss
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var material = "";
var lot = "";
var net = "";
var gross = "";
var serial = "";
var fullSerial = "";
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
material = materialList[i];
lot = lotList[i];
net = netWeightList[i];
gross = grossWeightList[i];
serial = serialNumberList[i];
fullSerial = fullSerialNumberList[i];
}
// database table and columns
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = serial,
NetWeight = Convert.ToDecimal(net) / 100,
GrossWeight = Convert.ToDecimal(gross) / 100,
LotLookupCode = lot,
MaterialLookupCode = material,
FullSerialNumberLookupCode = fullSerial,
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
// insert to the database
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
Here is the SerialNumber domain class that represents a database table using a code first migration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarcodeReceivingApp.Core.Domain
{
// domain class, represents a database table in sql server using code
// first migration
public class SerialNumber
{
public int Id { get; set; }
public int LicensePlateId { get; set; }
public string FullSerialNumberLookupCode { get; set; }
public string SerialNumberLookupCode { get; set; }
public decimal NetWeight { get; set; }
public decimal GrossWeight { get; set; }
public string LotLookupCode { get; set; }
public string MaterialLookupCode { get; set; }
public DateTime CreatedSysDateTime { get; set; }
public DateTime ModifiedSysDateTime { get; set; }
public string CreatedSysUser { get; set; }
public string ModifiedSysUser { get; set; }
}
}
I search other places but could not find a good solution so far, so any help is appreciate it.

I was able to resolve my question, what I did is to assign all lists in a loop and then assign them to each column in the database.
But I am still searching for a better and more clean way to this solution
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methods - represents each field of the database column
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = materialList[i],
NetWeight = Convert.ToDecimal(netWeightList[i]) / 100,
GrossWeight = Convert.ToDecimal(grossWeightList[i]) / 100,
LotLookupCode = lotList[i],
MaterialLookupCode = materialList[i],
FullSerialNumberLookupCode = fullSerialNumberList[i],
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
}

Related

'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'InternID'.'

i'm new to ASP.NET MVC
so i've been trying for the last week to create a dropdown list from sql server to view a list of the interns Names
I've tried various & different ways to solve it, i checked most of the stackoverflow solutions related to the same issue, but all is leading to is the same error 'There is no ViewData item of type 'IEnumerable' that has the key 'InternID'.'
So my question is, What am i missing?
this is my main code
Controller
public ActionResult AddTask(Add_TaskModel Add_Task, HttpPostedFileBase postedFile) {
var InternList = entities.InternsTbls.ToList();
ViewBag.internList = new SelectList(InternList, "InternID","Name");
return View();}
View
#Html.DropDownListFor(m => m.InternID, ViewBag.internList as SelectList, "--Select The Intern", new { #class = "form-cotrnol"})
Model
public class Add_TaskModel
{
[Key]
public int TaskID { get; set; }
public string TaskTitle { get; set; }
public string TaskType { get; set; }
public string TaskDes { get; set; }
public string DueDate { get; set; }
public int SupID { get; set; }
public string TaskStatus { get; set; }
public int FileID { get; set; }
public int InternID { get; set; }
public string Name { get; set; }
}
Note- this one of many ways i tried, but same error.
Code 2
//var myList = new List<SelectListItem>();
//var list = entities.InternsTbls.ToList();
//var items = from g in list
// select new SelectListItem
// {
// Value = g.InternID.ToString(),
// Text = g.Name.ToString()
// };
//foreach (var item in items)
// myList.Add(item);
//ViewBag["In_List"] = myList;
Code 3
//string mainconn = ConfigurationManager.ConnectionStrings["TaskTrackerDBEntities"].ConnectionString;
//if (mainconn.ToLower().StartsWith("metadata="))
//{
// System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(mainconn);
// mainconn = efBuilder.ProviderConnectionString;
//}
//using (SqlConnection sqlconn = new SqlConnection(mainconn))
//{
// string sqlquery = "select * from [dbo].[InternsTbl]";
// using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
// {
// sqlconn.Open();
// SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
// DataSet ds = new DataSet();
// sda.Fill(ds);
// ViewBag.internname = ds.Tables[0];
// List<SelectListItem> getinternname = new List<SelectListItem>();
// foreach (System.Data.DataRow dr in ViewBag.internname.Rows)
// {
// getinternname.Add(new SelectListItem { Text = #dr["Name"].ToString(), Value = #dr["Name"].ToString() });
// }
// ViewData ["Interns"] = getinternname;
// //new SelectList(getinternname, "Name", "Name");
// sqlconn.Close();
// }
//}
Code 4
//TaskTrackerDBEntities entities1 = new TaskTrackerDBEntities();
//var getInternName = entities1.InternsTbls.ToList();
//SelectList list = new SelectList(getInternName, "InternID", "Name");
// ViewBag["InternListName"] = list;
//ViewBag.SubNames = new SelectList(entities1.InternsNames, "InternID", "Name");

Call Apex Method from the Custom Button

I created a Apex Class like
Public class test_Controller
{
Public test_Controller() { }
Public void send(set<id> oppIds)
{
List<Oppurtunity> OppLst =[Select Name from Opportunity where id IN: oppIds];
Private static string integration_key = 'abcd';
Private static string account_id = 'efgh';
Public string signer_email { get; set; }
Public string signer_name { get; set; }
Public string email_message { get; set; }
Public string output { get; set; }
Public string envelope_id { get; set; }
Public string error_code { get; set; }
Public string error_message { get; set; }
Private static string ds_server = 'callout:DocuSign_Legacy_Demo/api/3.0/dsapi.asmx';
Private static string trace_value = 'SFDC_004_SOAP_email_send'; // Used for tracing API calls
Private static string trace_key = 'X-ray';
Private DocuSignTK.APIServiceSoap api_sender = new DocuSignTK.APIServiceSoap();
configure_sender();
do_send(OppLst);
}
Private void configure_sender()
{
api_sender.endpoint_x = ds_server;
api_sender.inputHttpHeaders_x = new Map<String, String>();
String auth = '<DocuSignCredentials><Username>{!$Credential.Username}</Username>'
+ '<Password>{!$Credential.Password}</Password>'
+ '<IntegratorKey>' + integration_key + '</IntegratorKey></DocuSignCredentials>';
api_sender.inputHttpHeaders_x.put('X-DocuSign-Authentication', auth);
}
Private void do_send(List<Oppurtunity> OppurLst)
{
if (integration_key == 'xxx-xxxx-xxxx' ||
account_id == 'xxxx-xxxx-xxxx')
{
error_message = 'Please configure the Apex class DS_Recipe_Send_Env_Email_Controller with your integration key and account id.';
error_code = 'CONFIGURATION_PROBLEM';
return;
}
String file_contents = '<html><h1>Quote Document</h1>' + get_lorem(OppurLst)
+ '<p> </p>'
+ '<p>Signature: <span style="color:white;">signer1sig</span></p>'
+ '<p>Date: <span style="color:white;">signer1date</span></p></html>';
DocuSignTK.Document document = new DocuSignTK.Document();
document.ID = 1;
document.Name = 'Quote Document';
document.FileExtension = 'html';
document.pdfBytes = EncodingUtil.base64Encode(Blob.valueOf(file_contents));
DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
recipient.Email = '';
recipient.UserName = '';
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
DocuSignTK.Tab signHereTab = new DocuSignTK.Tab();
signHereTab.Type_x = 'SignHere';
signHereTab.AnchorTabItem = new DocuSignTK.AnchorTab();
signHereTab.AnchorTabItem.AnchorTabString = 'signer1sig'; // Anchored for doc 1
signHereTab.AnchorTabItem.XOffset = 8;
signHereTab.RecipientID = 1;
signHereTab.Name = 'Please sign here';
signHereTab.ScaleValue = 1;
signHereTab.TabLabel = 'signer1sig';
DocuSignTK.Tab dateSignedTab = new DocuSignTK.Tab();
dateSignedTab.Type_x = 'DateSigned';
dateSignedTab.AnchorTabItem = new DocuSignTK.AnchorTab();
dateSignedTab.AnchorTabItem.AnchorTabString = 'signer1date'; // Anchored for doc 1
dateSignedTab.AnchorTabItem.YOffset = -6;
dateSignedTab.RecipientID = 1;
dateSignedTab.Name = 'Date Signed';
dateSignedTab.TabLabel = 'date_signed';
DocuSignTK.Envelope envelope = new DocuSignTK.Envelope();
envelope.Subject = 'Please sign the Quote Document';
envelope.AccountId = account_id;
envelope.Tabs = new DocuSignTK.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignTK.Tab[2];
envelope.Tabs.Tab.add(signHereTab);
envelope.Tabs.Tab.add(dateSignedTab);
envelope.Recipients = new DocuSignTK.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignTK.Recipient[1];
envelope.Recipients.Recipient.add(recipient);
envelope.Documents = new DocuSignTK.ArrayOfDocument();
envelope.Documents.Document = new DocuSignTK.Document[1];
envelope.Documents.Document.add(document);
if (String.isNotBlank(email_message))
{
envelope.EmailBlurb = email_message;
}
try
{
DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id);
}
catch (CalloutException e)
{
System.debug('Exception - ' + e);
error_code = 'Problem: ' + e;
error_message = error_code;
}
}
Private Boolean no_error()
{
return (String.isEmpty(error_code));
}
Private static String get_lorem(List<Oppurtunity> OLst)
{
String lorem = 'Hello World';
return lorem;
}
}
And I am trying to call the send Method from the Apex from the Custom Button like
{!REQUIRESCRIPT("/soap/ajax/41.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/41.0/apex.js")}
sforce.apex.execute("test_Controller","send",{oppIds:"{!Opportunity.Id}"});
When I try to execute the button I get the following error message:
A Problem with the OnClick JavaScript for this button or link was
encountered: {faultcode:''soapenv:Client', faultstring:'No operation
available for request
{http://soap.sforce.com/schemas/package/test_Controller}send, please
check the WSDL for the service.'}'
I am new to Salesforce and Apex scripting. Any help is greatly appreciated.
Your method is expecting a list of Ids.
Public void send(set<id> oppIds)
So I am guessing that maybe you need to send it as an array?
sforce.apex.execute("test_Controller","send",{oppIds:["{!Opportunity.Id}"]});
You need to expose this method as a webservice and it needs to be static
webservice static void send(List<Id> oppIds) {
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_and_ajax.htm

DbContext.SaveChanges() does not save the changes to database

DbContext.SaveChanges() does not save the changes to database but updates the grid. The method that is not working as I would like is in bSave_Click method. How can I force it to update also database?
The code of the Windows Forms application is below:
namespace WinFormsApp
{
public partial class MainForm : Form
{
private List<User> users;
private List<UserType> userTypes;
private List<DataGridViewUserDTO> usersForGrid;
public MainForm()
{
InitializeComponent();
GetData();
PrepareGrid();
FillGrid();
}
public void GetData()
{
using (var dbContext = new DataInFileEntities())
{
userTypes = dbContext.UserTypes.ToList();
users = dbContext.Users.ToList();
usersForGrid = users.Select(x => new DataGridViewUserDTO() { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, UserTypeId = x.UserTypeId, CreatedById = x.CreatedById, Created = x.Created, EditedById = x.EditedById, Edited = x.Edited }).ToList();
}
}
public void FillGrid()
{
var gridBindingList = new BindingList<DataGridViewUserDTO>(usersForGrid);
gridBindingSource = new BindingSource(gridBindingList, null);
dgvUsers.DataSource = gridBindingSource;
}
public void PrepareGrid()
{
dgvUsers.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Id";
col.HeaderText = "Id";
col.Name = "Id";
col.ReadOnly = true;
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgvUsers.Columns.Add(col);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "FirstName";
col.HeaderText = "First Name";
col.Name = "FirstName";
dgvUsers.Columns.Add(col);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "LastName";
col.HeaderText = "Last Name";
col.Name = "LastName";
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn userTypeCol = new DataGridViewComboBoxColumn();
userTypeCol.DataPropertyName = "UserTypeId";
userTypeCol.HeaderText = "User Type";
userTypeCol.Name = "UserTypeId";
userTypeCol.DataSource = new BindingList<UserType>(userTypes);
userTypeCol.DisplayMember = "Name";
userTypeCol.ValueMember = "Id";
dgvUsers.Columns.Add(userTypeCol);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Edited";
col.HeaderText = "Edited";
col.Name = "Edited";
col.ReadOnly = true;
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn editedByCol = new DataGridViewComboBoxColumn();
editedByCol.DataPropertyName = "EditedById";
editedByCol.HeaderText = "Edited By";
editedByCol.Name = "EditedById";
editedByCol.DataSource = new BindingList<DataGridViewUserDTO>(usersForGrid);
editedByCol.DisplayMember = "Name";
editedByCol.ValueMember = "Id";
editedByCol.ReadOnly = true;
dgvUsers.Columns.Add(editedByCol);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Created";
col.HeaderText = "Created";
col.Name = "Created";
col.ReadOnly = true;
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn createdByCol = new DataGridViewComboBoxColumn();
createdByCol.DataPropertyName = "CreatedById";
createdByCol.HeaderText = "Created By";
createdByCol.Name = "CreatedById";
createdByCol.DataSource = new BindingList<DataGridViewUserDTO>(usersForGrid);
createdByCol.DisplayMember = "Name";
createdByCol.ValueMember = "Id";
createdByCol.ReadOnly = true;
dgvUsers.Columns.Add(createdByCol);
}
private void bSave_Click(object sender, EventArgs e)
{
using (var dbContext = new DataInFileEntities())
{
foreach (var row in usersForGrid)
{
var dbItem = dbContext.Users.Where(x => x.Id == row.Id).SingleOrDefault();
if (dbItem != null)
{
if (dbItem.FirstName != row.FirstName || dbItem.LastName != row.LastName || dbItem.UserTypeId != row.UserTypeId)
{
dbItem.FirstName = row.FirstName;
dbItem.LastName = row.LastName;
dbItem.UserTypeId = row.UserTypeId;
dbItem.Edited = DateTime.UtcNow;
dbItem.EditedById = 1;
}
}
}
dbContext.SaveChanges();
}
GetData();
FillGrid();
}
}
public class DataGridViewUserDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get { return FirstName + " " + LastName; }}
public byte UserTypeId { get; set; }
public Nullable<System.DateTimeOffset> Edited { get; set; }
public Nullable<int> EditedById { get; set; }
public System.DateTimeOffset Created { get; set; }
public int CreatedById { get; set; }
}
}

how to display files from ftp server to a local windows application gridview

i have uploaded my files to ftb server, now i want to display that files in my local windows application gridview
i want to display that files in datagridview.
public List<string> ListFiles()
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://ipaddress/Requests/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("username", "password");
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
files.Add(line.Split(new[] { ' ', '\t' }).Last());
}
}
return files;
}
}
}
following is the code on my load form.
FTPItility is my class in which listfiles is a method
FTPUtility obj = new FTPUtility();
List<string> strings = new List<string>();
dataGridViewRequest.DataSource = obj.ListFiles();
Here is the code you can use.
Here is code of FtpUtility:
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
And here is the code of form:
I have created an instance of FtpUtility and passed requiered parameters to it, then get the files and put it in a friendly list(Name, Path) and bind to grid:
private void Form1_Load(object sender, EventArgs e)
{
this.LoadFiles();
}
public void LoadFiles()
{
var ftp = new FtpUtility();
ftp.UserName = "username";
ftp.Password = "password";
ftp.Path = "ftp://address";
this.dataGridView1.DataSource = ftp.ListFiles()
.Select(x => new
{
Name = x, //Name Column
Path = ftp.Path + x //Path Column
}).ToList();
}

BindingList<> (master) with a composed BindingList<> (child) reference

I have a situation where a BindingList<> represents a collection of POCOs that have sub-collections of similar nature, Here is a sample code of two such POCOs and their respective lists:
The DirectoryTypePoco
public class DirectoryTypePoco : IBasePoco
{
public DirectoryTypePoco()
{
}
public DirectoryTypePoco(Int16 directoryTypeId, String directoryImplementation, String directoryDescription, DirectoryDefinitionPocoList directoryDefinition)
{
DirectoryTypeId = directoryTypeId;
DirectoryImplementation = directoryImplementation;
DirectoryDescription = directoryDescription;
DirectoryDefinition = directoryDefinition;
}
public Int16 DirectoryTypeId { get; set; }
public String DirectoryImplementation { get; set; }
public String DirectoryDescription { get; set; }
public DirectoryDefinitionPocoList DirectoryDefinition { get; set; }
public object GenerateEntity(GenericRepository repository, params object[] parameters)
{
var lastMaxEntityId = repository.GetQuery<DirectoryType>().Select(select => #select.DirectoryTypeId).DefaultIfEmpty().Max();
var newEntity = new DirectoryType
{
DirectoryTypeId = (short)(lastMaxEntityId + 1),
DirectoryImplementation = this.DirectoryImplementation,
DirectoryDescription = this.DirectoryDescription
};
return newEntity;
}
}
And the BindingList<DirectoryTypePoco>:
public class DirectoryTypePocoList : BindingList<DirectoryTypePoco>
{
public DirectoryTypePocoList()
{
using (var repository = new GenericRepository(new PWRDbContext()))
{
var query = repository.GetQuery<DirectoryType>();
foreach (var r in query)
{
Add(new DirectoryTypePoco(r.DirectoryTypeId, r.DirectoryImplementation, r.DirectoryDescription, new DirectoryDefinitionPocoList(r.DirectoryTypeId)));
}
}
}
public DirectoryTypePocoList(short directoryTypeId)
{
using (var repository = new GenericRepository(new PWRDbContext()))
{
var query = repository.GetQuery<DirectoryType>(where => where.DirectoryTypeId == directoryTypeId);
foreach (var r in query)
{
Add(new DirectoryTypePoco(r.DirectoryTypeId, r.DirectoryImplementation, r.DirectoryDescription, new DirectoryDefinitionPocoList(r.DirectoryTypeId)));
}
}
}
}
The second object: DirectoryDefinitionPoco
public class DirectoryDefinitionPoco : IBasePoco
{
public DirectoryDefinitionPoco()
{
}
public DirectoryDefinitionPoco(Int16 directoryTypeId, Byte parameterId, String parameterName, String parameterValidation, Boolean encryptionRequired, PocoChangeType changeType = PocoChangeType.None)
{
DirectoryTypeId = directoryTypeId;
ParameterId = parameterId;
ParameterName = parameterName;
ParameterDescription = parameterName;
ParameterRequired = false;
ParameterValidation = parameterValidation;
EncryptionRequired = encryptionRequired;
}
public Int16 DirectoryTypeId { get; set; }
public Byte ParameterId { get; set; }
public String ParameterName { get; set; }
public String ParameterDescription { get; set; }
public String ParameterValidation { get; set; }
public Boolean ParameterRequired { get; set; }
public Boolean EncryptionRequired { get; set; }
public object GenerateEntity(GenericRepository repository, params object[] parameters)
{
var masterId = (short) parameters[0];
var lastMaxEntityId = repository.GetQuery<DirectoryDefinition>(where => where.DirectoryTypeId == masterId).Select(select => #select.ParameterId).DefaultIfEmpty().Max();
var newEntity = new DirectoryDefinition
{
DirectoryTypeId = (short)parameters[0],
ParameterId = (byte)(lastMaxEntityId + 1),
ParameterName = this.ParameterName,
ParameterDescription = this.ParameterDescription,
ParameterValidation = this.ParameterValidation,
ParameterRequired = this.ParameterRequired,
EncryptionRequired = this.EncryptionRequired
};
return newEntity;
}
}
And BindingList<DirectoryDefinitionPoco>:
public class DirectoryDefinitionPocoList : BindingList<DirectoryDefinitionPoco>
{
public DirectoryDefinitionPocoList(short directoryTypeId)
{
using (var repository = new GenericRepository(new PWRDbContext()))
{
var query = repository.GetQuery<DirectoryDefinition>(where => where.DirectoryTypeId == directoryTypeId);
foreach (var r in query)
{
Add(new DirectoryDefinitionPoco(r.DirectoryTypeId, r.ParameterId, r.ParameterName, r.ParameterValidation, r.EncryptionRequired));
}
}
}
public List<DirectoryDefinition> GetSourceQuery()
{
List<DirectoryDefinition> result;
using (var repository = new GenericRepository(new PWRDbContext()))
{
result = repository.GetQuery<DirectoryDefinition>().ToList();
}
return result;
}
public List<DirectoryDefinition> GetSourceQuery(short directoryTypeId)
{
List<DirectoryDefinition> result;
using (var repository = new GenericRepository(new PWRDbContext()))
{
result = repository.GetQuery<DirectoryDefinition>(where => where.DirectoryTypeId == directoryTypeId).ToList();
}
return result;
}
}
On the form, I load the data into the grid through a BindingSource component. The child rows are added properly and the data is valid.
Here is the issue: I'm able to add new DirectoryTypePoco but when try to add a DirectoryDefinitionPoco, in the code, the the DirectoryDefinitionPocoobject that I get has a zero for it's parent object. In the above picture, the Test5.dll234 is a DirectoryTypePoco with DirectoryTypeId = 8 and all child under it are ok except the new one I create. What am I suppose to do to make sure I have Master-Child relation in this case?
Ok. It seems that there are two thing I should have noticed in my design.
The individual child Poco needs to know the parent Poco through a reference.
The DevExpress Grid has methods that allow for retrieving the attached data to a parent row while in the child view' particular row.
The first part is straightforwards: add a new property in the child poco of parent poco type.
This however, in my case, doesn't solve my issue as when I visually add a new row on the grid, the default constructor is invoked and it takes no parameters and hence the parent poco reference will remain NULL and the Ids (numeric) will be defaulted to 0
The second point helped fix my issue completely. I was able to conjure up an extension method for the XtraGrid's GridView as follows:
public static class DevExpressGridHelper
{
public static IBasePoco GetPocoFromSelectedRow(this BaseView view)
{
return (IBasePoco)view.GetRow(((GridView)view).FocusedRowHandle);
}
public static IBasePoco GetParentPocoFromSelectedRow(this GridView view)
{
if (view.ParentView !=null)
{
// return (IBasePoco)(view.ParentView).GetRow(((GridView)(view.ParentView)).FocusedRowHandle);
return (IBasePoco)((GridView)view.ParentView).GetFocusedRow();
}
return null;
}
}
And used it as follows:
private void GridMain_Level_1_RowUpdated(object sender, RowObjectEventArgs e)
{
var view = sender as GridView;
if (view == null)
{
return;
}
var pocoObject = e.Row as DirectoryDefinitionPoco;
if (pocoObject == null)
{
return;
}
var parentPocoObject = view.GetParentPocoFromSelectedRow();
if (parentPocoObject == null)
{
return;
}
if (view.IsNewItemRow(e.RowHandle))
{
Create(pocoObject, parentPocoObject);
}
else
{
Update(pocoObject);
}
}

Resources