I am playing with the Blazor Webassembly template, specifically the weather forecast page.
I simply add a timer and have a function that increments a variable, that is shown on the page. What I don't get is, the addText function is never called specifically, and yet the variable keeps incrementing with the timer elapsed. So I don't understand what is happening here.
Could someone enlighten me? Do all functions within the html area get called on StateHasChanged() or something? If I changed the line in the html to '#((MarkupString)sometext.ToString())', it doesn't increment. Here is the code:
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
#if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
#foreach (var forecast in forecasts)
{
<tr>
<td>#forecast.Date.ToShortDateString()</td>
<td>#forecast.TemperatureC</td>
<td>#forecast.TemperatureF</td>
<td>#forecast.Summary</td>
</tr>
}
</tbody>
</table>
<br />
#((MarkupString)addText())
}
#code {
private WeatherForecast[] forecasts;
private int sometext = 0;
Timer timer;
protected override async Task OnInitializedAsync()
{
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += TimerOnElapsed;
timer.Start();
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
private void TimerOnElapsed(object sender, ElapsedEventArgs e)
{
StateHasChanged();
}
private string addText()
{
return sometext++.ToString();
}
}
StateHaseChanged is forcing a render. The render is calling the function... The Markup area is compiled to a delegate which is called on render. Your function is just a subroutine call. You are counting the render calls.
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
#if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
#foreach (var forecast in forecasts)
{
<tr>
<td>#forecast.Date.ToShortDateString()</td>
<td>#forecast.TemperatureC</td>
<td>#forecast.TemperatureF</td>
<td>#forecast.Summary</td>
</tr>
}
</tbody>
</table>
<br />
#sometext
}
#code {
private WeatherForecast[] forecasts;
private int sometext = 0;
Timer timer;
protected override async Task OnInitializedAsync()
{
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += TimerOnElapsed;
timer.Start();
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
private void TimerOnElapsed(object sender, ElapsedEventArgs e)
{
sometext++;
StateHasChanged(); // <- probably not needed not sure
}
}
Related
I am executing a stored procedure from my asp.net core app. The procedure executes a select statement from a db view. The db view inner joins 3 tables. When I execute the following code the result set comes as an int throwing an exception as the razor view expects List, I need to receive it as a list in order to pass it to the razor view and display the table. I would appreciate any help.
ViewModel:
public class ViewModel
{
public int TimeKey { get; set; }
public int FiscsalYear { get; set; }
public string LocationNum { get; set; }
public string Location { get; set; }
}
View:
#model List<FactWorkOrdersViewModel>
#{
ViewBag.Title = "Stored Procedure Test";
}
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th colspan="5"><h3>Stored Procedures results</h3></th>
</tr>
<tr>
<th>TimeKey</th>
<th>Fiscal Year</th>
<th>Location Number</th>
<th>Location</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.TimeKey
</td>
<td>
#item.WorkOrderAltKey
</td>
<td>
#item.FiscsalYear
</td>
<td>
#item.LocationNum
</td>
<td>
#item.Location
</td>
</tr>
}
</tbody>
</table>
<div>
Controller:
public IActionResult SPTest(ReportViewModel model)
{
DbConnection connection = db.Database.GetDbConnection();
using (DbCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "ExecuteReport";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#ReportId", model.ID));
if (connection.State.Equals(ConnectionState.Closed))
{
connection.Open();
}
var result = cmd.ExecuteScalar();
//var result = cmd.ExecuteNonQuery();
if (connection.State.Equals(ConnectionState.Open))
{
connection.Close();
}
return View(result);
}
This is a possible duplicate.
Please refer to What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery? for more information.
Short answer : You need ExecuteReader not ExecuteScalar.
ExecuteScalar returns first column's value of first row. ExecuteReader will return the list of rows which we can iterate through and display on your page.
I figured it out, thanks #Amogh
public IActionResult SPTest(ReportViewModel model)
{
List<ViewModel> viewModel = new List<ViewModel>();
using (SqlConnection conn = new SqlConnection("server=ServerName;database=DBName; user id=user_id; password=password; MultipleActiveResultSets=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("ExecuteReport", conn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.Add(new SqlParameter("#ReportId", model.ID));
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
foreach (var item in rdr)
{
ViewModel vm = new ViewModel
{
TimeKey = (int)rdr.GetValue(0),
FiscsalYear = (int)rdr.GetValue(2),
LocationNum = (string)rdr.GetValue(5),
Location = (string)rdr.GetValue(6)
};
viewModel.Add(vm);
}
}
}
}
return View(viewModel);
}
I'm a final year student, working on FYP, I have an issue about fetching image that is stored in binary data in database. I tried lots of solutions, I've searched on Google, but not working any solution.
View
#model IEnumerable<PictureServices.Picture>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
<tr>
#foreach (var item in Model)
{
<td>
#{
var base64 = Convert.ToBase64String(item.image);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
}
<img src='#imgsrc' style="max-width:100px; max-height:100px;">
</td>
model
public class Picture
{
public int id { get; set; }
public byte[] image { get; set; }
public string name { get; set; }
}
controller
public class CarServicesController : Controller
{
TestingEntities db = new TestingEntities();
public ActionResult Index()
{
Picture ds = new Picture();
var item = (from d in db.Pictures
select d).ToList();
return View(item);
}
You can convert the byte array to base 64 string and use that as the image source. You can use the Convert.ToBase64String to do so. One thing you must do is a null check before trying to convert the byte array as that could be null.
#model IEnumerable<PictureServices.Picture>
<table class="table table-striped">
#foreach (var r in Model)
{
<tr>
<td>#r.Id</td>
<td>#r.Name</td>
<td>
#if (r.Image != null)
{
var imgSrc = $"data:image/jpg;base64,{Convert.ToBase64String(r.Image)}";
<img src="#imgSrc" alt="#r.Name" />
}
</td>
</tr>
}
</table>
I would also recommend using PascalCasing for C# class properties ( Name instead of name).
I want to return a JSON Object in a datatable. I've provided the static working code that I found in an example in my angularjs template.
Thanks for help.
controller.js
function datatablesCtrl($scope,DTOptionsBuilder){
$scope.persons = [
{
id: '1',
firstName: 'Monica',
lastName: 'Smith'
},
{
id: '2',
firstName: 'Sandra',
lastName: 'Jackson'
}
];
}
Utenti.jsp
<div class="wrapper wrapper-content animated fadeInRight" ng-controller="datatablesCtrl">
<div class="row">
<div class="col-lg-12">
<table datatable="ng" dt-options="dtOptions" class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{ person.id }}</td>
<td>{{ person.user }}</td>
<td>{{ person.password }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I need to populate the $scope.person with data into a database.
The table of database is "utenti" with column id,fistName,lastName.
These are my classes.. There is also a class Utenti with a simple getter & setter.
UtentiService.class
#Service("UtentiService")
public class UtentiService implements IUtentiService{
private EntityManager entityManager;
final static Logger logger = Logger.getRootLogger();
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
#Transactional(readOnly = true)
public List<Utenti> getAll() {
Query queryFindAll = null;
try{
queryFindAll = entityManager.createNamedQuery("utenti.findAll");
}catch(Exception ex){
logger.error("Failed in method **getAll** of utentiService: ",ex);
}
return (List)queryFindAll.getResultList();
}
}
IUtentiService.class
public interface IUtentiService {
public List<Utenti> getAll(); //Restituisce una lista di tutti i siti
}
UtentiRest.class
#Path("/utenti")
#Component
#Scope("request")
public class UtentiRest {
#Autowired
IUtentiService nameUtentiService;
final static Logger logger = Logger.getRootLogger();
#GET
#Produces("application/json")
#Path("/getAll")
public JSONObject getAll() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
JSONObject jsonSitiTotal = new JSONObject();
try {
List<Utenti> soluzioni = nameUtentiService.getAll();
Iterator<Utenti> iter = soluzioni.iterator();
JSONArray jsonArray = new JSONArray();
while (iter.hasNext()) {
Utenti ut = (Utenti) iter.next();
JSONObject jsonSiti2 = new JSONObject();
jsonSiti2.put("id", ut.getId());
jsonSiti2.put("user", ut.getUserName());
jsonSiti2.put("password", ut.getPassword());
jsonArray.put(jsonSiti2);
}
jsonSitiTotal.put("Siti",jsonArray);
} catch (JSONException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.BAD_REQUEST)
.entity("JSON Exception " + ex.getMessage())
.build()
);
} catch (NullPointerException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NO_CONTENT)
.entity("No process find ")
.build()
);
} catch (IllegalArgumentException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NOT_ACCEPTABLE)
.entity("Couldn't process request with the provided argument: "
+ " (" + ex.getMessage() + ")")
.build()
);
}finally {
executorService.shutdown();
}
return jsonSitiTotal;
}
}
I have to store my image into database Oracle using EJB through Struts2. It persists data but when I add input file to JSP I have NullPointerException on this line:
byte[] buffer=new byte[(int)this.telethoraxImg.length()];
Below are some parts of my code:
PictureAction.java
public class PictureAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(MorphoRECAction.class);
private Map session ;
private ExamMorpho exMoR;
private Patient pat;
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public ExamMorpho getExam(){
return exMoR;
}
public void setExam(ExamMorpho exMoR){
this.exMoR = exMoR;
}
public Patient getPat(){
return pat;
}
public void setPat(Patient pat){
this.pat = pat;
}
private Date dateExMorpho;
private String echoAbdo;
private String echoCard;
private String exGyneco;
private String exOphtalmo;
private String mamo;
private String telethoraxTxt;
private File telethoraxImg;
public String execute(){
log.info("Entrée dans la méthode execute() ");
System.out.println("creation examen");
ExamMorpho ex = new ExamMorpho();
System.out.println("fin création");
try{
Patient pt = (Patient)session.get("lepat");
InitialContext initialContext = new InitialContext();
ExMorphoRemote facade = (ExMorphoRemote) initialContext.lookup("PatProjet/ExMorphoBean/remote");
System.out.println("ID Patient RECUPERE /" + pt.getIdPat());
System.out.println("Debut conversion image");
byte[] buffer=new byte[(int)this.telethoraxImg.length()];
/*exMoR = new ExamMorpho(buffer, dateExMorpho, echoAbdo, echoCard, exGyneco, exOphtalmo, mamo, telethoraxTxt); */
System.out.println("Fin conversion image");
FileInputStream in=new FileInputStream(this.telethoraxImg);
in.read(buffer);
ex.setTelethoraxImg(buffer);
ex.setDateExMorpho(dateExMorpho);
ex.setEchoAbdo(echoAbdo);
ex.setEchoCard(echoCard);
ex.setExGyneco(exGyneco);
ex.setExOphtalmo(exOphtalmo);
ex.setMamo(mamo);
ex.setTelethoraxTxt(telethoraxTxt);
System.out.println("FIN AJOUT IMAAAGE");
exMoR = facade.AddExMorphoR(ex, pt);
System.out.println("FIN AJOUT MORPHOOS");
} catch(Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
/*private byte[] telethoraxImg = null;
public byte[] getTelethoraxImg() {
return this.telethoraxImg;
}
public void setTelethoraxImg(byte[] telethoraxImg) {
System.out.println("ENTREE ADD IMAGE");
this.telethoraxImg = telethoraxImg;
System.out.println("SORTIE ADD IMAGE");
}*/
/*private Date dateExMorpho = null;
public Date getDateExMorpho() {
return this.dateExMorpho;
}
public void setDateExMorpho(Date dateExMorpho) {
this.dateExMorpho = dateExMorpho;
}
private String echoAbdo = null;
public String getEchoAbdo() {
return this.echoAbdo;
}
public void setEchoAbdo(String echoAbdo) {
this.echoAbdo = echoAbdo;
}
private String echoCard = null;
public String getEchoCard() {
return this.echoCard;
}
public void setEchoCard(String echoCard) {
this.echoCard = echoCard;
}
private String exGyneco = null;
public String getExGyneco() {
return this.exGyneco;
}
public void setExGyneco(String exGyneco) {
this.exGyneco = exGyneco;
}
private String exOphtalmo = null;
public String getExOphtalmo() {
return this.exOphtalmo;
}
public void setExOphtalmo(String exOphtalmo) {
this.exOphtalmo = exOphtalmo;
}
private String mamo = null;
public String getMamo() {
return this.mamo;
}
public void setMamo(String mamo) {
this.mamo = mamo;
}
private String telethoraxTxt = null;
public String getTelethoraxTxt() {
return this.telethoraxTxt;
}
public void setTelethoraxTxt(String telethoraxTxt) {
this.telethoraxTxt = telethoraxTxt;
}
*/
public void setSession(Map session) {
this.session = session;
}
public Map getSession() {
return session;
}
}
jsp code
<form action="fileUpload" method="POST" enctype ="multipart/form-data"><table>
<thead>
<tr>
<th colspan="2"></th>
<th colspan="2" rowspan="3"><center><input type="text" name="dateExMorpho" id="dn"/></a></center></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
<tr><td colspan="2">Echographie Abdominale</td><td><textarea name="echoAbdo" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Ecographie Cardiaque</td><td><textarea name="echoCard" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Examen Gynécologique</td><td><textarea name="exGyneco" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Examen Ophtalmoloique</td><td><textarea name="exOphtalmo" rows=4 COLS=40></textarea></td></tr>
<tr><td colspan="2">Mamographie</td><td><textarea name="mamo" rows=4 COLS=40></textarea></td></tr>
<tr>
<td ROWSPAN="2">Téléthorax</td>
<td >Image</td>
<td><s:file name="telethoraxImg" ContentEditable="false" style="float:left;"/></td>
</tr>
<tr>
<td>Remarques</td>
<td><textarea name="telethoraxTxt" rows=4 COLS=40></textarea></td>
</tr>
</tbody>
my Xml
<action name="fileUpload" class="clientStruts2.PictureAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/pjpeg,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg</param>
<param name="maximumSize">2097152</param></interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="input">/login/dossierRec.jsp</result>
<result name="error">/login/dossierRec.jsp</result>
<result name="success">/login/dossierRec.jsp</result>
</action>
WE are using SPA template,Code first Approach(Entity Framework),Web API for services and Angular.js for DataBind.We are able to connect with our database to perform the CRUD aperation.But the Problem is that data is not displaying in the Web Page.Below is the code snippet:
Markup Script:-
<table id="example" class="table table-bordered table-hover" style="border:1px solid lightgray">
<thead>
<tr>
<th>ProgramID</th>
<th>ProgramName</th>
<th>SiteID</th>
</tr>
</thead>
<tbody id="tableBody">
<tr data-ng-show="addMode">
<td></td>
<td><input type="text" data-ng-model="newStatusDTO.ProgramID" /></td>
<td><input type="text" data-ng-model="newStatusDTO.ProgramName" /></td>
<td><input type="text" data-ng-model="newStatusDTO.SiteID" /></td>
<td>
<p><a data-ng-click="add(newStatusDTO)" href="javascript:;">Save</a> | <a data-ng-click="toggleAdd()" href="javascript:;">Cancel</a></p>
</td>
</tr>
<tr data-ng-repeat="StatusD in sgvm.gridData">
<td data-ng-model="StatusD.ProgramName">{{StatusD.ProgramName}}</td>
<td>
<p data-ng-hide="StatusD.editMode">{{ StatusD.ProgramName }}</p>
<input data-ng-show="StatusD.editMode" type="text" data-ng-model="StatusD.ProgramName" />
</td>
<td>
<p data-ng-hide="StatusD.editMode">{{ StatusD.SiteID }}</p>
<input data-ng-show="StatusD.editMode" type="text" data-ng-model="StatusD.SiteID" />
</td>
<td>
<p data-ng-hide="StatusD.editMode"><a data-ng-click="toggleEdit(StatusD)" href="javascript:;">Edit</a> | <a data-ng-click="deleteStatusDTO(StatusD)" href="javascript:;">Delete</a></p>
<p data-ng-show="StatusD.editMode"><a data-ng-click="save(StatusD)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(StatusD)" href="javascript:;">Cancel</a></p>
</td>
</tr>
</tbody>
</table>
Angular Code:
angular.module('PPCRApp', [
'PPCRSearchController'
]);
function PPCRSearchController($scope, $http) {
$scope.loading = true;
$scope.addMode = false;
//Used to display the data
$http.get('/api/PPCRSearch/GetProgram').success(function(data) {
$scope.sgvm = data;
$scope.loading = false;
})
.error(function() {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.toggleEdit = function() {
this.StatusD.editMode = !this.StatusD.editMode;
};
$scope.toggleAdd = function() {
$scope.addMode = !$scope.addMode;
};
//Used to save a record after edit
$scope.save = function() {
$scope.loading = true;
var abc = this.StatusD;
$http.put('/api/PPCRSearch/UpdateStatus/', abc).success(function(data) {
alert("Saved Successfully!!");
abc.editMode = false;
$scope.loading = false;
}).error(function(data) {
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
//Used to add a new record
$scope.add = function() {
$scope.loading = true;
$http.post('/api/PPCRSearch/PostStatus/', this.newStatusDTO).success(function(data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.sgvm.gridData.push(data);
$scope.loading = false;
}).error(function(data) {
$scope.error = "An Error has occured while Adding Friend! " + data;
$scope.loading = false;
});
};
//Used to edit a record
$scope.deleteStatusDTO = function() {
debugger;
$scope.loading = true;
var prgid = this.StatusD.programID;
$http.delete('/api/PPCRSearch/DeleteProgram/' + prgid).success(function(data) {
debugger;
alert("Deleted Successfully!!");
$.each($scope.sgvm.gridData, function(i) {
if ($scope.sgvm.gridData[i].programID == prgid) {
$scope.sgvm.gridData.splice(i, 1);
return false;
}
});
$scope.loading = false;
}).error(function(err) {
debugger;
$scope.error = "An Error has occured while deleting Friend! " + err.val();
$scope.loading = false;
});
};
}
GetProgram Function:
public class PPCRSearchController: ApiController {
private DataContext db = new DataContext();
static readonly IPPCRRepository repository = new ProgramRepository();
[HttpGet]
public SearchGridViewModel GetProgram() {
var b = repository.GetProgram(1, 10);
return b;
}
}
ProgramRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class ProgramRepository: IPPCRRepository {
public SearchGridViewModel GetProgram(int page, int pagesize) {
using(DataContext dbcontext = new DataContext()) {
SearchGridViewModel ddl = new SearchGridViewModel();
var lstProgram = from r in dbcontext.Program select r;
var a = Converter.LProgramDTO(lstProgram.ToList());
ddl.gridData = (0 == page ? null : a.Skip((page - 1) * pagesize).Take(pagesize).ToList());
// calculated number of pages and ceil the value
ddl.NumberOfPages = ((int) Math.Ceiling((double) a.Count / pagesize));
return ddl;
}
}
}
}
SearchGridViewModel function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class SearchGridViewModel {
public List < ProgramDTO > gridData {
get;
set;
}
public int NumberOfPages {
get;
set;
}
}
}
ProgramDTO:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class ProgramDTO {
public int ProgramID {
get;
set;
}
public string ProgramName {
get;
set;
}
public int SiteID {
get;
set;
}
}
}
The records are saved successfully in database.But while trying to fetch it is not displayed.