Read local json file and show the data in UI for blazor server - json

I have one blazor. Net 5 web application.I have added one json file. Need to call that json file to razor page and show the data in UI for blazor server.
#page "/"
#inject HttpClient Http
#if (employees == null)
{
<p>Loading...</p>
}
else
{
#foreach (var employee in employees)
{
<p>Employee ID: #employee.Id</p>
}
}
#code {
private Employee[] employees;
protected override async Task OnInitializedAsync()
{
employees = await Http.GetFromJsonAsync<Employee[]>("employee.json");
}
public class Employee
{
public string Id { get; set; }
}
}
Getting the following error for the above code snippet -
Invalid operation exception: cannot provide a value for property 'http' on type
There is no registered service for type System.Net.Http.HttpClient
Kindly help with example. It is a huge blocker.

You are using dependency injection for an instance of HttpClient:
#inject HttpClient Http
and the error message is indicating that no HttpClient service has been registered. You need to register an HttpClient service: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0
Or you could use IHttpClientFactory and call CreateClient();

Related

Can't see the JSON result of a Get request in postman and shows empty string array

I have an ASP.NET CORE application that sends a POST/GET request to a REST (Orthanc Rest API). The issue is I receive the result and convert it to a JSON, but postman shows as an empty array. here is my code:
// GET Method
public class PACSController : ControllerBase
{
// GET: api/PACS
[HttpGet]
public async Task<object> Get()
{
var result = await Orthanc.Orthanc.InstanceAsync();
return result;
}
}
public class Orthanc
{
public static string baseUrl = "https://demo.orthanc-server.com/";
public static async Task<object> InstanceAsync()
{
string url = baseUrl + "instances";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage res = await client.GetAsync(url))
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
var jData = JsonConvert.DeserializeObject(new string[] { data }[0]);
return jData;
}
}
}
The result of request inside the code
Postman result
As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json has been removed from the ASP.NET Core shared framework for asp.net core 3.x.
Follow the steps:
Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package on nuget.
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Update Startup.ConfigureServices to call AddNewtonsoftJson.
services.AddControllersWithViews().AddNewtonsoftJson();
Reference:
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project

Nested Transactions with MySQL and Entity Framework Core

