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

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;
}
}

Related

Convert SqlDataReader to object for .NET Framework 4

I am working on a class Library with .NET Framework 4.0. I have managed to pull a row using ADO.NET, but I'm unable to read individual values. I want the end result in class object. I have tried reading individual value dbReader.GetValue(dbReader.GetOrdinal("BranchCode")) but getting empty result.
Branch class:
public class Branch
{
public Branch() { }
public int BranchId { get; set; }
public string BranchCode { get; set; }
public string BranchName { get; set; }
}
DataReader class:
public void Initialize()
{
try
{
string connectionString = "xyz";
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from dbo.Branch", dbConnection);
dbConnection.Open();
SqlDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var x1 = dbReader.GetValue(dbReader.GetOrdinal("BranchId"));
var x2 = dbReader.GetValue(dbReader.GetOrdinal("BranchCode"));
var x3 = dbReader.GetValue(dbReader.GetOrdinal("BranchName"));
}
var dd = "Dd";
}
catch(Exception ex)
{
throw ex;
}
}
You have a number of issues with your code.
You need to actually create the Branch objects and do something with them. For example, return List.
To read the values, the easiest way is to do (typeNameHere) dbReader["ColumnName"]
You should SELECT exactly the right columns not SELECT *
Don't catch then re-throw exceptions with throw ex; as it wipes the stakc trace.
public List<Branch> Initialize()
{
string connectionString = "xyz";
const string query = #"
Select
b.BranchId,
b.BranchCode,
b.BranchName
from dbo.Branch b;
";
using (SqlConnection dbConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
using (SqlDataReader dbReader = cmd.ExecuteReader())
{
var list = new List<Branch>();
while (dbReader.Read())
{
var b = new Branch();
b.BranchId = (int)dbReader["BranchId"];
b.BranchCode = (string)dbReader["BranchCode"];
b.BranchName = (string)dbReader["BranchName"];
list.Add(b);
}
return list;
}
}
}

How to insert data into database using formcollection

