I have this problem with error timeout, always when it suppose to get data from database it bounce error. I am trying to retrieve video from database with this code:
Repository.cs
public List<videoTble> Video()
{
var model = new List<videoTble>();
string ConStr = "Data Source="";Connect Timeout=60";
using (SqlConnection con = new SqlConnection(ConStr))
{
string str = "SELECT * FROM videoTbles";
con.Open();
SqlCommand cmd = new SqlCommand(str, con);
cmd.CommandTimeout = 60;
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
var v = new videoTble();
v.Name = rd["Name"].ToString();
v.Data = (byte[])rd["Data"];
v.ContentType = rd["ContentType"].ToString();
v.ArtistName = rd["ArtistName"].ToString();
v.Expirydate = (DateTime)rd["Expirydate"];
model.Add(v);
}
con.Close();
}
return model;
}
Controller.cs
public ActionResult Download()
{
Repository res = new Repository();
ViewBag.Video = res.Video();
return View();
}
Model.cs
public partial class videoTble
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
public string ArtistName { get; set; }
public DateTime Expirydate { get; set; }
}
The timeout Error I got, when i run application
It looks like you are storing your video as raw data in your database. I highly advise against this. Store the video files on your file system, and store the paths to the video files in your database.
Related
This is my models class (ObjektiMeQira.cs):
namespace crud2.Models
{
public class ObjektiMeQira
{
public int ObjektiMeQiraId { get; set; }
public string ObjektiMeQiraEmri { get; set; }
public string LlojiObjektit { get; set; }
public string Siperfaqe { get; set; }
public int NumriIDHomave { get; set; }
public string Kati { get; set; }
public int Cmimi { get; set; }
public string Vendndodhja { get; set; }
public string Qyteti { get; set; }
public string Shteti { get; set; }
}
}
And now this is my Controllers class (ObjektiMeQiraController.cs):
Note: I am only getting this error in Post method, otherwise Get method works fine.
[HttpPost]
public JsonResult Post(ObjektiMeQira omq)
{
string query = #"
insert into dbo.ObjektiMeQira(ObjektiMeQiraEmri,LlojiObjektit,Siperfaqe,
NumriIDHomave, Kati, Cmimi, Vendndodhja, Qyteti, Shteti)
values (#ObjektiMeQiraEmri), (#LLojiObjektit), (#Siperfaqe),
(#NumriIDHomave), (#Kati), (#Cmimi), (#Vendndodhja), (#Qyteti), (#Shteti)
";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("#ObjektiMeQiraEmri", omq.ObjektiMeQiraEmri);
myCommand.Parameters.AddWithValue("#LlojiObjektit", omq.LlojiObjektit);
myCommand.Parameters.AddWithValue("#Siperfaqe", omq.Siperfaqe);
myCommand.Parameters.AddWithValue("#NumriIDHomave", omq.NumriIDHomave);
myCommand.Parameters.AddWithValue("#Kati", omq.Kati);
myCommand.Parameters.AddWithValue("#Cmimi", omq.Cmimi);
myCommand.Parameters.AddWithValue("#Vendndodhja", omq.Vendndodhja);
myCommand.Parameters.AddWithValue("#Qyteti", omq.Qyteti);
myCommand.Parameters.AddWithValue("#Shteti", omq.Shteti);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Added Successfully");
}
Even though I looked at other posts in stackoverflow I didn't quite find the solution.
Your insert query in C# is just plain wrong - it should be:
string query = #"INSERT INTO dbo.ObjektiMeQira (ObjektiMeQiraEmri, LlojiObjektit, Siperfaqe,
NumriIDHomave, Kati, Cmimi, Vendndodhja, Qyteti, Shteti)
VALUES (#ObjektiMeQiraEmri, #LLojiObjektit, #Siperfaqe,
#NumriIDHomave, #Kati, #Cmimi, #Vendndodhja, #Qyteti, #Shteti);";
You MUST NOT put each parameter into its own round parenthesis!
You need to provide one row of data, with a total of 9 column values - in a single VALUES (.....) statement.
I have text boxes to search for data, and 6 text boxes to display data if the data I am looking for is found. I'm trying to use an object class to make the code in the form look a little neat. the class is named ClsSearch. This is the class code snippet:
public string Name { get; set; }
public string txtCode { get; set; }
public string txtBarcode { get; set; }
public string txtUnit { get; set; }
public string txtQty { get; set; }
public string txtCost_price { get; set; }
public string txtSales_price { get; set; }
string mainconn = ConfigurationManager.ConnectionStrings["DbLearn"].ConnectionString;
public void X001_TextChanged()
{
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
string sqlquery = "SELECT * FROM tb_stock_product WHERE Item_Name='" + Name + "'";
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
mysqlconn.Open();
MySqlDataReader sdr;
sdr = sqlcmd.ExecuteReader();
if (sdr.Read())
{
txtCode = sdr.GetString("Code");
txtBarcode = sdr.GetString("Barcode");
txtUnit = sdr.GetString("Unit");
txtQty = sdr.GetDouble("Qty").ToString();
txtCost_price = sdr.GetInt32("Cost_price").ToString();
txtSales_price = sdr.GetInt32("Sales_price").ToString();
}
mysqlconn.Close();
then I tried calling the class in the form, exactly when the button was pressed, and this is the code:
private void X_001_Click(object sender, EventArgs e)
{
Connection_Frm_Ordering load = new Connection_Frm_Ordering();
load.X001_TextChanged();
load.Name = X_001.Text;
load.txtCode = X_002.Text;
load.txtBarcode = X_003.Text;
load.txtUnit = X_004.Text;
load.txtQty = X_005.Text;
load.txtCost_price = X_006.Text;
load.txtSales_price = X_007.Text;
}
but the code i made is not working.. can anyone help me where is the error ? sorry if this code might be messy, I'm still learning :)
I am creating my first project using asp.net MVC - I have successfully connected to the database and displayed the information on the index page. My question is how do I get more than one query result on the one index page
for e.g
SELECT student ID,first name,surname FROM STUDENT Notes WHERE student ID = 7
Do I need to create new controllers/models for each query or need to add to the current and if I add to the current how would I do it? Below is the code I currently have in my controller.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
List<CustomerModel> customers = new List<CustomerModel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
// CustomerId = Convert.ToInt32(sdr["Student Number"]),
Title = sdr["title"].ToString(),
Name = sdr["first name"].ToString(),
Surname = sdr["surname"].ToString()
});
}
}
con.Close();
}
}
return View(customers);
}
Create a view model with two result set for e.g. Student and Marks
public class Result
{
public Student Student { get; set; }
public Marks Marks { get; set; }
}
Load/Construct this Result view model in controller /service with appropriate data and pass this view model to view.
I hope this helps!
You have to create a new class with all the properties you want to display in your View.
Example:
public class StudentModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
public class MarkModel {
public int Id { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int Mark { get; set; }
}
public class ResultModel
{
public StudentModel Student { get; set; }
public List<MarkModel> Marks { get; set; }
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
var model= new ResultModel{
Student = new StudentModel(),
Marks = new List<MarkModel>();
}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string queryStudent = "SELECT id, title, `first name`, surname FROM `STUDENT` WHERE Id=1";
using (MySqlCommand cmd = new MySqlCommand(queryStudent))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.student.Id = Convert.ToInt32(sdr["id"]),
model.student.Title = sdr["title"].ToString(),
model.student.Name = sdr["first name"].ToString(),
model.student.Surname = sdr["surname"].ToString()
}
}
}
string queryMarks = "SELECT Id, `StudentId`, StudentId,Mark FROM `MARK` WHERE StudentId=1";
using (MySqlCommand cmd = new MySqlCommand(queryMarks))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Marks.Add(new MarkModel
{
Id = Convert.ToInt32(sdr["Id"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
Mark = Convert.ToInt32(sdr["Mark"]),
});
}
}
}
}
return View(model);
}
You should create a new ViewModel class with all the properties you want to display in your View. Then you model your View after it.
From the properties you provided so far, the class should look like this:
public class StudentViewModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
Then you do the value x property assignment
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
List<StudentViewModel> model = new List<StudentViewModel>();
using (MySqlCommand cmd = new MySqlCommand(query)) {
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Add(new StudentViewModel
{
Id = Convert.ToInt32(sdr["StudentNumber"]),
Title = Convert.ToString(sdr["title"]),
Name = Convert.ToString(sdr["first name"]),
Surname = Convert.ToString(sdr["surname"])
});
}
}
con.Close();
}
return View(model);
Hi everyone I am new to programming, I am currently trying to create a web service to retrieve the customer information in my database but currently I am unable to solve this error, someone please help me
CustAccounts.svc.cs
public class CustAcc : ICustAccounts
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<CustAcc> GetCustAccJSON()
{
List<CustomerAccountDAL> abc = new List<CustomerAccountDAL>();
CustomerAccountDAL caDAL = new CustomerAccountDAL();
List<CustAcc> allAcc = new List<CustAcc>();
allAcc = caDAL.retrieveCustAccount();
//caDAL.retrieveCustAccount();
return allAcc;
}
}
CustomerAccountDAL.cs
public List<CustAcc> retrieveCustAccount()
{
List<CustAcc> acc = new List<CustAcc>();
using (SqlConnection myConnection = new SqlConnection(con))
{
string jString = "Select * from CustDB";
SqlCommand jCmd = new SqlCommand(jString, myConnection);
myConnection.Open();
using (SqlDataReader rr = jCmd.ExecuteReader())
{
while (rr.Read())
{
CustAcc accounts = new CustAcc();
custEmail = rr["custEmail"].ToString();
custPassword = rr["custPassword"].ToString();
acc.Add(accounts);
}
myConnection.Close();
}
}
return acc;
}
CustAcc.cs
public class CustAcc
{
public string custFullName { get; set; }
public string custPreferredName { get; set; }
public string custPassword { get; set; }
public string custEmail { get; set; }
public string custPhoneNumber { get; set; }
public string message { get; set; }
public CustAcc(string custName, string custFullName, string custPreferredName, string custPassword, string custEmail, string custPhoneNumber)
{
this.custFullName = custFullName;
this.custPreferredName = custPreferredName;
this.custPassword = custPassword;
this.custEmail = custEmail;
this.custPhoneNumber = custPhoneNumber;
}
public CustAcc()
{
this.custEmail = custEmail;
this.custPassword = custPassword;
}
}
Move your Model classes to their own assembly called Model and reference the assembly in both the WS and website assemblies.
You will also need to setup the Service reference in your website to look for the Service types in the Model assembly (it's an option in the Add Service Reference wizard).
I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public float Rating { get; set; }
public string Industry { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string CountryCode { get; set; }
public virtual Snapshot Snapshot { get; set; }
}
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public DateTime DateTimeSent { get; set; }
public string Subject { get; set; }
public string Html { get; set; }
public string Image { get; set; }
public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
{
public Brand Brand { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
controller:
public ActionResult Index(string brandGuid)
{
BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
Brand brand = GetBrand(brandGuid);
viewModel.Brand = brand;
List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
viewModel.SnapshotItems = snapshot;
List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList.AsEnumerable());
}
private Brand GetBrand(string brandGuid)
{
Brand brand = new Brand();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
if (dbResult.Read())
{
brand.Guid = dbResult["brand_guid"].ToString();
brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
brand.Industry = dbResult["industry_name"].ToString();
}
dbResult.Close();
dbConn.Close();
return brand;
}
private List<Snapshot> GetBrandSnapshots(int brandId)
{
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
List<Snapshot> snapshots = new List<Snapshot>();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Subject = dbResult["subject"].ToString(),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Email = dbResult["email"].ToString(),
ContentType = dbResult["content_type"].ToString(),
Type = dbResult["type"].ToString()
});
}
dbResult.Close();
dbConn.Close();
return snapshots;
}
edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
#model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#item.Brand.Guid;
for(int i = 0; i< #item.SnapshotItems.Count; i++)
{
#item.SnapshotItems[i].Subject<br/>
}
}
That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.
you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
while (dbResult.Read())
{
BrandEmailList brandSnapshots = new BrandEmailList (); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
while (dbResult.Read())
{
Snapshot brandSnapshots = new Snapshot(); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
// ...
}
public class BrandEmailList : List<Snapshot>
{
}
You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
var brand = GetBrand(brandName);
var brandSnapshots = GetBrandSnapshots();
return View(brand, brandSnapshots);
}
private Brand GetBrand(string brandName)
{
try
{
var brand = new Brand();
brand.Name = brandName;
// database stuffs ...
return brand;
}
catch (Exception ex)
{
throw ex;
}
}
private List<Snapshot> GetBrandSnapshots()
{
// ...
// DB stuffs -- that *really* should not be in the controller anyways.
// ...
var snapshots = new List<BrandEmailList>();
while (dbResult.Read())
{
// object initializer syntax
snapshots.Add(new Snapshot {
ID = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString(),
DateTimeSent = dbResult["date_sent"],
Subject = dbResult["subject"].ToString(),
Image = dbResult["image"],
});
}
return snapshots
}
As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.