Reading data from web service using angularjs - angularjs

I'm trying to read data from a WS and attach it to a scope variable in angularjs.
The controller API looks like this:
public class ContactsController : ApiController
{
// GET: api/Contacts
public List<Contact> Get()
{
List<Contact> cl = new List<Contact>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Contacts", con);
try
{
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Contact c = new Contact();
c.Name = rdr["Name"].ToString();
c.Phone = (int)rdr["Phone"];
c.Mail = rdr["Mail"].ToString();
c.City = rdr["City"].ToString();
c.Address = rdr["Address"].ToString();
c.Image = rdr["Image"].ToString();
cl.Add(c);
}
rdr.Close();
}
catch (Exception e)
{
}
finally
{
con.Close();
}
return cl;
}
The HTML controller looks like this:
controller: function ($scope, $http) {
var url = "http://example.com"
$http.get(url + "/api/Contacts").then(function (res) {
$scope.contacts = res.data;
}, function (err) { alert(err);});
but res.data seems to contain nothing.
Any help would be appreciated.
Thank you

You have just returning List<Contact> object, You can directly use the response instead of response.data.
Just try this code instead of yours
$scope.contacts = res;
Should check return cl; is returning any result

Related

Get data from database between two dates using Google Charts asp.net

I want to get data from database using two dates and get displayed in a chart.
I have used the link for the chart: https://www.aspsnippets.com/Articles/Google-Charts-in-ASPNet-MVC-Google-Pie-Doughnut-Chart-example-with-database-in-ASPNet-MVC.aspx
I have used the following video for the dates and getting data from the database: https://youtu.be/Rm4uiny5Ano
**CONTROLLER:**
public ActionResult Index()
{
mymodel db = new mymodel();
db.slips = AjaxMethod();
return View(db);
}
[HttpPost]
public JsonResult AjaxMethod(DateTime? start, DateTime? end)
{
string query = "SELECT [status], sum(total_amount) as Payment";
query += " FROM slips WHERE convert(varchar,date_paid, 101) BETWEEN '" + start + "' AND '" + end + "' and status='Paid' and inv_type='Valid' GROUP BY [status]";
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"status", "Payment"
});
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["status"], sdr["Payment"]
});
}
}
con.Close();
}
}
return Json(chartData);
}
private DbSet<slip> AjaxMethod()
{
throw new NotImplementedException();
}
It should display data from a database using a chart. But then there's an error that it throws on the "AjaxMethod()" method. I don't know if my code on the "Index" it's correct.
Chart Data
There is much more to this but just for your question and comment, you can create a Payment class and then a list of those and return that data. This should all be in the proper files (per class) to do it right.
How you use this list of payments I will leave up to you but you can start with this perhaps. Your model for example might include the text for the column headers.
using PaymentRepository;
public ActionResult Index()
{
PaymentModel db = new PaymentModel();
// the model might also do this directly
var chartData = PaymentRepository.GetPaidPaymentList();
db.slips = chartData;
return View(db);
}
[HttpPost]
public JsonResult GetPaymentList(DateTime start, DateTime end)
{
var chartData = PaymentRepository.GetPaymentByStatusList(start,end);
return Json(chartData);
}
// put in a class with using Payment
public class PaymentRepository
{
public static List<Payment> GetPaidPaymentList()
{
DateTime startDate = DateTime.MinValue;
DateTime endDate = DateTime.Now;
string status = "Paid";
return GetPaymentByStatusList(startDate, endDate, status = );
}
public static List<Payment> GetPaymentByStatusList(DateTime startDate, DateTime endDate, string status = "Paid")
{
List<Payment> payments = new List<Payment>();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ConnectionString))
{
var sqlQuery = #"
SELECT [status], SUM(total_amount) as Payment
FROM slips
WHERE WHERE date_paid >= #startDate AND date_paid < #endDate
AND status = #status'
AND inv_type = 'Valid'
GROUP BY [status];
";
connection.Open();
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection))
{
cmd.Parameters.Add("#startDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#startDate"].Value = startDate;
cmd.Parameters.Add("#endDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#endDate"].Value = endDate;
cmd.Parameters.Add("#status", System.Data.SqlDbType.VarChar);
cmd.Parameters["#status"].Value = status;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var payment = new Payment()
{status = (string)reader["status"], payment = (decimal)reader["Payment"]};
payments.Add(payment);
}
}
}
connection.Close();
}
return payments;
}
}
public class Payment
{
public string status
{
get;
set;
}
public decimal payment
{
get;
set;
}
}