I am trying insert data into a database table. Unfortunately, the data does not get inserted into the database.
Controller:
public class UserController : Controller
{
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
string query = "INSERT INTO Member (#ID, #Name, #City, #Address) " +
"VALUES (ID, Name, City, Address)";
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
//model get,set method does not access
sqlcmd.ExecuteNonQuery();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Repository:
public class UserMasterRepository : IUserMasterRepository
{
private List<UserMaster> users = new List<UserMaster>();
private int _nextId = 1;
public UserMaster Add(UserMaster item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.ID = _nextId++;
users.Add(item);
return item;
}
}
IUserMasterRepository:
public interface IUserMasterRepository
{
IEnumerable<UserMaster> GetAll();
UserMaster Get(int id);
UserMaster Add(UserMaster item);
bool Update(UserMaster item);
bool Delete(int id);
}
How can I resolve this issue?
As suggested by #marc_s you need to change your inline query for insertion and before inserting value you need to fetch records from FormCollection.
I assume that you have view model something like this.
public class VM
{
public int Id { get; set; }
public string Name { get; set; }
public string City{ get; set; }
public string Adderess{ get; set; }
}
Retrieve input values from FormCollection Object in action method:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
//model get,set method does not access
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = collection["ID"];
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = collection["Name"];
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = collection["City"];
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value =collection["Address"];
///continue
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I believe for SQL Server, your INSERT statement is wrong - try this:
string query = "INSERT INTO Member (ID, Name, City, Address) " +
"VALUES (#ID, #Name, #City, #Address)";
The list of columns after the INSERT INTO must list the column names as defined in the database table - and those are without a leading #.
On the other hand, the parameter placeholders in the VALUES (...) section are just that - parameters - and they must have the leading # for their name.
Those parameters must then be defined and a value must be provided for each of them before the .ExecuteNonQuery() call:
//model get,set method does not access
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = 42;
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = "Miller";
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = "London";
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value = "123 Earl's Court";
sqlcmd.ExecuteNonQuery();

How to improve the coverage of this test class in Apex?

I have created a test class with 51% code coverage till line no 34.
Further, I tried to satisfy if condition but I couldn't. Now I am not getting how to do with 100% code coverage.
Here is the Apex class:
public class AssignProjectController {
public String CaseIds;
public String status {get;set;}
public List<Project__c> activeProjects {get;set;}
public String keyWordSearched {get;set;}
public Id projectId {get;set;}
public AssignProjectController (){
CaseIds = ApexPages.currentPage().getParameters().get('id');
}
public void getProjects(){
status = '';
String searchQuery = 'FIND \'' + keyWordSearched + '*\' IN ALL FIELDS RETURNING Project__c (id,Name,Description__c where Status__c =\'Active\')';
try{
List<List<Project__c >> searchList = search.query(searchQuery);
activeProjects = searchList[0];
if(activeProjects.size() == 0) status = 'No search result found.';
}catch(Exception ex){
system.debug('ex..'+ex.getMessage());
}}}
public PageReference assignProjectToCases(){
List<Case__c> customSettingList = Case__c.getall().values();
List<String> settingRecordTypeList = new List<String>();
for(Case__c caseObj:customSettingList){
settingRecordTypeList.add(caseObj.Name);
}
List<RecordType> recordTypeListData = [SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name In : settingRecordTypeList];
if(CaseIds != null){
List<String> caseIDList = new List<String>();
caseIDList = CaseIds.split(',');
if([Select id from Case where Id In : caseIDList and RecordType.Id NOT In : recordTypeListData].size() > 0){
status = 'failed';
}else{
List<Case> cases = [Select id,Project__c,RecordType.Name from Case where Id In : caseIDList and RecordType.Id In : recordTypeListData];
if(cases.size() > 0){
for(case caseOb: cases){
caseOb.Project__c = projectId ;
}
try{
update cases ;
status = 'Changes are scheduled';
}catch(Exception ex){
system.debug('AssignProjectController :::'+ex.getMessage());
status = 'Something Went Wrong';
}}}}
return null;
}}
Here is the test class- which I tried to resolve
#isTest public class TestAssignProjectController {
public static Project__c insertProject(){
Project__c proObj = new Project__c();
proObj.Name = 'testProject';
proObj.Status__c = 'Active';
proObj.Description__c = 'for testing';
proObj.Internal_Email_Alias__c = 'a#test.com';
return proObj;
}
public static Account getAccount(){
Account accoObj = new Account();
accoObj.Name = 'testAcc';
accoObj.Location__c = 'testLocation';
accoObj.Type = 'CM';
accoObj.BillingCountry = 'United States';
return accoObj;
}
public static Contact insertContact(Account accObj){
Contact conObj = new Contact();
conObj.FirstName = 'test';
conObj.LastName = 'testLastname';
conObj.AccountId = accObj.Id;
conObj.Email = 'abc#gmail.com';
return conObj;
}
public static Id getTechTypeId(){
return Schema.SObjectType.Case.getRecordTypeInfosByName().get('Tech ').getRecordTypeId();
}
public static Case insertCase(String conId, String proId){
Case caseObj = new Case();
caseObj.Project__c = proId;
caseObj.ContactId = conId;
caseObj.Status = 'Open';
caseObj.Inquiry_Type__c = 'All';
caseObj.Subject = 'TestSubject';
caseObj.Description = 'TestDescription';
caseObj.Case_Is_Reopened__c = false;
caseObj.RecordTypeId = getTechTypeId();
return caseObj;
}
public static testmethod void testMethodExecution(){
AssignController asigncon = new AssignController ();
Project__c proObj = insertProject();
insert proObj;
System.assertEquals(proObj.Status__c,'Active');
Account accObj = getAccount();
insert accObj;
System.assertNotEquals(accObj.Id,null);
Contact conObj = insertContact(accObj);
insert conObj;
System.assertNotEquals(conObj.Id,null);
Case caseObj = insertCase(conObj.Id, proObj.Id);
insert caseObj;
system.debug(caseObj);
//Set baseURL & case ID
PageReference pageRef = Page.Assign;
pageRef.getParameters().put('id',caseObj.id+',');
AssignController asigncon1 = new AssignController ();
asigncon1.getProjects();
asigncon1.assignProjectToCases();
}}
If you are referring if(cases.size() > 0) this statement, then surely there is problem of inserting the case. Make sure that insert caseObj; is working and inserts data in Salesforce backend.
If there is no data in case object, the test method cannot cover the if statement.

