Inserting values in two tables using one controller in ASP.NET MVC4 - asp.net-mvc-4

I have two tables in my database the first one is librarybooklot where I want to keep record when new book is bought.
The next table is LibraryBookInventory where I want to keep record
of individual book.
Now what I want to do is when Book name A is bought in 1st lot and number of book is 10, the record should be entered in 1st table as well as second table, in second table 10 records need to entered for 10 books with different accession number, the accession number may be +1 of previous.
this is my function in LibBookLotDAO.cs
public static bool NewLibBookLotInformation(LibBookLotDTO LibBookLotDTO)
{
try
{
string sql = #"Insert into LibBookLot
(BookCode,Price,ReceivedOn,NumberOfBooks,Edition)
values (#BookCode,#Price,#ReceivedOn,#NumberOfBooks,#Edition ); ";
_dbm = new DBManager();
_dbm.CreateParameters(5);
_dbm.AddParameters(0, "#BookCode", LibBookLotDTO.BookCode);
_dbm.AddParameters(1, "#Price", LibBookLotDTO.Price);
_dbm.AddParameters(2, "#ReceivedOn", LibBookLotDTO.ReceivedOn);
_dbm.AddParameters(3, "#NumberOfBooks", LibBookLotDTO.NumberOfBooks);
_dbm.AddParameters(4, "#Edition", LibBookLotDTO.Edition);
int row = _dbm.ExecuteNonQuery(CommandType.Text, sql);
if (row == 0) return false;
else return true;
}
catch (Exception ex) { throw ex; }
finally { _dbm.Close(); }
}
and this is my code in LibBookLotController.cs
[HttpPost]
public ActionResult Add(LibBookLotDTO LibBookLotDTO)
{
if (LibBookLotDAO.NewLibBookLotInformation(LibBookLotDTO))
{
Session["INFO"] = "Successfully Added";
}
else
{
Session["ERROR"] = "Failed To Add";
}
return Redirect("Index?plugin=Library");
}
Plz someone help me, since I am new to asp.net

Related

Asp.net core api I can't enter more than one data on the same line

I have 3 tables, customer table has one to many relation with the other tables
a customer needs to add more than one address and phone number. With HTTPGET, I can pull data as follows, but I cannot perform crud operations.
enter image description here
GET:
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> GetCustomer(int id)
{
var customers = _context.Customers
.Include(customer => customer.Adresses)
.Include(customer=> customer.Phones)
.Where(customer => customer.CId == id)
.FirstOrDefault();
if (customers == null)
{
return NotFound();
}
return customers;
}
POST:
[HttpPost]
public async Task<ActionResult<Customer>> PostCustomer(Customer customer)
{
_context.Customers.Add(customer);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (CustomerExists(customer.CId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetCustomer", new { id = customer.CId }, customer);
}
I can't enter more than one data on the same line
I want to receive customer information (how many addresses and phone numbers) at the same time as a record, I don't know how to do this.

How to update a many to many relationship that has fields extra to its foreign keys

I’m implementing a project using asp.net core. Employing DB first approach and creating models in Visual studio, in SQl server I have two tables called API and Applicant that have many to many relationship and there is also their junction table called ApiApplicant.
Suppose these 3 tables has the following fields each:
Api: ID, name,date
Applicant:Id,name,type
ApiAppliant:Id,ApiID,ApplicantId,reqDate,gateId
My ApiApplicant table also has many to one relationship with another table called Gate.Gate table has the following fields:Id, name,
Now I want to know how can I update ApiApplicant table in my code.
I appreciate if anyone solve the above problem by showing me a sample relevant linq code.
It is not clear how you would like to update the junction table.You does not show any code.
Anyany, you could firstly remove all original records which you want to update and then add new records.
Below is a demo which updates an existing Api's related Applicants.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(long id, Api api)
{
if (id != api.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
//your new ApplicantIds
var newSelectedApplicantIds = new int[] { 3,4 };
var apiApplicants = new List<ApiApplicant>();
var apiAppList = await _context.ApiApplicant.Where(a => a.ApiID == api.Id).ToListAsync() ;
_context.RemoveRange(apiAppList);
foreach (var newid in newSelectedApplicantIds)
{
var item = new ApiApplicant()
{
ApiID = api.Id,
ApplicantId = newid,
};
apiApplicants.Add(item);
}
_context.AddRange(apiApplicants);
_context.Update(api);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
}
return RedirectToAction(nameof(Index));
}
return View(api);
}

After trying to update records I get "Value cannot be null"

After I want to update a user records and when I press Update button I get
An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null.
Parameter name: source
System.Linq.Enumerable.Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector)
Here is my function for updated user record:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, AppointmentDetailsViewModel objAppointmentVM)
{
if(ModelState.IsValid)
{
objAppointmentVM.Appointment.AppointmentDate = objAppointmentVM.Appointment.AppointmentDate
.AddHours(objAppointmentVM.Appointment.AppointmentTime.Hour)
.AddMinutes(objAppointmentVM.Appointment.AppointmentTime.Minute);
var appointmentFromDb = _db.Appointments.Where(a => a.Id == objAppointmentVM.Appointment.Id).FirstOrDefault();
appointmentFromDb.CustomerName = objAppointmentVM.Appointment.CustomerName;
appointmentFromDb.CustomerEmail = objAppointmentVM.Appointment.CustomerEmail;
appointmentFromDb.CustomerPhoneNumber = objAppointmentVM.Appointment.CustomerPhoneNumber;
appointmentFromDb.AppointmentDate = objAppointmentVM.Appointment.AppointmentDate;
appointmentFromDb.isConfirmed = objAppointmentVM.Appointment.isConfirmed;
if(User.IsInRole(SD.SuperAdminEndUser))
{
appointmentFromDb.SalesPersonId = objAppointmentVM.Appointment.SalesPersonId;
}
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(objAppointmentVM);
}
This function is for Drop-Down menu which display the Users from DB
public static IEnumerable<SelectListItem> ToSelectListItemString<T>(this IEnumerable<T> items, string selectedValue)
{
if(selectedValue == null)
{
selectedValue = "";
}
return from item in items
select new SelectListItem
{
Text = item.GetPropertyValue("Name"),
Value = item.GetPropertyValue("Id"),
Selected = item.GetPropertyValue("Id").Equals(selectedValue.ToString())
};
}
Any Idea where I made mistake ?
Maybe your table's column is set to not null.
Go to SQL Server and open your table. In the design table window, check the allow nulls checkbox.
In your item select one of the items is null, and LINQ is failing throwing an argument exception because you're trying to run a selector function on something that is null.

abas-ERP: Copy TN field into another TN field with edp/epi

I want to create an invoice and fill the field pftext (TN2) with the content of another TN2 field called ytdescription.
My problem is, that I always have the path of my textfield in pftext but not the content of my textfield.
1st try of edp header:
kunde;artex;pftext;mge
'M|ytkdnr';'M|ytartnr';'M|ytdescription';'M|ytmge'
2nd try:
kunde;artex;*pftext;mge;
'M|ytkdnr';'M|ytartnr';'M|ytdescription';'M|ytmge'
Of course I could create a T254 field and store the content of M|ytdescription in the new field, but then I am stuck to max 3000 chars for the content.
Many other tries followed but with no success :-(
Any help is highly appreciated!
I Don't know the options to do this per EDP, but there is a solution to do this per AJO:
public int run(DbContext dbContext, String[] args) {
/*
* Get the object to copy data from, in this case a customer with idno 70001
*/
String idno = "70001";
SelectionBuilder<Customer> selectionBuilder = SelectionBuilder.create(Customer.class);
selectionBuilder.add(Conditions.eq(Customer.META.idno, idno));
Customer customer = QueryUtil.getFirst(dbContext, selectionBuilder.build());
VendorEditor vendorEditor = null;
// Read the original content to a StringWriter
StringWriter originalFreeText = new StringWriter();
try {
customer.getFreeText(originalFreeText);
// Create a new object to write the values to. In example a Supplier
vendorEditor = dbContext.newObject(VendorEditor.class);
vendorEditor.setSwd("Searchword");
vendorEditor.setAddr("Vendor Name");
if (!originalFreeText.toString().equals("")) {
vendorEditor.setFreeText(new StringReader(originalFreeText.toString()));
}
vendorEditor.commit();
} catch (IOException e) {
dbContext.out().println(e.getMessage());
} finally {
if (vendorEditor != null) {
if (vendorEditor.active()) {
vendorEditor.abort();
}
}
}
return 0;
}

Combining two different jTables and adding button into jTable

I try to do for forum using java swing. Here are my codes for table :
public void SetUpJTable() {
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
String[] data = new String[4];
db.setUp("IT Innovation Project");
String sql = "Select topic_title,topic_description,topic_by from forumTopics WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
data[0] = resultSet.getString("topic_title");
data[1] = resultSet.getString("topic_description");
data[2] = resultSet.getString("topic_by");
tableModel.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
I set up this table to retrieve the topic details which user select certain thread from main page. And I set up another table to store for the replies by users. Here is it :
public void SetUpJTableComment() {
DefaultTableModel tableModel1 = (DefaultTableModel) jTableComment
.getModel();
String[] data = new String[3];
db.setUp("IT Innovation Project");
String sql = "Select reply_content,reply_by from forumReplies WHERE reply_topic = "
+ topicId + "";
ResultSet resultSet = null;
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_content");
data[1] = resultSet.getString("reply_by");
tableModel1.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
And this is how I set up the table :
private JTable getJTableComment() {
String header[] = { "Comment", "Reply By" };
if (jTableComment == null) {
jTableComment = new JTable() {
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
}
DefaultTableModel tableModel1 = (DefaultTableModel) jTableComment
.getModel();
tableModel1.setColumnIdentifiers(header);
jTableComment.getColumnModel().getColumn(0).setMinWidth(700);
jTableComment.getColumnModel().getColumn(0).setMaxWidth(800);
jTableComment.getColumnModel().getColumn(1).setMinWidth(97);
jTableComment.getColumnModel().getColumn(1).setMaxWidth(100);
jTableComment.getTableHeader().setFont(
new Font("Dialog", Font.PLAIN, 20));
jTableComment.getTableHeader().setForeground(Color.white);
jTableComment.getTableHeader().setBackground(new Color(102, 102, 102));
jTableComment.setRowHeight(50);
jTableComment.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTableComment.setFont(new Font("Dialog", Font.PLAIN, 18));
return jTableComment;
}
It works perfectly with two separating tables. I wonder if there is some way to combine both of these tables into one table? And how can I customize the table to make it look less-liked a table because my current one is just .. solid-table and my teacher asked me to improve it but I have no idea to do so. And I tried to add button into the table but I realized that I cannot add it from the try statement because that is is retrieve data from database directly. Any guides? Thanks in advance.
You can use SQL join construct and have one table with more columns:
select topic_title,topic_description,topic_by,
reply_content,reply_by
from forumTopics join forumReplies
on (forumTopics.topic_id=forumReplies.topic_id) WHERE topic_id = 1234
then build the model from the five column result set as you are already doing.
But surely if there is more than one reply to a forum topic, the topic part will be repeated in the table.
To make a table not to look like a table, try JTreeTable from Swing Labs maybe, it allows to have tree-like subsections, exactly that is required. It is not part of the system library however, you will need to download it. Some source code on how to just JTreeTable can be found here.
On how JTreeTable looks is Swing Labs, you can see in they web-startable demo. It also shows the code sample automatically.