Umbraco Get properties of a Blog Post - json

I have Blog Repository and it contains blog posts list. I am accessing all Blog Posts by using this code
var contentType = ApplicationContext.Services.ContentTypeService.GetContentType("BlogPost");
var blogPostList = ApplicationContext.Services.ContentService.GetContentOfContentType(contentType.Id);
Now I am accessing custom data type properties by using
foreach (var blog in blogPostList)
{
foreach ( var property in blog.Properties)
{
}
}
Now I can access properties and get its value but for few properties I get json String and that is no use for me as I would need to create models to properly parse json string into proper json.
Is there any way to use GetPropertyValue in this situation or some other way to get properly formatted Json.

Stop right there!!! If this is for the front end DO NOT use the ContentService. This is specifically for the back end of the site, and is VERY database intensive.
For all front end code, you should be using IPublishedContent. This queries the content cache, and is MUCH faster, as there is no database access.
If you have an UmbracoHelper (which you will in Umbraco controllers), you have access to it out of the box, otherwise you need to spin up a helper. Here's an example:
var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var blogPosts = umbracoHelper. TypedContentAtXPath("//BlogPost [#isDoc]");
You will then have a list of pages, and can use the standard .GetPropertyValue methods to get the values out of the fields. Note, the XPath query here isn't super efficient, you could make it a lot more specific if you wanted to.

Related

Razor WebPage: How to make data from the database alvailable to several pages?

My question is quite similar to this one.
I get the same data (attributes of objects, each row represents an object) from the database for two of my pages, one page to edit the data and one page to view it. To reduce redundant code and to improve maintaining I wanted to write the piece of code that loads the data only once.
My idea was to use a _PageStart.cshtml. But with that I only can store strings in the PageData array but not Objects.
So what is the best way to make the rows from the database available on several pages?
Here is how I get the data from the database:
var db = Database.Open("mydb");
String query = "select * from motors";
var rows = db.Query(query);
System.Data.DataTable motors = new System.Data.DataTable();
motors.Columns.Add("posX", typeof(int));
motors.Columns.Add("posY", typeof(int));
IEnumerator<dynamic> en = rows.GetEnumerator();
while (en.MoveNext()) {
motors.Rows.Add(en.Current.posX, en.Current.posY);
}
I would like to access the DataTable motors on different pages.
All you have to do is create a page that only has your code in it, Then on whatever page you want it displayed just use:
#RenderPage("~/yourpage.cshtml");

What is the correct way to handle a POST request in Django class based view?

In my class based view I am handling a post request (which is an AJAX call).I am inserting some data in a database table and returning some json to the frontend.
def post(self,request,*args,**kwargs):
result_data = {}
doc = kwargs['doc']
doc_obj = Document.objects.get_document(doc)
doc_id = doc_obj.doc_id
reference_obj = Reference.objects.save_to_db(request,doc_id)
friendly_name = reference_obj.friendly_name
result_data['friendly_name'] = friendly_name
return HttpResponse(json.dumps(result_data),content_type='application/json')
My question is that is this the right way of handling a post request?My doubt arises here - I am writing some data into database and returning a json of properties of the same data I have written to the database.
Should I do it differently, ie first storing some data in database and returning just id of the row and again making GET request on the same URL?
I would say if it is an API, it is best to minimize the number of queries by returning the whole object the way you did. In case it is to serve a web user interface, it is simpler to return the id and get the rest of the data, if it needs to be displayed, from the client itself.
Either way is fine. The gain is negligible. I have also seen applications give a local positive feedback and then replace with a negative one if the request was unsuccessful. The technique can improve responsiveness, which is always appreciated.
Django-rest-framework returns the json of the inserted object, so i would think it reasonable to copy that behaviour.

How to query mongoDB using mongoose?