Execute Reader is not returning a result

Can you please help me see what is wrong with my code? If I run the stored procedure using the a parameter for Id, I get a result in SQL Server. But when I use the code below using the same value for Id, in my if(rdr.HasRows).. I get a false.
public Student Find(int key)
{
string connectionPath = ConnectionStrings.DbConnection;
Student student = null;
try
{
using(var sqlCon = new SqlConnection(connectionPath))
{
sqlCon.Open();
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
{
cmd.Parameters.AddWithValue("#Id", key);
using(var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
if (rdr.HasRows)
{
while (rdr.Read())
{
student = new Student
{
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString(),
Gender = rdr["Gender"].ToString()
};
}
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return student;
}
If I try to get all records, I don't get any problems:
public IEnumerable<Student> GetAll()
{
var studentList = new List<Student>();
try
{
string connectionPath = ConnectionStrings.DbConnection;
using(var sqlCon = new SqlConnection(connectionPath))
{
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
{
sqlCon.Open();
using(var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
studentList.Add
(
new Student
{
Id = Convert.ToInt32(rdr["Id"]),
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString()
}
);
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return studentList;
}
This is using asp.net core
Your code for Find lacks the definition that this is a stored procedure that you're calling.
If you look at your GetAll, you have:
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
defining this SqlCommand to be a stored procedure - this setting is missing from your Find code:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
I'm pretty sure it'll work if you add that:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon) { CommandType = CommandType.StoredProcedure}))

Returning multiple Row using SqlConnection in web api

My Api:
public ConnectionStringSettings product;
public DbConnection connection1;
public DbCommand cdm1;
public void conn1(string a)
{
product = ConfigurationManager.ConnectionStrings["addConnection"];
connection1 = new SqlConnection();
connection1.ConnectionString = product.ConnectionString;
cdm1 = connection1.CreateCommand();
cdm1.CommandType = CommandType.Text;
cdm1.CommandText = a;
connection1.Open();
}
[Route("api/JobApi/BrowseJobs/")]
[HttpGet]
public object BrowseJobs()
{
string f = "";
try
{
conn1(string.Format("select * from FreelancerLogin"));
//select karim from UserPictures where username= karim
f = cdm1.ExecuteScalar().ToString();
}
catch (Exception ex)
{
f = ex.Message.ToString();
}
return f;
}
it returns single value like 21. But i want to return all row like the image and in json format to use in angularjs. How can i do that? Is there any other way to get my desired result?
you should use SqlDataReader and ExecuteReader method not execute scalar (execut sacal are for update, delete or insert = query with not return except key or valid result) like it:
SqlDataReader reader = cdm1.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();

How to generate and download xls with Angular Post using Spring Rest Service?

Problem solved using angular-file-saver dependency.
When I click in my export button, I make an angular like this and I want to download an xls file:
$http.post('api/sportsbooks/downloadXLS').then(function (response) {
return response.data;
});
And in my Spring Rest service I have:
#RequestMapping(value = "/sportsbooks/downloadXLS",method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
public void downloadXLS(HttpServletResponse response) {
Pageable pageable = new PageRequest(0, 20, Direction.ASC, "id");
Page<Sportsbook> page = sportsbookRepositoryCustom.findAll(pageable, null, null, null);
List<Sportsbook> sportsbookList = page.getContent();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] { "Emp No.", "Name", "Salary" });
data.put("2", new Object[] { 1d, "John", 1500000d });
data.put("3", new Object[] { 2d, "Sam", 800000d });
data.put("4", new Object[] { 3d, "Dean", 700000d });
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
if (workbook != null) {
// Writing file to outputstream
try {
byte[] bytes = workbook.getBytes();
String fileName = "report.xls";
response.setContentType("application/xls");
response.setHeader("Content-Length", String.valueOf(bytes.length));
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.getOutputStream().write(bytes);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
Maybe I have to do something in my angular callback but I don't know what. Can anybody help me?

upload file from phonegap camera to .Net web api

Server side
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
Client side code, After I get the imageURI from camera send it to below
function send(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
}
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://localhost/api/api/upload"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
I get error code 1 on the fail function. is their anything wrong with server side code? can I send ImageURI the above web api i wrote?
the code seemed to be working fine. The server user which was set on IIS did not have the proper permissions to do the write hence it was returning error. thanks

Resources