How do I save a custom entity in the Sensenet database? - entity

I'm trying to save a custom entity in the Sensenet database with an api call.
How do I create the model in the Sensenet database? Preferably in the ASP.NET project or with an api call from the front-end.
What url do I POST the entity to, to save it in the model I just created?
Here is the Angular TypeScript entity I want to save:
export class PersonEntity {
public name: string;
public email: string;
}
At first this will only be two text fields, to keep it simple. Later on I'd like to add an image too.

Related

Is there any way to initialize settings model of c# on startup from the JSON settings available in the database in .net core?

I have created a web application in which I am using .net core 3.0 as server-side technology and have Postgres as backend. I have a table called settings in the database in which I am storing settings as JSON using JSON data type available in Postgres.
Now I want to initialize my settings model in the application from the JSON data available in the database. I want to initialize the model at the start of the application and use it throughout the application wherever needed to avoid the database roundtrips for fetching the settings from the database on demand.
Is there any way to achieve this?
Following is the Json data in the database:
{
"CurrencyCode": "USD",
"CurrencySymbol": "$"
}
Here is my C# model in the application
public class SettingsModel
{
public string CurrencySymbol { get; set; }
public string CurrencyCode { get; set; }
}
I was thinking to achieve this in the following way but still does not have idea about what and how to use it.
Initializing the model using singleton service
services.AddSingleton<SettingsModel, GetJsonSettingsFromDatabase()>();
GetJsonSettingsFromDatabase() will return the SettingsModel after deserializing the settings from DB to SettingsModel .
I also wanted some function that will contain the logic for updating the SettingsModel so that I can invoke the same when there are changes in the database table for settings.
Initializing the model using singleton service should use the factory delegate
For example.
services.AddSingleton<SettingsModel>(sp => return GetJsonSettingsFromDatabase());
assuming
GetJsonSettingsFromDatabase() will return the SettingsModel after deserializing the settings from DB to SettingsModel.
The same could have been done with an instance
SettingsModel settings = GetJsonSettingsFromDatabase();
services.AddSingleton(settings);
As for
I also wanted some function that will contain the logic for updating the SettingsModel so that I can invoke the same when there are changes in the database table for settings.
Then do not register it as a singleton. Consider caching the settings instance to avoid round trips and only loading fresh instance as needed.

Few queries about InitializeSimpleMembership class usage in ASP.Net MVC4

i am new in MVC. so i just create a mvc project with vs2013 with internet template. i found one class called InitializeSimpleMembership. tell me what is the usage of this class.
i put break point on this function OnActionExecuting & SimpleMembershipInitializer and saw this function is getting called when i try to access any protected page or when i am clicking on login or register link. i need some insight about this class InitializeSimpleMembership.
what this line is doing LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); ?
tell me what the below routine is doing
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized.", ex);
}
}
i could understand this line context.Database.Exists() is trying to check a specific db is exist or not. which db it is trying to check exist or not?
what this line is doing WebSecurity.InitializeDatabaseConnection() ?
guide me what i need to do as a result simple membership provider create required table and i could validate user against my database.
tell me what if i need to add more fields then what i need to do.
looking for guidance. thanks
The SimpleMembership provider has been introduced with ASP.NET MVC 4. It extends the core membership and role providers in order to make more flexible the way in which user information are stored in a custom database.
The attribute InitializeSimpleMembershipAttribute takes care of initializing the simple membership provider, defining which context class should be used to work with the database (the UserContext class).
The WebSecurity.InitializeDatabaseConnection initializes the membership system specifying the database through the connection string (“DefaultConnection”), the name of the table in which the user profile data are stored (“UserProfile”) and the name of the field that should be used for the login and so to match the user profile with the membership account.
The method LazyInitializer.EnsureInitialized just ensures that the simple membership is initialized once.
This attribute creates the tables necessary for managing membership in the database specified by the connection string. So it creates the table for the UserProfile model class with the columns “UserId” and “UserName” and uses the “UserId” as a foreign key to relate with the other auto generated tables needed for authentication and authorization.
The AccountController that contains all the basic operations that can be performed on the user profile is decorated with the attribute and in this way every time the user tries to login or register the simple membership is automatically initialized.
http://weblogs.asp.net/jongalloway/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates

