I have tried to display a chart for database data but I'm having some trouble. I've tried using json to high charts but it's not working. Could someone please explain to me how to show axis as date and to call this on viewpage?
public List<CustomerAccount> ChartData(long customerID)
{
List<CustomerAccount> chart = new List<CustomerAccount>();
List<CustomerAccount> points = new CustomerAccountDBMgr().ChartAccount(customerID).FindAll(e => e.AccountName != "Others");
if (null == points || points.Count == 0)
return null;
var val = (from item in points select new { CreatedAt = item.CreatedAt, OpeningBalance = item.OpeningBalance }).ToList();
foreach (var data in val)
{
CustomerAccount objCustomer = new CustomerAccount()
{
CreatedAt = data.CreatedAt,
OpeningBalance = data.OpeningBalance
};
chart.Add(objCustomer);
}
return chart;
}
Model
public class Chart1
{
public DateTime CreatedAt { get; set; }
public Double? OpeningBalance { get; set; }
public List<CustomerAccount> ChartData()
{
PersonalizeBL business=new PersonalizeBL();
var CustomerID = PERFICSSession.GetCustomerID();
List<CustomerAccount>point=business.ChartData(CustomerID);
return point;
}
}
Controller
public ActionResult Chart1()
{
if (!PERFICSSession.IsValidSession())
return View("Login");
Chart1 model = new Chart1();
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
.SetTitle(new Title { Text = "Database Data" })
.SetXAxis(new XAxis { Type = AxisTypes.Datetime })
.SetYAxis(new[]
{
new YAxis
{
Title = new YAxisTitle { Text = "Amount" },
GridLineWidth = 1
}
})
.SetSeries(new[]
{
new Series
{
Name = "OpeningBalance",
Data = new Data((model.ChartData()).Select(x=>new points{X=DotNet.Highcharts.Helpers.Tools.GetTotalMilliseconds(x.CreatedAt),Y=x.OpeningBalance}).ToArray())
}
});
return View("Chart1");
}
Finally i found answere for this issue. i would have return view which object i did created from highcharts. i wrongly returned the view page name.
public ActionResult Chart1()
{
chartModel model = new chartModel();
var data = model.chartPlots(Session);
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
.SetTitle(new Title { Text = "Database Data" })
.SetXAxis(new XAxis { Type = AxisTypes.Datetime })
.SetYAxis(new[]
{
new YAxis
{
Title = new YAxisTitle { Text = "Amount" },
GridLineWidth = 1
}
})
.SetSeries(new[]
{
new Series
{
Name = "OpeningBalance",
Data = new Data(data.Select(x=>new points{X=DotNet.Highcharts.Helpers.Tools.GetTotalMilliseconds(x.CreatedAt),Y=x.OpeningBalance}).ToArray())
}
});
return View(chart);
}
return View(chart);
}
Related
i am creating simple sales system for my final year project. i am creating a sales Form. attached the screen shot image below how the form look like.
after sales completed i need to save the data into multiple table along with the lastinsert id. if i click print invoice button. i have a tables in the database sales,sales product i shown the shot shotimage below.i don't how to save records into multipule table with lastinsert id.
enter image description here
Sales Table
id date subtotal
Sales_Product Table
id sales_id product_id price qty total
Code which i tried
jQuery
function addProject() {
var table_data = [];
$('#product_list tbody tr').each(function (row, tr) {
var sub = {
//these records i am going to add into sales table
'barcode': $(tr).find('td:eq(1)').text(),
'pname': $(tr).find('td:eq(2)').text(),
'pro_price': $(tr).find('td:eq(3)').text(),
'qty': $(tr).find('td:eq(4)').text(),
'total_cost': $(tr).find('td:eq(5)').text(),
};
table_data.push(sub);
});
//these records i am going to add into sales
var total = $("#total").val();
$.ajax({
type: 'POST',
url: '/product/Save',
dataType: 'JSON',
data: {
total: $('#total').val(), data: table_data
},
success: function (data) {
console.log(_data);
var msg;
if (isNew) {
msg = "Sales Completed";
}
last_id = data.last_id
window.location.href = "print.php?last_id=" + last_id;
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
}
});
}
Controller
[HttpPost]
public ActionResult Save(sale s)
{
bool status = false;
if (ModelState.IsValid)
{
using (saleEntities3 dc = new saleEntities3())
{
//Sales table
var v = dc.sales.Where(a => a.id == s.id).FirstOrDefault();
dc.sales.Add(v);
dc.SaveChanges();
v.id = s.id; // lastinsertid
//how to add into lastinsertid as a sales product table as a sales_id colum
//Sales product table i don't how to add
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
saleEntities3
public partial class saleEntities3 : DbContext
{
public saleEntities3()
: base("name=saleEntities3")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<product> products { get; set; }
public virtual DbSet<sale> sales { get; set; }
public virtual DbSet<sales_product> sales_product { get; set; }
}
}
To save in the Sales_Product table you need to save with the id of the saved sales according to your table structure
[HttpPost]
public ActionResult Save(sale s)
{
bool status = false;
if (ModelState.IsValid)
{
using (saleEntities3 dc = new saleEntities3())
{
//Sales table
var v = dc.sales.Where(a => a.id == s.id).FirstOrDefault();
dc.sales.Add(v);
dc.SaveChanges();
dc.sales_product.Add(new sales_product{
sales_id = s.id,
product_id = s.barcode, //I believe this is the product id
price = s.pro_price,
quantity = s.qty,
total = s.total_cost
});
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
I'm trying to write additional properties to the log using {Properties} (which are not in the message template):
Used (FileSink) template:
"[{Level}] {Message}{NewLine}{Properties}{NewLine}{Exception}"
Log operation (simplified, normally the object array is given by a method parameter):
Log.Information("Start logging",
new object[]{
new { Version = "VersionString"},
new { StartDate = DateTime.Now },
new { Id = Guid.NewGuid() }
});
I also tired:
Log.Information("Start logging",
new object[]{
"VersionString",
DateTime.Now,
Guid.NewGuid()
});
I had a look on LogEventPropertyCapturingTests and this PR, but I couldn't get it working...
Update
I use wrapper functions like this:
public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
{
_MainLog.Information(messageTemplate, propertyValues);
}
if(show)
{
// Code to show a the event to the user
}
}
Update2 Found a way but it's not very nice, as the template-property-matching rudimentary.
public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumer = -1)
{
using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumer }))
{
Regex matchProperties = new Regex("{[^}]+}");
int usedPropertiesCount = matchProperties.Matches(messageTemplate).Cast<Match>().Select(m => m.Value).Distinct().Count();
if (propertyValues.Length > usedPropertiesCount)
{
using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount)))
{
_MainLog.Information(messageTemplate, propertyValues);
}
}
else
{
_MainLog.Information(messageTemplate, propertyValues);
}
}
if(show)
{
// Code to show a the event to the user
}
}
The ForContext() method will do this:
Log.ForContext("Version", "VersionString")
.ForContext("Id", Guid.NewGuid())
.Information("Start logging");
(I've omitted StartDate because all Serilog events are already timestamped.)
This blog post series includes some posts on message templates plus context and correlation that cover this plus other alternatives.
Here i have a problem with data table to convert json. This is my class called SearchCollection
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public int ClassGroupId { get; set; }
public string ClassName { get; set; }
public int ClassNumber { get; set; }
public int BookTypeId { get; set; }
public string BookType { get; set; }
I have collected a data from store procedure and pushed into the datatable, thats why am using ConvertToDatatable(), that time i got a datatable which contains 3 tables data
static DataTable ConvertToDatatable(IEnumerable<SearchCollection> list)
{
var dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("CategoryName");
dt.Columns.Add("ClassGroupId");
dt.Columns.Add("ClassName");
dt.Columns.Add("ClassNumber");
dt.Columns.Add("BookTypeId");
dt.Columns.Add("BookType");
foreach (var item in list)
{
var row = dt.NewRow();
row["CategoryId"] = item.CategoryId;
row["CategoryName"] = item.CategoryName;
row["ClassGroupId"] = item.ClassGroupId;
row["ClassName"] = item.ClassName;
row["ClassNumber"] = item.ClassNumber;
row["BookTypeId"] = item.BookTypeId;
row["BookType"] = item.BookType;
dt.Rows.Add(row);
}
return dt;
}
this contain 3 tables data.
So.. this is have tried to group the data, but here am getting the answer like category on top inside category shows booktype and inside booktype shows list of classnames, but i want 3 set of data
category {},booktype{},classnames{}
var result = rows.GroupBy(r => new { x = r["CategoryId"], y = r["CategoryName"] }).Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y,
BookTypes = g.GroupBy(r => new { h = r["BookTypeId"], i = r["BookType"] }).Select(g1 => new
{
BookTypeId = g1.Key.h,
BookType = g1.Key.i,
ClassNames = g1.Select(r => new
{
ClassGroupId = r["ClassGroupId"],
ClassName = r["ClassName"],
ClassNumber = r["ClassNumber"]
}),
}),
});
Rusult
This is my result
{ CategoryId:1 CategoryName:CD ClassGroupId:15 ClassName:I ClassNumber:1 BookTypeId:1 BookType:General CD}
{ CategoryId:2 CategoryName:DVD ClassGroupId:16 ClassName:II ClassNumber:2 BookTypeId:2 BookType:General DVD}
{ CategoryId:3 CategoryName:Book ClassGroupId:17 ClassName:III ClassNumber:3 BookTypeId:3 BookType:General Books}
But i want the result like this
+ Category={ CategoryId:1 CategoryName:CD
CategoryId:2 CategoryName:DVD
CategoryId:3 CategoryName:Book }
ClassGroup={ClassGroupId:15 ClassName:I ClassNumber:1
ClassGroupId:16 ClassName:II ClassNumber:2
ClassGroupId:17 ClassName:III ClassNumber:3}
BookType{ BookTypeId:1 BookType:General CD
BookTypeId:2 BookType:General DVD
BookTypeId:3 BookType:General Books
}
here my result is booktype is under category and classname under booktype. but i want the result just like 3 groups of records in single json, any one help just like category grouped collection, class grouped collection and book type collection in single json data.
Is this what you're looking for?
var result = new
{
Category = rows
.GroupBy(r => new
{
x = r["CategoryId"],
y = r["CategoryName"]
})
.Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y
}),
ClassGroup = rows
.GroupBy(r => new
{
x = r["ClassGroupId"],
y = r["ClassName"],
z = r["ClassNumber"]
})
.Select(g => new
{
ClassGroupId = g.Key.x,
ClassName = g.Key.y,
ClassNumber = g.Key.z
}),
BookType = rows
.GroupBy(r => new
{
x = r["BookTypeId"],
y = r["BookType"]
})
.Select(g => new
{
BookTypeId = g.Key.x,
BookType = g.Key.y
})
};
Fiddle: https://dotnetfiddle.net/h9qXqc
friends I'm new to highchart ,need your help to create chart in MVC 4 ,I write the code on Home controller like...
public class HomeController : Controller
{
public ActionResult Index()
{
Highcharts chart = new Highcharts("chart")
.SetCredits(new Credits { Enabled = false })
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
.SetTitle(new Title { Text = "Membership Overview" })
.SetXAxis(new XAxis { Categories = new[] { "Paid Members", "Active Members", "Retained Members", "New Members", "Lapsed Members" } })
.SetYAxis(new YAxis
{
Min = 0,
Title = new YAxisTitle { Text = "Total Members" }
})
.SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +''; }" })
.SetPlotOptions(new PlotOptions { Bar = new PlotOptionsBar { Stacking = Stackings.Normal } })
.SetSeries(new[]
{
new Series { Name = "Total", Data = new Data(new object[] { 441, 441, 22, 30, 610 }) }
});
return View(chart);
}
}
now I don't understand how to render it on index.cshtml page.
Your Index.cshtml page should look something like this to display your chart.
#model DotNet.Highcharts.Highcharts
#{
var chart = Model;
}
if(Model != null) {
#(chart)
}
I tried to implement this solution here:
Display image from database in asp mvc
But the picture is not showing. I wonder what I could be doing wrong.
ApplicantPosition is a table with a 2 column primary key, that's why I use 2 parameters.
It seems to be pretty simple and I got not compiler errors.
public ActionResult Show(int applicantId, int positionId)
{
var imageData = unitOfWork.ApplicantPositionRepository.Find(d => d.ApplicantID == applicantId && d.PositionID == positionId).ToList()[0].Applicant.photo;
return File(imageData, "image/jpg");
}
<img src="#Url.Action("show", "image", new { applicantId = ViewData["applicantId"] , positionId=ViewData["positionId"]} )" />
This is the initializer of the database that shows that I am loading the pictures.
protected override void Seed(HRContext context)
{
#region Status
Status applied = new Status() { status = "Applied" };
Status reviewedByHR = new Status() { status = "Reviewed By HR" };
Status approvedByHR = new Status() { status = "Approved by HR" };
Status rejectedByHR = new Status() { status = "Rejected by HR" };
Status assignedToTechnicalDepartment = new Status() { status = "Assigned to Technical Department" };
Status approvedByTechnicalDepartment = new Status() { status = "Approved by Technical Department" };
Status rejectedByTechnicalDepartment = new Status() { status = "Rejected by Technical Department" };
Status assignedToGeneralManager = new Status() { status = "Assigned to General Manager" };
Status approvedByGeneralManager = new Status() { status = "Approved by General Manager" };
Status rejectedByGeneralManager = new Status() { status = "Rejected by General Manager" };
context.Status.Add(applied);
context.Status.Add(reviewedByHR);
context.Status.Add(approvedByHR);
context.Status.Add(rejectedByHR);
context.Status.Add(assignedToTechnicalDepartment);
context.Status.Add(approvedByTechnicalDepartment);
context.Status.Add(rejectedByTechnicalDepartment);
context.Status.Add(assignedToGeneralManager);
context.Status.Add(approvedByGeneralManager);
context.Status.Add(rejectedByGeneralManager);
#endregion
#region Position
Position netdeveloper = new Position() { name = ".net developer", yearsExperienceRequired = 5 };
Position javadeveloper = new Position() { name = "java developer", yearsExperienceRequired = 5 };
context.Positions.Add(netdeveloper);
context.Positions.Add(javadeveloper);
#endregion
#region Applicants
Applicant luis = new Applicant()
{
name = "Luis",
skypeuser = "le.valencia",
telephone = "0491732825",
photo = File.ReadAllBytes(#"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\1.jpg")
};
Applicant john = new Applicant()
{
name = "John",
skypeuser = "jo.valencia",
telephone = "3435343543",
photo = File.ReadAllBytes(#"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\2.jpg")
};
context.Applicants.Add(luis);
context.Applicants.Add(john);
#endregion
#region ApplicantsPositions
ApplicantPosition appicantposition = new ApplicantPosition()
{
Applicant = luis,
Position = netdeveloper,
appliedDate = DateTime.Today,
Status = applied
};
ApplicantPosition appicantposition2 = new ApplicantPosition()
{
Applicant = john,
Position = javadeveloper,
appliedDate = DateTime.Today,
Status = applied
};
context.ApplicantsPositions.Add(appicantposition);
context.ApplicantsPositions.Add(appicantposition2);
#endregion
try
{
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
you have an incorrect syntax, try this:
<img src="#Url.Action("Show", new { applicantId = item.ApplicantID, positionId=item.PositionID })" />