How do you query MongoDB using mongoose with node.js? I have it to where I can insert my JSON object to my DB, but all the ways I have tried to return the JSON object from the DB return null or just information about the database.
Is there some good method using mongoose to be able to query the database similar to the method:
var cursor = db.collection.find()
var JSONobject = cursor.next()
Here's what is in my code right now:
mongoose.connect('mongodb://localhost/myDB');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var cursor = mongoose.connection.db.contents.find();
console.log(cursor.next());
This throws an error at the line :
var cursor = mongoose....
claiming 'cannot call method 'find' of undefined'.
Note, that my collection 'contents' does in fact exist, and it contains one JSON document. I know this because I manually navigated to the collection using the mongo shell.
Edit: I am open to alternative methods to querying the database. I simply just want to be able to return JSON objects from my DB one at a time, while keeping track of where the client is at in the database.
One method to query mongoDB using mongoose is as follows:
Content.findOne().exec(function(err,docs){console.log(docs)});
Docs contains the JSON object. Access its attributes like any other object.
Note, this method uses asynchronous call backs. As such, you can't store the JSON object docs to a variable in order to use the JSON document information outside of the function. Therefore, you need to perform whatever actions needed with the JSON docs object information inside of the function.
For example, I was needing the query information to provide the filepath for my get api. As such, the result was as follows:
//get
app.get('/api/media/', function(req,res){
Content.findOne().exec(function(err,docs){res.sendFile(path.join(__dirname, '/api/media/', docs.filename))});
});
Note, Content is the model of my schema, and one of its parameters is filename.

Adding query Parameters to Go Json Rest

I am using the library go-json-rest. I'm trying to recognize queries parameters in the code for example localhost:8080/reminders?hello=world I want to access {hello: world} . I have the following code:
//in another function
&rest.Route{"GET", "/reminders", i.GetAllReminders},
func (i *Impl) GetAllReminders(w rest.ResponseWriter, r *rest.Request) {
reminders := []Reminder{}
i.DB.Find(&reminders)
w.WriteJson(&reminders)
}
I know that r.PathParams holds the url parameters but I cannot seem to find how to the query parameters past the "?" in the url.
Given that go-json-rest is a thin wrapper on top of net/http, have you looked at that package's documentation? Specifically, the Request object has a field Form that contains a parsed map of query string values as well as POST data, that you can access as a url.Values (map[string][]string), or retrieve one in particular from FormValue.

How to do php operations in drupal

I am absolute beginner to drupal.
I have added a contact form (using Webform module).
Now I want to save the data entered in the form. But I am lost. I have searched over internet, found db_query() is used to query database.
But I dont know where to write the php code. Please help me or if you know any link,please give me.
The tables you'll be most interested in are webform, webform_submissions, webform_submitted_data and webform_component. Have a look at those tables and it becomes very obvious how they're linked together.
You'll want to look at the Drupal 7 Database API to learn how to use the query system but here's an example to get you going:
/* Get a list of all submissions from webform for the node with ID (`nid`) of 1 */
$nid = 1;
$submissions = db_select('webform_submissions', 'ws')
->fields('ws')
->condition('nid', $nid)
->execute();
/* If you want to use db_query and a plain old SQL statement instead you'd do it like this:
$submissions = db_query('SELECT * FROM webform_submissions WHERE nid = :nid', array('nid' => $nid)); */
/* Loop through the submissions and load up the submitted data for each */
$submission_data = array();
foreach ($submissions as $submission) {
$query = db_select('webform_submitted_data', 'wsa')
->fields('wc', array('name'))
->fields('wsa', array('data'))
->condition('sid', $submission->sid);
/* Join in the component table to get the element label */
$query->join('webform_component', 'wc', 'wc.nid = wsa.nid AND wc.sid = wsa.cid');
$submission_data[] = $query->execute()->fetchAllKeyed();
}
At the end of that code you'll have an array ($submission_data), which contains a list of arrays of submission data for the provided node. Each of those arrays' items has a key of the component label, and a value of the submitted user value.
Hope that helps
It's worth noting that for most normal use cases you'll never need to look at the databases or do any kind of coding. The UI allows you to view submissions of a form (and see what was submitted). You can also configure the Webform to send you a copy of each submission (via email)... There is a lot you can do without "looking under the hood" or messing with the database in any way.
If you are really new to Drupal and Webforms, I just thought I'd point that out. There are a lot of tabs in the UI which might easily be overlooked.
Webform has Views support, so you probably don't really need to write database queries to generate the report you want.