Datastructures problem in asp.net/c# - asp.net

I have a e-commerce web application which allows users to buy software components in my website. I'm retrieving the invoice number and the software component title that was bought by the user from UserTransactionHistory table in sql server. I'm storing them in arraylist with the help of a SoftwareTitles Class
public class SoftwareTitles
{
string softwareTitle;
string invoiceNumber;
public SoftwareTitles(string softwareTitle, string invoiceNumber)
{
this.softwareTitle = softwareTitle;
this.invoiceNumber = invoiceNumber;
}
string InvoiceNumber
{
get
{
return this.invoiceNumber;
}
}
string SoftwareTitle
{
get
{
return this.softwareTitle;
}
}
}
}
And I'm adding this class to arraylist in this manner.
ConnectionToSql con1 = new ConnectionToSql();
string connectionString = con1.ConnectionStringMethod();
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd2 = new SqlCommand("SelectionOfSoftwareTitles", sqlConnection);
cmd2.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.HasRows)
{
while (dr2.Read())
{
String softwareTitle = (String)dr2[0];
String invoiceNumber = (String)dr2[1];
softwareTitlesArray.Add(new SoftwareTitles(softwareTitle, invoiceNumber));
int i = 0;
}
}
sqlConnection.Close();
dr2.Close();
But when I want to retrieve all the software titles that are associated with a certain Invoice number. I'm not able to do it.
Am i doing it properly ?? Is arraylist appropriate data structure for such operation ?? How should I do it ?

I would personally use a non-generic list object.
To declare:
List<Software> softwareTitles= New List<Software>();
And the object software:
if (dr.HasRows)
{
while (dr.Read())
{
string title = dr["TITLE_COLUMN"];
int invoice = dr["INVOICE_COLUMN"];
Software s = new Software();
s.Title = title;
s.Invoice = invoice;
softwareTitles.add(s);
}
}
and then you can traverse through the list using a simple loop and counter like, softwareTitles(i) or you can even use LINQ to accomplish whatever you want to do.
e.g.
for (i=0; i<softwareTitles.Count;i++)
{
if (softwareTitles[i].Invoice==213)
{
Console.WriteLine(softwareTitles[i].Title);
}
}
Somthing like that. Sorry I am using VB.NET lately, so my C# has become rusty. But it seems correct

Use Generic List Collection to add the Objects and Linq to Query the Records.

Related

How to add data to associative table in asp.net core

