ASP.NET Core 6 Create data in the database with swagger - asp.net-core-6.0

As it says in the title, I want to save data in the database by entering the data in the swagger, for this I made a service layer and controller and in the backend is the model and in frontend the dto.
Service Class
public async Task<SuperHeroDto> Create(SuperHeroDto dto)
{
#region
_firstAPIDatabaseContext.SuperHeroes.Add(dto);
var saveChangesAsync= await _firstAPIDatabaseContext.SaveChangesAsync();
}
I have the problem here:
_firstAPIDatabaseContext.SuperHeroes.Add(dto);
enter image description here
I want to learn it on my own, but need tips on how to do it.
I also created a profile for folders

I don't know the difference between SuperHeroDto and SuperHero in your code.
But obviously the code you provided is wrong to store SuperHeroDto objects in SuperHeroes.
Maybe you can write
_firstAPIDatabaseContext.SuperHeroeDto.Add(dto);

Related

How to get metadata from MongoDB with Breeze

Currently I have a project using WebAPI and EF with Breeze, it works fine with Metadata stuffs for validation on server but when migrating to NodeJS and MongoDB, I get stuck for trying get Metadata from MongoDB. I checked out zza BMEAN app but I just saw on this project:
app.get('/breeze/Breeze/Metadata', getMetadata);
function getMetadata(req, res, next) {
next({
statusCode: 404,
message: "No metadata from the server; metadata is defined on the client"
});
}
I also read all document about Breeze/MongoDB but still doesn't help me to get Metadata for this.
The main point is I just want to change backend with BMEAN instead of WebAPI+EF+Breeze, don't need to change code on client.
Thanks
The metadata is provided by EF, not by MongoDB. If you are using a CodeFirst approach with EF then you should already have a DBContext.
This talks about how to use the DBContext -
http://www.breezejs.com/documentation/entity-framework-dbcontext
This talks about how to use EF as a design tool to build your meta data from classes -
http://www.breezejs.com/documentation/ef-design-tool
Odds are you already have what you need to generate the metadata it is just extending that and exposing a service to provide it to the client.
PW Kad's answer is correct, but to clarify, there is no way to get metadata from a MongoDB database because the database itself has an indeterminate structure. So you have to tell your client what the structure is. If you want to use the same client code for EF and Mongo then saving the metadata provided by the EFContext in your Mongo project makes a lot of sense. In other cases simply define the metadata directly on the client via Breeze's metadata api calls.

How to use Custom Routes with Auto Query

Using the first example in the ServiceStack Auto Query documentation in a project structured similar to the EmailContacts sample project (i.e. separate projects for the ServiceModel and ServiceInterface), how would one register the custom route "/movies" defined by the Route attribute?
[Route("/movies")]
public class FindMovies : QueryBase<Movie>
{
public string[] Ratings { get; set; }
}
Normally, custom routes such as these can be register by passing the ServiceInterface assembly when instantiating AppHostBase:
public AppHost() : base("Email Contact Services", typeof(ContactsServices).Assembly) {}
However, the FindMovies request DTO does not have an associated service and therefore won't be included. No routes are registered.
If I pass typeof(FindMovies).Assembly instead of or in addition to typeof(ContactsServices).Assembly, then the pre-defined route will be registered (i.e. shows up in the metadata, postman, etc.) but the custom route is still not registered (i.e. does not show up in the metadata, postman, etc.).
What is the best way to register the custom route using attributes when there is no service and the ServiceModel and ServiceInterface are in separate projects?
These issues should be resolved in v4.0.24+ that's now available on MyGet.
There's a new AutoQueryFeature.LoadFromAssemblies property to specify an additional list of assemblies to scan for IQuery Request DTO's. This automatically looks in the assemblies where your other Request DTO's are defined so in most cases nothing needs to be done as it will automatically be able to find your query services.
The routes for Query DTO's should now appear on the metadata pages as well as Swagger and Postman metadata API's.

Can I or Should I use a Global variable in Angularjs to store a logged in user?