how do I configure a (MVC using entity framework) controller in a web api project

I have a MVC 4.0 Web API project and I have already added the model of my database to it so I have the files:
.edmx
.Context.tt
.context.cs
.edmx.diagram
I'm trying to figure out how to add a controller after I've created my entity framework model.
It's asking for the Model Class and Data context class.
I'm not sure what they are in my solution.
can anyone give me a hand?
It depends what you are trying to do...
1. you can create an empty controller and then you do not need to select the Model and Context. you write the Add/Edit/Delete functions yourself and their views.
2. you can create a controller with read/write action and views - this way you get these functions Add/Edit/Delete + views done for you automatically:).
The Context is (as I understand it) the reference to the database.
if you havent already you should add your model classes that you want to create as tables in the database to the YOUR-PROJECTNAMEContext.cs file under DAL folder. this will create the tables for you (if I didn't forget anything). you shoula add somethis like:
public DbSet<Note> Notes { get; set; }
where Note is your class for example and Notes is your table name.
now if you want to create a Controller for you notes class in the model and let MVC to do for you the ADD/Edite/Delete function and views than your model is: Note and Context is YOUR-PROJECTNAMEContext.
Hope it will help.

Writing a Custom Hive Provider using objects as datasource

Im trying to create a hive provider that would be able to work towards some objects.
An object may look something like this
public class MyContent
{
public System.Collections.Generic.List Content { get; set; }
}
public class ContentExample
{
public string Title { get; set; }
public string Text { get; set; }
}
public class MyFiles
{
public System.Collections.Generic.List Files { get; set; }
}
public class FileExample
{
public System.IO.FileInfo File { get; set; }
}
I've downloaded and checked the two Hive providers from the Visual Studio Gallery (Umbraco 5 Hive Provider and Umbraco 5 Simple Hive Provider), but the lack of documentation is a bit disturbing. I also downloaded some of the other example hives, like the Wordpress hive provider, but that one is rather different from the ones in the Visual Studio Gallery.
The Idea
Im used to working with stuff like ObjectDataSource, the example above could be complemented with full CRUD if required.
Now, I assume one Hive provider would be able to serve different parts of Umbraco with content (right?). Just set up a new Repository and go? I have now clue how to connect all parts or even how to get the data into the provider yet.
Any help in how I could bring all pieces together?
Thanks
The first step is to take a step back and evaluate your business requirements. Will you allow for users to be updating the information with forms in the frontend? Do you need a tree editor for the content in the backoffice? Do you need to be work with data outside of the built-in ORM?
If the answer to these is no, a hive provider is overkill. Evaluate solutions using either a simple surface controllers, or just a custom document type. Umbraco 5 is a full EAV/CR system, so unlike some CMS products, you'll be able to represent any rdbs structure you can imagine
ContentExample could be represented be a document type called 'Article', which has properties Title and Text. Just by defining this document type we're instantly given add and edit forms for our back office users in our content section. We can even restrict which nodes are able to have children of type 'Article', e.g News.
In the same way, an upload control is a field type that allows you to attach files to your document.
So what's point of a custom hive provider?
The goal of a custom hive provider is to unify CRUD actions for data access layers.
As a result data can be stored in the baked-in nhibernate orm, custom tables, rss feeds, or even flat files, while still using a common interface to retrieve and update it. If this sounds like what you're aiming for, read on.
Going back to the business requirements, specifically, where do you want to actually store the data?--Given that you have some fields and properties related to flat file storage, let's say that one TypedEntity (a model) is equivelant to one file and write some pseduocode:
The first step, is as you say 'get the data into the repository.' This involves going back to that VS template and filling in the 'not implemented' methods with your logic for storing and retrieving data.
protected override void PerformAddOrUpdate(TypedEntity entity)
{
// step 1: serialize the typed entity to xml
// step 2: write the file to the hdd, making sure that the file name is named using the hive id so that we can pull it back later.
}
Once you've written the data access layer, or DAL, you can hook it up in the hive config, giving it url to match. e.g. rather than matching content:\\, yours might match on file-manager:\\
We can allow our backoffice users to be able to add new entities (indirectly, new files) by writing a custom tree, and we can display the results to our front-end users via macros.

asp.net mvc without entity framework

I am learning asp.net mvc and went through a great tutorial that demonstrated it. The tutorial also used Entity Framework.
We have our own data access class which I have to use.
I am a little bit confused as to what I need to do to bridge the gap between our class and MVC framework.
For example, in the tutorial, inside of MovieController.cs file, there is a Edit method, that looks like this:
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
If I don't use the Entity framework, what would it look like? Will I still need to use ModelState.IsValid and save the state like it's done
db.Entry(movie).State = EntityState.Modified;
Please advise. A clearly written example of using asp.net mvc without the use of Entity framework would be great.
What I need to know is what role does state play here and whether it is mandatory to use or is it just a part of how the Entity framework operates.
I would re-write this as:
[HttpPost]
public ActionResult Edit(Movie movie)
{
myDBObject.SaveChanges();
return RedirectToAction("Index");
}
Where myDBObject is my custom database access object.
The examples you see out there where controllers use directly some data access framework such as Entity Framework are bad examples. The whole internet is polluted with such stuff. I can hardly look at it without having my eyes hurt. I consider those as bad practices. Data access should be separated and abstracted in a repository. So for example:
public interface IMoviesRepository
{
Movie Get(int id);
void Save(Movie movie);
}
then you could have some implementation of this interface using plain ADO.NET, EF, NHibernate, a remote web service call, some custom ORM or really whatever:
public class MyCustomFrameworkMoviesRepository: IMoviesRepository
{
...
}
and the controller will take this repository interface as constructor argument:
public class MoviesController: Controller
{
private readonly IMoviesRepository _repository;
public MoviesController(IMoviesRepository repository)
{
_repository = repository;
}
public ActionResult Index(int id)
{
var movie = _repository.Get(id);
return View(movie);
}
[HttpPost]
public ActionResult Index(Movie movie)
{
if (!ModelState.IsValid)
{
return View(movie);
}
_repository.Save(movie);
return RedirectToAction("Success");
}
}
and the last part is to configure your dependency injection framework to pass the correct implementation of the repository into the controller. Now as you can see the way the data is fetched is completely decoupled from the controller logic. It is the way it should be. Always try to avoid the strong coupling between the different layers of your application.
And to answer your question about the State property : this is something completely specific to EF, seeing something like this in a controller is a really pity.
And to bring this even further and improve it you would introduce view models. View models are classes which are specifically designed to meet the requirements of a given view. So for example Movie is a domain model. Domain models should never be directly passed to views. Controller actions should never take domain models as action arguments. You should define view models which will contain only what is required by the given view and then perform the mapping between the view models and the domain models. Frameworks such as AutoMapper make this very simple.
hmm.
MVC and entity framework really have nothing to do with each other; they just work well together.
the if (ModelState.IsValid) validates your view model. If you are not using view objects with validators, it's a little pointless; if you are, then it's quite valuable.
inside the if (ModelState.IsValid) brackets, you would take the post data from your web page (usually a view model) and apply it to the object that will persist it to the database. EF is often used because once it's set up, it's fairly easy to maintain, and a lot less code to write.
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
are both EF-related. These would need to be replaced by your repository class methods and objects.
return RedirectToAction("Index");
is MVC. Upon successful persistence to your data store, return the control to the index page.
return View(movie);
is used to redirect back to the original view, because something failed validation.
You would still check ModelState.IsValid, but otherwise your code would look like what you have.
This assumes that your model has DataAnnotations attributes on it, though, which is what ModelState.IsValid is using to check. Those attributes can be used on any C# class' properties - not just Entity Framework.
You might end up creating specific view models for this purpose.
You need to make some connection between the Movie object (passed in on the http POST) and your database methods (myDBObject).
Maybe you want to say myDBObject.SaveChanges(movie) and assuming your db code knows how to handle the object Movie then you'll be fine.