I am a little confused on how to go about using the RESTful server API in SilverStripe 3. I have just starting learning and the following has confused me.
All content on our site is stored in a database. Each class that is a child of the DataObject class will have its own table in our database.
Every object of such a class will correspond to a row in that table - this is our "data object", the "model" of Model-View-Controller. A page type has a data object that represents all the data for our page. Rather than inheriting directly from DataObject, it inherits from SiteTree. We generally create a "Page" data object, and subclass this for all other page types. This allows us to define behavior that is consistent across all pages in our site.
I have done this to set up pages but now I am learning about the RESTful server API and it says to create an object that extends DataObject.
Forgive my ignorance but would extending SiteTree not be the same thing?
Very confused so would appreciate some enlightenment.
As commented above, if you extend SiteTree, then you are extending DataObject, but getting a lot of overhead. Some of this overhead may be useful to you, as SiteTree provides Versioning, Hierarchies and other nice tricks which make it a good class for Pages in your site.
However, if you are wanting to manage a lot of objects, or if you aren't using the Hierarchy or Versioning models, or if you just want to customize how the objects are presented or managed in the CMS, then it is better to extend DataObject directly. There are various tutorials on this on the SilverStripe documentation site, and on SSBits
This may also be useful to you.
Once you have your DataObject subclass working well for you, you can start to add the RestfulServer capabilities to it. The most basic way to do this is to add a static property to your class:
static $api_access = true;
More information about using RestfulServer is available here
Have you had a look at the following URL : http://doc.silverstripe.org/framework/en/reference/restfulservice
This example allows you to make data available in the RSS format. I'm not sure if there is an easy way to output the data as JSON, but there are plenty of examples on the web of converting rss to json, so you could simply update your app to work with this format and convert if need be.
Related
I have a component that acts as a middle man between 2 web services. Both of them communicate using JSON.
The data that goes back and forth from the web services is very similar. However, it does need to be massaged a little.
I currently have this working by deserializing the JSON, build a new JObject and serialize it. It seems like there should be better way.
I'm looking at JsonConvert, JsonConverter, JsonSerializer, JsonReader, etc. trying to see if there's a better way to do this.
Any guidance on what classes to use/override to make this process more efficent?
Thanks!
You can write a custom JsonConverter using the approach described in the documentation, so you'll only have one concrete class, but this class can translate to a slightly different JSON representation of your object.
Another, more verbose, blog post about writing custom JsonConverters can be found here: http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/
I'm not an ASP.NET programmer, but, as it happens in life, I had to do some minor projects using it. Now came another one in which I have to implement some custom solutions and I haven't figured it out yet - I need some tip or maybe a piece of advice like "don't go that way" ;)
Previously it was simple - there was a table in DB, there was an adequate model and a view that worked with it - worked like charm. Now it's a little bit more complicated.
The "site" is going to contain, shortly and generally speaking, a survey - but a fully configurable one, unfortunately. In another product there's gonna be a configuration manager that will allow user to define pages, block types, questions, steps and so on and will generate an XML.
For the time being, in accordance with the specification, in the site's database I'm going to have only one table which will contain just a key and the XML generated by the configurator (and maybe some additional, not important information). Now - I need to parse this XML and build the site containing pages and other elements corresponding to it.
And that WOULD not be a problem, but I don't really know how to work that way using asp.net + mvc and can't find any piece of advice that would help me anyhow. Should I create an object that would somehow fake being a model and allow me to work for example on a dataset generated from XML? Or just create a model of the mentioned table and work with the XML directly on the view (I don't like even such an idea itself)? Or - having to do something like that - just give up on MVC and use only "clear" ASP.NET? Or maybe something else?
I'll be very grateful for any help.
And I hope I described what I need understandably ;)
If the XML documents have a schema defined then you can easily generate a class that matches the document using the xsd.exe tool. The document can then be deserialized into an instance of that class using existing functionality in the .Net framework. Just google .Net Xml serialization :-)
Now, if you don't have a schema you could create one if you are sure that you know the format of the Xml. Alternatively you could create a class that matches the format you expect to get and then parse the Xml manually. This last option is much more work, so I wouldn't recommend it.
In any case, the class you end up with should contain all the data you need from the Xml document and can then be used as the Model in your MVC page. As long as you can use the standard Xml deserialization technique then this should be quite easy and painless.
Most MVC tutorials I've been reading seem to create 4 View objects for each Model. For example, if my Model is "Foo", there seem to be 4 .cshtml files: Foo/Create, Foo/Delete, Foo/Details, and Foo/Edit. Using the VisualStudio "scaffolding" helper does this as well.
Is this really considered MVC best-practice? It just feels wrong to have 4 classes that are 80-90% identical to each other. When I add a new field to Foo, I need to edit all 4 .cshtml files. This sort of dual-maintenance (quad-maintenance?) just makes my OO skin crawl.
Please tell me: is there an expected/accepted best-practice which handles this differently? Or, if this really IS accepted best-practice, tell me why the quad-maintance shouldn't make me squirm.
I'm a reasonably skilled veteran of ASP.NET / c# / OO Design, but pretty new to MVC; so apologies if this is a noob question. Thanks in advance for your help!
Edit: thanks for all the replies! I marked the most thorough one as the answer, but upvoted all that were helpful.
You'll probably need between two and four different views:
List (for viewing many things)
View (for viewing a single thing. Might not be necessary, if it's OK to use Edit as View, or if List has room to show all properties)
Create
Edit (can be the same as create, if you code cleverly)
Thus, if your model doesn't have too many properties to show them all in a table, and if you're OK with not having a static, non-editable view for just examining, you can get well away with just List and Edit, and scrap the other two.
However, this doesn't solve your problem of double (or triple) maintenance if you update your model. There's other magic for that ;)
In ASP.NET MVC 3, there are extensions on HtmlHelper that let you do Html.DisplayForModel() and Html.EditorForModel(). These use predefined templates to nest themselves into your object and draw up display/edit fields for all public properites. If you pass DisplayForModel an IEnumerable<Foo>, it will create a table with column headers that are the property names of Foo (using the DisplayName attribute information if you supplied it) and where each row represent one Foo instance. If you give EditorForModel a Foo, it will create a <label> and an <input> for each public property on Foo.
All of the templates used by these powerful extension methods can be replaced by you, if you're not happy with the defaults. This can be done either on the level of Foo, in which case you'd be back in your double-maintenance scenario, or on lower levels (such as string or DateTime) to affect all editor/display fields generated with the templates.
For more information on exactly how this works, google "ASP.NET MVC 3 editor templates" and read a couple of tutorials. They'll explain the details much better than I could.
The views that ASP.NET MVC create for you don't necessarily need to be the views that you use in production. I found those just to be handy while developing quick prototypes or to test the database CRUD operations. Feel free to create whatever view(s) you would like to handle the operations.
I would generally just have 1 or 2 views to handle the basic operations and not use the built in views that are generated. For example, 1 view for adding, editing, or details and 1 view to show a list of objects.
It all depends on your application.
If you have a single item, you don't need a List view. If you can't edit it, then you don't need an edit view. Create and Edit can often be the same view, unless there are special things you need to do in one, but not the other.
In other words, use as many views as you need. There's no hard and fast rule here. The scaffolding is just there to help you on your way. Many kinds of apps will work just fine using the scaffolding, and won't require advanced HTML or Javascript.
Why would you want multiple views? Well, let's take the display and edit functions. You could create one view, in which you use if statements to determine the edit mode of the view, however this will complicated the view logic and views should be as simple as possible.
The reason to create seperate views is that its easier to maintain than one gigantic view with tons of conditional logic in it.
You can use exactly the same view when you are performing [HttpGet]. Given that you pass a proper ViewModel to this view, it will populate with appropriate data every time whether you are loading create, update, or delete Action.
The problem becomes apparent when you try to post that data to a specific Action.
Naturally View should have only one form, which will be used for posting data. When you declare this form, you specify which exactly Action to use for Post.
Having 3 different Submit buttons in that form will not make a difference since all of them will post the same form to the same Action.
You could do some javascript tweaking on OnClick event for these buttons to change Action to which data is posted, but this definitively would not be best practice.
Buttom line: having 4 different views for each of the CRUD actions is the best practice for MVC.
I tend to create the following for an object's CRUD ops:
index
_form (partial)
new
update
delete
view
As the same form is shared between new and update, there is very little difference between the two. It really depends on how much you want the variation to be, honestly.
As for delete, this is optional. I like to have a view in case javascript is disabled.
edit:
You mention view models and the guy above posted a long, convoluted (no offense) VM code sample.
Personally, I hate classes written to basically mirror domain objects and are only used to "move" data. I hate VMs. I hate DTOs. I hate everything that makes me have to write more code than is necessary.
I guess I've drank the coolaid of other frameworks (rails, sinatra, node.js) to the point where I can't stomach the idea of tossing DRY to the wind.
I personally say skip um.
Edit2 I forgot list..
I worked on DotNetNuke in some projects and I find very much interesting Custom Business Object Class which is named as CBO.vb in the DotNetNuke project.
So I want to use this helper class in my other project also which is not in DotNetNuke but in core asp.net projects.
So I read about some important methods of this class which are majority used by me are:
CBO.FillObject
FillCollection
Now I am searching what are issues in this class that can be improved by me before I am going to use this class.
So I search this and found an interesting topic on code project which point out several issues like:
business object and the fields in the database had to have the same name
FillCollection method returned an ArrayList
So my question is there any other thing which can be solved before use like
use reflection to create objects which are slower for that they give idea how to implement this by using The IHydratable Interface
You can find class here
CBO is a useful class. However if I were looking for a similar solution today, I would look to one of the new "Micro-ORMs" such as:
Massive
PetaPoco
Dapper
When applying such a light wrapper around the database, I am not sure that supporting different names in the DB and business objects is really a good idea. It is a likely source of confusion.
Also there are already generic overloads for the FillCollection method which return List<T>. The ArrayList versions are only there for backward compatibility, no one should write any new code with them.
I was watching a tutorial on Rails and was very impressed that you could so easily create an editing system for a class just by defining it.
Can this be done in ASP.NET?
I know there are ORMs out there, but do they come with an editing system?
To explain what I mean by an editing system, consider a class for defining people
class Person
{
string First_Name;
string Last_Name
}
And then perhaps with one bold stroke something like this:
CreateEditAbleClass(Person)
You would get the functionality below in a browser:
http://www.yart.com.au/images/orm_editor.jpg
And this functionality would extend to all the UML definitions – inheritance, association, aggregation etc. In addition, there would be a simple way of adding customisable validation and so forth.
I currently use DataGrids and a lot of manual coding to achieve these results.
You can do it with reflection. Using reflection, you can enumerate over the members of a class, and therefore create a form to edit the members.
Creating the code for rendering the web form based on the members of the class is a bit more code then I'm willing to type out here, but if you look into reflection you should be able to come up with your own solution in a couple hours.
Sure. This is off the top of my head, but I believe you could connect your class to an ObjectDataSource component which would in turn connect to a DetailsView control. So it's a hair more work, but it would be pretty trivial to have a method that created the needed items on the fly and bound them together.
This is called "Scaffolding".
It really depends on what you are using for your data layer or ORM. Entityspaces, for example, comes with a scaffolding generator.
Absolutely! Scaffolding in Ruby is known as Dynamic Data in ASP.NET. Scott Hanselman speaks to Dynamic Data here.
There's a screen cast from Scott Hunter that shows it off here. It's of note that it's pretty new (still in beta).
You can for simple sites/purposes but it quickly breaks down when you want to do something more complex. Like what happens if you don't want certain fields to be visible, what happens if you have a relationship to a subset of a certain class etc.
Having been down this path before I'm guessing you came at the issue by realizing that:
You spend alot of time creating similar forms/lists etc for similar entities.
You want to minimize this time and are considering if your forms can be automatically generated.
Basically, if you want it to be done automatically then you'll end up creating an overcomplicated system that does half of what you want and actually takes longer to implement.
If however, you want to drastically cut the amount of time doing and maintaining writing repetitive gui code then then I suggest using a declarative style form builder and table builder (like the form builder in ROR).
This lets you quickly create forms/tables without repeating yourself any more than necessary and also gives you the flexibility that you need for complex scenarios.