ComboBox Shows System.Data.DataRow (MVC)

My Combobox does not show me the values in my SQL-Attribute "TimeBlock", instead it shows System.Data.DataRow 5 Times. What is wrong with my code?
Code:
//DAL:
public class DAL{
string ConnectionString = "server=ICSSQL13\\Grupp28,1528; Trusted_Connection=yes; database=Yoloswag";
public DataTable StoreSqlDataInComboBoxTP()
{
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();
string StoreSqlDataInComboBoxTP = "SELECT TimeBlock FROM TimePeriod GROUP BY TimeBlock";
SqlCommand Cmd = new SqlCommand(StoreSqlDataInComboBoxTP, Conn);
SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
DataSet DSet = new DataSet();
Adapter.Fill(DSet);
Adapter.Dispose();
Cmd.Dispose();
Conn.Close();
Conn.Close();
return DSet.Tables[0];
}
}
//Controller:
public class Controller
{
DAL Dal = new DAL();
public DataTable storesqldataincomboboxtp()
{
return Dal.StoreSqlDataInComboBoxTP();
}
}
//View:
public partial class Booking : Form
{
Controller controller = new Controller();
DataTable DTable = new DataTable();
DataSet DSet = new DataSet();
//Ignore string UserName
public Booking(string UserName){
DTable = controller.storesqldataincomboboxtp();
if (DTable.Rows.Count > 0)
{
for (int i = 0; i < DTable.Rows.Count; i++)
{
CBTime.Items.Add(DTable.Rows[i].ToString());
}
}
}
}
Instead of the 5 System.Data.DataRow I want to show what is stored in "TimeBlock".
"SELECT TimeBlock From TimePeriod GROUP BY TimeBlock" shows:
"08-00 - 10:00"
"10:00 - 12:00"
"12:00 - 14:00"
"14:00 - 16:00"
"16:00 - 18:00"
How can i solve this?
Thanks
You are not getting to the Field level when you are calling the Add() on CBTime. Something like this within your conditional checking that your table has rows would work:
foreach (DataRow dRow in DTable.Rows)
{
CBTime.Items.Add(dRow["TimeBlock"]);
}

CRUD operation in MVC with out Entity framework

Hi I am beginner in MVC , I am trying to achieve CRUD operation in MVC using SQL with out Entity Framework or LINQ-SQL class. I done well with insert and getting the details of the selected table but when coming to Edit, details and delete I am confused how to perform so can some one help me out.
This is my code
Create a new Employee
public ActionResult Index(Test test)
{
try
{
if (ModelState.IsValid)
{
test.insert(test);
test.Name = "";
test.LastName = "";
}
}
catch (Exception)
{
}
return View(test);
}
Display all results
public ActionResult display()
{
Test tst = new Test();
return View(tst.getList());
}
This is my code in class file
public class Test
{
public int EmpID { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("LastName")]
public string LastName { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["SomeDataBase"].ConnectionString.ToString();
public void insert(Test test)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
SqlCommand cmd = new SqlCommand("insert into Employee values('" + test.Name + "','" + test.LastName + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<Test> getList()
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
public List<Test> edit(int id)
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
}
Can some one help me how to do the remaining operations like Details, Edit update and Delete.
for Details you can use
public Test details(int id)
{
Test _products = new Test();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
_products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_products.Name = dr["FirstName"].ToString();
_products.LastName = dr["LastName"].ToString();
}
catch(exception ex)
{
/* Do Some Stuff */
}
return _products;
}
And from your Controller
public ActionResult Details(int id)
{
Test tst = new Test();
return tst.Details(id);
}
for Edit you can use
public Bool Edit(test tst)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("UPDATE TABLE Employee SET FirstName='"+tst.Name+"',Lastname='"+tst.LastName+"' where EmpID='" + tst.EmpId + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
return true;
}
catch(exception ex)
{
/* Do Some Stuff */
}
}
And from your Controller
public ActionResult Edit(test tsts)
{
Test tst = new Test();
return tst.Edit(tsts);
}
and proceed similarly for the rest of the cases

Resources