I am new to asp.net core. I am building a web application for book management. I have a table called Author and books. Being a many to many relationships I made an associative entity that consists of the bookId and authorId. When I try to create I am able to create author and book. I successfully added the author and book to the database.
My author class looks like this
public class Author
{
private int _ID
private string _Name;
public string ID {
get { return _ID; }
set { _ID = value; }
public string Name {
get { return _Name; }
set { _Name = value; }
}
My book class is
public class Author
{
private int _ID
private string _Name;
private string _Title;
public string ID {
get { return _ID; }
set { _ID = value; }
}
public string Title {
get { return _Name; }
set { _Name = value; }
}
public string Name {
get { return _Name; }
set { _Name = value; }
}
I have a data access called db.cs to help to create the book and author in database.
public static int AddAuthor(Author A)
{
int renum = -1;
SqlConnection conn = null;
conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand comm = new SqlCommand("sproc_AuthorAdd", conn);
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#Name", A.Name);
comm.Parameters.AddWithValue("#Title", a.Title);
SqlParameter output = new SqlParameter();
output.ParameterName = "#AuthorID";
output.DbType = System.Data.DbType.Int32;
output.Direction = System.Data.ParameterDirection.Output;
comm.Parameters.Add(output);
int affect = comm.ExecuteNonQuery();
renum = affect;
c.ID = (int)output.Value;
I have done the same for books as well. I want to fill out the association table as well when the user filled out a book and author using their ID. I tried to do various things like using a cookie to pass data. But I cannot store data. Any kind of help is appreciated. Thanks in advance.
I'm not really sure I understand your last code snippet, but if you're having issues managing your many-to-many relationship between Books and Authors, have you considered just using Entity Framework Core?
Instead of writing a bunch of code that accesses your database, you just create models of your tables (similar to the classes you have defined above), and it handles the many-to-many relationship for you. The code to query for Authors and/or Books could then look as simple as:
using (var db = new dbContext())
{
var books = db.Books
.Where(b => b.ID > 1234)
.OrderBy(b => b.Title)
.ToList();
}
And creating a new Book or Author would be similarly simple:
using (var db = new dbContext())
{
var book = new Book { ID = 1234, Title = "Some Title", Name = "Some Name" };
db.Books.Add(book);
db.SaveChanges();
}
You might have to reimplement a bunch of things to take advantage of Entity Framework Core in your app, but it sounds like it would save you time in the long run.

ASP.NET Core 2.1 API not taking parameter

I am trying to pass a parameter from my API, but it does not seem to be taking it. I have a lastName (eventually will be replaced with a unique id) that I want to pass, which will ultimately route to a profile view or that person.
Here is my API Controller:
public class GetInquiryController : BaseController
{
private GetInquiry manager;
public GetInquiryController(IConfiguration config) : base(config)
{
manager = new GetInquiry(config);
}
[HttpGet]
[Route("api/[controller]")]
public IEnumerable<InquiryModel> Get(string lastName)
{
return manager.GetInquiriesByUser(lastName);
}
}
And my logic for my stored procedure that gets the last name
public class GetInquiry
{
private readonly IConfiguration configuration;
public GetInquiry(IConfiguration config)
{
configuration = config;
}
public IEnumerable<InquiryModel> GetInquiriesByUser(string lastName)
{
string ApplicationDB = configuration.GetConnectionString("ApplicationDB");
List<InquiryModel> lstinquiry = new List<InquiryModel>();
using (SqlConnection con = new SqlConnection(ApplicationDB))
{
SqlCommand cmd = new SqlCommand("spGetInquiriesByUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter lastNameParameter = cmd.Parameters.Add("lastName", SqlDbType.Char, 10);
lastNameParameter.Value = lastName;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
InquiryModel inquiry = new InquiryModel();
//inquiry.FormID = rdr["FormID"].ToString();
inquiry.firstName = rdr["firstName"].ToString();
inquiry.lastName = rdr["lastName"].ToString();
inquiry.SID = rdr["SID"].ToString();
inquiry.email = rdr["email"].ToString();
inquiry.phone = rdr["phone"].ToString();
inquiry.email = rdr["email"].ToString();
inquiry.employer = rdr["street"].ToString();
inquiry.city = rdr["city"].ToString();
inquiry.state = rdr["state"].ToString();
inquiry.zip = rdr["zip"].ToString();
inquiry.date = rdr["date"].ToString();
inquiry.comment = rdr["comment"].ToString();
lstinquiry.Add(inquiry);
}
con.Close();
}
return lstinquiry;
}
}
}
I am using VUE.js and calling my API
methods: {
editItem(lastName) {
let id = lastName
this.$http.get('http://localhost:61601/api/GetInquiry/', {
id: lastName
}),
I have tried using my logic without IEnumerable, which i didn't think will make a difference in this case.
I guess the good thing is that I am getting,
"SqlException: Procedure or function 'spGetInquiriesByUser' expects parameter '#lastName', which was not supplied"
when type my API route into the browser, but when I add the lastName to the end of my route or Postman, I get a blank page.
Hope this makes sense, please let me know if i need to provide more detail and if someone can point me into the right direction!
You need to define from where your lastName parameter should be read.
If you want to read it from the route, use FromRoute attribute
[HttpGet("{lastName}")] //api/GetInquiry/yourlastname
public IEnumerable<InquiryModel> Get([FromRoute]string lastName)
{
return manager.GetInquiriesByUser(lastName);
}
If you want to read it from the querystring, use FromQuery attribute
[HttpGet] //api/GetInquiry?lastName=yourlastname
public IEnumerable<InquiryModel> Get([FromQuery]string lastName)
{
return manager.GetInquiriesByUser(lastName);
}
Note: Above solution works when moving the [Route("api/[controller]")] ontop of the GetInquiryController class.
Update
When you added your vue.js api call it makes more sence why this is not working, you are actually calling the lastName parameter by the id name. Changing your id prop to lastName would work with above
methods: {
editItem(lastName) {
this.$http.get('http://localhost:61601/api/GetInquiry/', {
lastName: lastName
}),

How to move Resultset curser via button click, and display data in textfields?

So, I'm creating a desktop banking application. It's nothing too serious, I'm just trying to practice and get better.
// Method I use to get a connection. I know this works.
public static Connection getConnection() throws SQLException {
String sCon = "jdbc:sqlite:banking.sqlite";
Connection connection = DriverManager.getConnection(sCon);
return connection;
}
.
..
...
.....Other code
Method I attempt to use to create and manipulate the data in the result set.
The problem I believe starts here. With this code, I am only able to return one row of the result set and only the last row.
public static Customers getAccounts(Customers c) {
String query = "select RowCount, Customers.Account_Number, "
+ "Customers.First_Name, Last_Name, Address, "
+ "Phone_Number, Accounts.Balance "
+ "from Customers "
+ "join Accounts ";
try (Connection connection = getConnection();
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
c.setFirstName(fName);
c.setLastName(lName);
c.setAddress(address);
c.setPhoneNumber(phone);
c.setAccountNumber(accNum);
c.setBalance(balance);
}
return c;
} catch (SQLException e) {
System.err.println(e);
}
return null;
}
}
Here is the method that is linked to the button I use to perform what I'm trying to attempt. It's part of the Controller class. I believe this method is also a part of the problem. Any ideas? Thank for all you guys do. This website is a real benefit to the community.
public void next() {
Customers c = new Customers();
DBInterface.getAccounts(c);
firstNameF2.setText(c.getFirstName());
lastNameF2.setText(c.getLastName());
addressF2.setText(c.getAddress());
phoneNumberF2.setText(c.getPhoneNumber());
accNumF.setText(c.getAccountNumber());
balanceF.setText(c.getBalance());
}
If you are expecting to get multiple Customers objects, then you definitely should return a list of that.
public static List<Customers> getAccounts() {
// Whatever you originally had...
final List<Customers> ret = new ArrayList<>();
while (rs.next()) {
String fName = rs.getString("First_Name");
String lName = rs.getString("Last_Name");
String address = rs.getString("Address");
String phone = rs.getString("Phone_Number");
String accNum = rs.getString("Account_Number");
String balance = rs.getString("Balance");
final Customers cust = new Customers();
cust.setFirstName(fName);
cust.setLastName(lName);
cust.setAddress(address);
cust.setPhoneNumber(phone);
cust.setAccountNumber(accNum);
cust.setBalance(balance);
ret.add(cust);
}
return ret;
}
I have removed the part about passing in the instance of Customers (which would have ended up as passing in List<Customers>. If you really need to do that, you can add back in and do all the necessary checks.

How to get live database change notifications in ASP.Net using MSSQL

Im designing a logistics website in ASP.Net, customers are able to place order, orders will inserted to database.
I want, when a new order inserted into database, it automatically send a notification to employee for new order.
the question is , how to manipulate the following code to get live notifications ,when database changes?
public class FreightOrderList
{
int customerID = 0;
public int CustomerID
{
get { return customerID; }
set { customerID = value; }
}
string email = string.Empty;
public FreightOrderList()
{
//default Cons
}
public FreightOrderList(int _customerID)
{
this.customerID = _customerID;
}
public DataSet displayOrders()
{
string ConString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlConnectionObj = new SqlConnection(ConString);
SqlDataAdapter sqlDataAdapterObj = new SqlDataAdapter();
DataSet dataSetObj = new DataSet();
sqlDataAdapterObj.SelectCommand = new SqlCommand();
sqlDataAdapterObj.SelectCommand.Connection = sqlConnectionObj;
sqlDataAdapterObj.SelectCommand.CommandText = "customerShipOrderProc";
sqlDataAdapterObj.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlConnectionObj.Open();
sqlDataAdapterObj.SelectCommand.Parameters.AddWithValue("customerID", this.CustomerID);
sqlDataAdapterObj.Fill(dataSetObj,"customerShipOrder");
sqlConnectionObj.Close();
return dataSetObj;
}
}
You can use sqldependency which updates you when a row is updated instead of hitting the database over and over again.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx
or
If you are skilled, you can go for Asynchronous Page or SignalR
or
AJAX Callbacks

Reading a RSS feed using visual C#

I am trying to a read a RSS feed and display in my C# application. i have used the code below and it works perfectly for other RSS feeds. I want to read this RSS feed ---> http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml and the code below doesn't work for it. I don't get any errors but nothing happens, the text box which i want the RSS feed to be displayed is empty. Please help. What am I doing wrong?
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
public class RssReader
{
public static List<RssNews> Read(string url)
{
var webResponse = WebRequest.Create(url).GetResponse();
if (webResponse == null)
return null;
var ds = new DataSet();
ds.ReadXml(webResponse.GetResponseStream());
var news = (from row in ds.Tables["item"].AsEnumerable()
select new RssNews
{
Title = row.Field<string>("title"),
PublicationDate = row.Field<string>("pubDate"),
Description = row.Field<string>("description")
}).ToList();
return news;
}
}
private string covertRss(string url)
{
var s = RssReader.Read(url);
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s)
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
return sb.ToString();
}
//Form Load code///
string readableRss;
readableRss = covertRss("http://ptwc.weather.gov/ptwc/feeds/ptwc_rss_indian.xml");
textBox5.Text = readableRss;
It seems that the DataSet.ReadXml method fails because there category is specified twice in the item, however under a different namespace.
This seems to work better:
public static List<RssNews> Read(string url)
{
var webClient = new WebClient();
string result = webClient.DownloadString(url);
XDocument document = XDocument.Parse(result);
return (from descendant in document.Descendants("item")
select new RssNews()
{
Description = descendant.Element("description").Value,
Title = descendant.Element("title").Value,
PublicationDate = descendant.Element("pubDate").Value
}).ToList();
}

Resources