I'm new to angular and developing my first 'real' application. I'm trying to build a calendar/scheduling app ( source code can all be seen on github ) and I want to be able to change the content if there is a user logged in (i.e. display details relevant to them) but here's the catch:
I don't want the app to be dependent on having a logged in user ( needs to be something that can be configured to work publicly, privately or both)
I don't want to implement the user/login within this app if it can be avoided ( I want to eventually include my app in another app where this might be implemented but isn't necessarily implemented using any particular security frameworks or limited to any)
I had an idea of creating some global variable user that could be referenced through out my application, or if I had to implement a system to do it all in this app that I could do so in in some abstract way so that different options could be injected in.
some of my ideas or understanding of what I should be doing may be completely wrong and ignorant of fundamentals but I genuinely do not know what approach I should take to do this.
In case it is relevant I currently don't have any back-end but eventually hope use MongoDB for storage and nodejs for services but I also want to try keep it open-ended to allow others to use different storage/backends such as sql and php
is there away to have a global uservariable/service that I could inject/populate from another (parent?) app?
If so what would be the best approach to do so?
If Not, why and what approach should I take and why?
Update
I Believe from comments online and some suggestion made to me that a service would be the best option BUT How would I go about injecting from a parent application into this applications service?
If your (single) page is rendered dynamically by the server and the server knows if you are logged-in or not, then you could do the following:
Dynamically render a script tag that produces:
<script>
window.user = { id: 1234, name: 'User A', isLoggedIn: true };
</script>
For non logged-in users:
<script>
window.user = { isLoggedIn: false };
</script>
For convinience, copy user to a value inside angular's IOC:
angular.module('myApp').value('user', window.user);
Then, you can use it in DI:
angular.module('myApp').factory('myService', function(user) {
return {
doSomething: function() {
if (user.isLoggedIn) {
...
} else {
...
}
}
};
});
Something tricky (which you should thing twice before doing [SEE COMMENTS]) is extending the $scope:
angular.module('myApp').config(function($provide) {
$provide.decorator('$controller', function($delegate, user) {
return function(constructor, locals) {
locals.$scope._user = user;
return $delegate(constructor, locals);
};
});
});
This piece of code decorates the $controller service (responsible for contructing controllers) and basically says that $scope objects prior to being passed to controllers, will be enhanced with the _user property.
Having it automatically $scoped means that you can directly use it any view, anywhere:
<div ng-if="_user.isLoggedIn">Content only for logged-in users</div>
This is something risky since you may end up running into naming conflicts with the original $scope API or properties that you add in your controllers.
It goes without saying that these stuff run solely in the client and they can be easily tampered. Your server-side code should always check the user and return the correct data subset or accept the right actions.
Yes you can do it in $rootScope. However, I believe it's better practice to put it inside a service. Services are singletons meaning they maintain the same state throughout the application and as such are prefect for storing things like a user object. Using a "user" service instead of $rootScope is just better organization in my opinion. Although technically you can achieve the same results, generally speaking you don't want to over-populate your $rootScope with functionality.
You can have a global user object inside the $rootScope and have it injected in all your controllers by simply putting it into the arguments of the controller, just as you do with $scope. Then you can implement functionalities in a simple check: if($rootScope.user). This allows you to model the user object in any way you want and where you want, acting as a global variable, inside of Angular's domain and good practices with DI.
Just to add on my comment and your edit. Here is what the code would look like if you wanted to be able to re-use your user service and insert it into other apps.
angular.module('user', []).service('userService', [function(){
//declare your user properties and methods
}])
angular.module('myApp', ['user'])
.controller('myCtrl', ['userService', '$scope', function(userService, scope){
// you can access userService from here
}])
Not sure if that's what you wanted but likewise you could have your "user" module have a dependency to another "parent" module and access that module's data the same way.

ServiceStack Service structure for predominantly read-only UI

I'm getting started with ServiceStack and I've got to say I'm very impressed with all it has under the bonnet and how easy it is to use!
I am developing a predominantly read-only application with it. There will likely be updates to the database 3 or 4 times a year but the rest of the time the solution will be displaying data on an electronic information board (large touch screen monitor).
The database structure is well normalised with a few foreign keyed tables and with this in mind I think it may be best to separate the read only API from the CRUD API. The CRUD API can be used to create and modify the relational data with POCO classes matching the database tables. I would then ensure the read-only API flattens the relational data into a few POCOs spanning a few db tables making the data easier to handle on the read-only UIs.
I'm just looking for ideas and advice really on whether this separation of concerns is wasted effort or if there is a better way of achieving what I need? Has anyone had similar thoughts / ideas?
Having developed a similar read only application (a gazetteer, updated quarterly/yearly) using ServiceStack we went with optimizing the API for reads, making use of the built in caching:
// For cached responses this has to be an object
public object Any(CachedRequestDto request)
{
string cacheKey = request.CacheKey;
return this.RequestContext.ToOptimizedResultUsingCache(
base.Cache, cacheKey, () =>
{
using (var service = this.ResolveService<RequestService>())
{
return service.Any(request.TranslateTo<RequestDto>()).TranslateTo<CachedResponseDto>();
}
});
}
Where CacheKey is just:
public string CacheKey
{
get
{
return UrnId.Create<CachedRequestDto>(string.Format("{0}_{1}", this.Field1, this.Field2));
}
}
We did start creating a CRUD / POCO service, but for speed went with using bulk import tools such SQL Server DTS/SSIS or console apps which suffices for now, and will revisit this later if required.
Might want to consider something like CQRS.
https://gist.github.com/kellabyte/1964094 (or Google for CQRS Martin Fowler, can only post 2 links).
Also found the following article valuable recently when starting to implement additional search type services: https://mathieu.fenniak.net/stop-designing-fragile-web-apis/

Implementing "Sign Up/Register," when CRUD methods are protected with #Check('admin')?

I have a simple application using the Play! framework's secure module. My 'Users' controller extends CRUD and is protected by #Check('admin'), so users have to be admins to access CRUD methods. However, I'd like anyone to be able to create new Users-- like a "Sign Up" or "Register" button.
What is a good way to do this, given that all of my Users methods except Create should be protected? Can I apply #Check("admin") to individual methods?
Here is my Users controller:
package controllers;
import play.*;
import play.mvc.*;
#Check("admin")
#With(Secure.class)
public class Users extends CRUD {
};
What is a good way to do this, given that all of my Users methods except Create should be protected?
In my practice, I create new controller in another package with the same name for doing this.
For example,
So, I think the best way is you should put Sign up method in the Non-Admin.
After I find some reference, this link has same idea with you and the answer of this topic is like what I said.
Can I apply #Check("admin") to individual methods?
Yes, you can. But you need to use #With(Secure.class) in that controller first.
You can see the example in Secure Module Documentation.

Resources