I'm using MySQL with EF Core. I am currently using Pomelo Provider for MySQL. I need to implement Unit Of Work Pattern for transactions. I have a Service which calls two methods in repository. I am not able to implement nested transactions. This is how my method in service looks now:
public void methodA(param)
{
using (TransactionScope tx = new
TransactionScope(TransactionScopeOption.Required))
{
repo1.save(data1);
repo2.save(data2);
tx.complete();
}
}
This is how save method in repo1 is implemented
private readonly UserDbContext appDbContext;
public repo1(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(User entity)
{
var dbset = appDbContext.Set<User>().Add(entity);
appDbContext.SaveChanges();
}
This is how save method in repo2 is implemented
private readonly UserDbContext appDbContext;
public repo2(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(UserRole entity)
{
var dbset = appDbContext.Set<UserRole>().Add(entity);
appDbContext.SaveChanges();
}
I am getting the following error while running method in service:
Error generated for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.AmbientTransactionWarning: An ambient transaction has been detected. The current provider does not support ambient transactions. See http://go.microsoft.com/fwlink/?LinkId=800142'. This exception can be suppressed or logged by passing event ID 'RelationalEventId.AmbientTransactionWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
This is how I registered UserDbContext in Startup.cs
services.AddDbContext<UserDbContext>(options => options.UseLazyLoadingProxies().UseMySql("Server = xxxx; Database = xxx; Uid = xx;ConnectionReset=True;", b => b.MigrationsAssembly("AssemblyName")));
I even tried adding a middleware which starts transaction at the begining of request and commits/rollbacks during the response . But still I am not able to manage nested transactions.
This is how my middleware looks:
public class TransactionPerRequestMiddleware
{
private readonly RequestDelegate next_;
public TransactionPerRequestMiddleware(RequestDelegate next)
{
next_ = next;
}
public async Task Invoke(HttpContext context, UserDbContext
userDbContext)
{
var transaction = userDbContext.Database.BeginTransaction(
System.Data.IsolationLevel.ReadCommitted);
await next_.Invoke(context);
int statusCode = context.Response.StatusCode;
if (statusCode == 200 || statusCode==302)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
Can anyone help me please?

How to correctly load Firebase ServiceAccount json resource with Spring MVC?

I'm trying to connect my Spring MVC (not Spring Boot) application to Firebase. My application's folder structure looks like this:
folder structure
The problem is that I don't know where to place the api key json file, how to load the resource, and the correct order of the method calls.
I tried loading the resource the way shown below. Before that I also tried using ClassLoader to load it from the WEB-INF folder and it worked, but changed the code and kept receiving NullPointer Exception (why not FileNotFound Exception?) for the InputStream and couldn't restore the previous state.
With the current state I keep receiving FileNotFound Exception as I'm am not able to load the resource no matter how much I googled "Spring MVC load resource" and as I checked the debugger the service account's "init" method with #PostConstruct isn't running at starting the server.
I understand that I should be able to load the resource and call the "init" method in order to make it work. (I suppose it's enough to call it once after creating the bean and before using firebase methods) But I just couldn't come up with a working implementation.
I used examples from here:
https://github.com/savicprvoslav/Spring-Boot-starter
(Bottom of the Page)
My Controller Class:
#Controller
#RequestMapping("/firebase")
public class FirebaseController {
#Autowired
private FirebaseService firebaseService;
#GetMapping(value="/upload/maincategories")
public void uploadMainRecordCategories() {
firebaseService.uploadMainRecordCategories();
}
My Service Class:
#Service
public class FirebaseServiceBean implements FirebaseService {
#Value("/api.json")
Resource apiKey;
#Override
public void uploadMainRecordCategories() {
// do something
}
#PostConstruct
public void init() {
try (InputStream serviceAccount = apiKey.getInputStream()) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl(FirebaseStringValue.DB_URL).build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
e.printStackTrace();
}
}
}
how about saving value in a spring property and using #Value("${firebase.apiKey}")?
Alternatively, save path to file in property and reference that in #Value()
#Value("${service.account.path}")
private String serviceAccountPath;
In application.properties:
service.account.path = /path/to/service-account.json
then config code:
private String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(getServiceAccountInputStream())
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging"));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
private InputStream getServiceAccountInputStream() {
File file = new File(serviceAccountPath);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("Couldn't find service-account.json");
}
}

Queries leading to data modification are not allowed grails

In my current application i have a service which uses a saxparser to read some xml. In saxparser i try to store a new objectto the database but i get the following error:
ERROR util.JDBCExceptionReporter - Connection is read-only. Queries leading to data modification are not allowed
My Service looks like so:
#Transactional
class SchedulingService {
def printIets() {
LessonParser par = new LessonParser()
print "de service macheert ier e trut"
par.parse(["src/data/tweede/"])
}
}
The parser:
class LessonParser {
public void parse(baseFileLocations){
....
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
LessonHandler handler = new LessonHandler()
saxParser.parse(is, handler);
...
}
}
And finally the handler where the attempt to save something to the database is made
class LessonHandler extends DefaultHandler{
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("TTSession")) {
//voorlopig enkel hoorcolleges
if (parse && this.courseType == CourseType.HC) {
Course course = new Course (name:this.name , info:this.info,courseType:this.courseType,creator:this.creator)
course.save()
}
}
}
}
The error occurs when i try to save a course in the above handler.
Also i'm using a mysql database
I had connected the service to a restful api, i forgot an #transactional definition there. Adding it did the trick
Thanks for sharing.
the service got a "#Transactional(readOnly = true)" definition. So all the methods will be read only.
If you want to do some modification, you need to add "#Transactional" before the method.

Jersey 2.2: output xml OK, but fails on json

I've run into a weird problem.
I use Jersey 2.2 to do my restful web services (with jersey-media-moxy).
If I produce my output as application/xml, it runs fine.
But if produce my output as application/json, I get "Internal Server Error 500".
My dependency settings in ivy.xml are:
<dependency org="org.glassfish.jersey.core" name="jersey-server" rev="2.2"/>
<dependency org="org.glassfish.jersey.containers" name="jersey-container-servlet-core" rev="2.2"/>
<dependency org="org.glassfish.jersey.media" name="jersey-media-moxy" rev="2.2"/>
My service class is:
#Path("/projects/{companykey: [0-9]*}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class ProjectResource {
private static Logger logger = Logger.getLogger(ProjectResource.class);
private final Application app = Application.getInstance();
#GET
public List<ProjectBase> getProjectBases(
#PathParam("companykey") String companyKeyStr) {
...
}
#GET
#Path("/{projectkey: [0-9]*}")
public ProjectBase getProjectBase(
#PathParam("companykey") String companyKeyStr,
#PathParam("projectkey") String projectKeyStr) {
int companyKey = Integer.valueOf(companyKeyStr);
int projObjKey = Integer.valueOf(projectKeyStr);
logger.debug(MessageFormat.format("get project {1} of company {0}",
companyKey, projObjKey));
ProjectBase project = null;
try {
project = app.getProjectIF().getProjectBase(companyKey, projObjKey);
if (project == null) throw new WebApplicationException(404);
return project;
} catch (ServerException se) {
logger.warn("get project fails ! " + se);
throw new WebApplicationException(500);
}
}
...
}
//class end
If I ask for the xml output (visit http://biz.loc.net:8080/tm/rest/projects/100/104), I get:
<projectBase>
<_checkTopicAccess>false</_checkTopicAccess>
<_checkTaskAccess>false</_checkTaskAccess>
....
If I ask for the json output, I get:
HTTP Status 500 - Internal Server Error
type Status report
message Internal Server Error
description The server encountered an internal error (Internal Server Error) that prevented it from fulfilling this request.
I do not find any error messages in my app's log file or Tomcat's log file, so I have no
idea what is going on.
Does anyone know any possible reason for this problem? Really appreciate ...
Can you show the entity code? Are you missing an empty constructor?
Thanks for your help, the following code snippet is my entity clas:
#XmlRootElement
public class ProjectBase implements UdaEnabled, SdaEnabled, FormBean {
private int projObjKey;
private String projName;
//...
private Timestamp createdAt;
//...
//...
#XmlElement(name = "createdAt")
#XmlJavaTypeAdapter(TimestampAdapter.class)
public Timestamp getCreatedAt() {
return createdAt;
}
// non-args Constructor
public ProjectBase() {
init();
}
}
It does has an empty constructor, although these's a init() inside.
As I said, I think it is weird because producing xml is OK.