Accessing the Database Row of the Current User - mysql

I manually added fields to my "_User" table on Parse. Specifically, a Twitter Handle that is a string and has the key "TwitterHandle." For some reason, when I execute the following statement (and the Twitter Handle is non-null), I receive null:
NSLog(#"%#", [[PFUser currentUser] objectForKey:#"TwitterHandle"]);
Instead, I have to execute the following code, querying the backend to find the current user's fields, and their twitter handle specifically, which seems redundant and overly complicated:
PFUser *currentUser = [PFUser currentUser];
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query whereKey:#"username" equalTo:currentUser.username];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
// do some stuff here with the current user's row in the User table, the only object in
// the NSArray of *objects
NSLog(#"%#", [[PFUser currentUser] objectForKey:#"TwitterHandle"]); --> (non-null)
}];
Is it because of the way I set up the field, manually? Otherwise, I'm not sure why my code is exhibiting this behavior.

The currentUser object is populated at login and cached, if the data is changing you will need to fetch the latest copy:
[[PFUser currentUser] fetchInBackground];

As mentionned by Timothy [[PFUser currentUser] fetchInBackground]; will get new column at the expense of a request to Parse.
However, while developping, Logout from the app and log back in. This will clear the cache and retrieve all USER info.

Related

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.

Strange results returning from Response.getId() in GAS

I am working with a script to pull the response ID from a form submission so that when users edit their response, I can match the edit to the initial response. My script creates a .pdf of the contents of each form submitted, but when users edit responses, it creates a new form containing only the edited data, without linking it to the initial response.
The edit response contains a timestamp and the edited information, and the timestamp is used with Response.getId(timestamp), iirc, and returns the ID of the form submission. However, I am sometimes getting a very strange return, and I don't know where it comes from. The response is much shorter than a typical response ID (10-12 alphanumeric instead of 30+). I will try to comeback and edit this question with the code, but I'm on a different log in at the moment, so I'll have to swap over and copy code and come back. Running unit tests hasn't really helped, as I get the expected result most of the time. It's just an occasional hiccup, but I have to find where the incorrect information is coming from.
function getResponseId(timestamp){
var form = FormApp.openById('<formID>');
if(typeof(timestamp) != 'number'){
timestamp = new Date(timestamp);
}
var responses = form.getResponses(timestamp);
var entryId = responses[0].getId();
return entryId;
}
That's is. I suppose the if(typeof... may be throwing things off if it's passing in a Date string instead of the actual timestamp of entry, but I don't think so. I'll double check it and debug it in the meantime, and if I answer my own question, I'll come back and fix it.
Hmm. Sounds like the same behavior. What I decided to do instead was to match the timestamps that are recorded, but you have to grab the stamps in the 3rd line of code, as the old stamp is overwritten quickly. I just subtracted oldTime from newTime, left a 5 sec window to match them, and that worked. I just haven't had a chance to post it yet, as I just got it working for new submissions, edits, and failed writes about an hour ago.

EWS SearchFolder does not return values from body

I am trying to create a SearchFolder using the EWS API (managed or web service directly). I noticed that I if I create a SearchFilter.ContainsSubstring on the ItemSchema.Body, I do not get any conversations from it.
here is how I create my folder:
var folder = new SearchFolder(service)
{
DisplayName = topic
};
var searchParameters = folder.SearchParameters;
searchParameters.SearchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Body, topic, ContainmentMode.Substring, ComparisonMode.IgnoreCaseAndNonSpacingCharacters);
searchParameters.RootFolderIds.Add(WellKnownFolderName.Root);
searchParameters.Traversal = SearchFolderTraversal.Deep;
folder.Save(WellKnownFolderName.SearchFolders);
Later, I try to get the conversations from this folder:
service.FindConversation(conversationView, folder.Id);
And this returns 0 conversations.
I made sure by sending two messages to my email account, the first with a special term only in the subject, and the second with the same term in the body. If I create a SearchFolder with a filter on the ItemSchema.Subject, I get the first conversation, but using the SearchFolder I created above, I do not get the expected result.
Are there some restrictions regarding the ContainsSubstring SearchFilter? I tried using NormalizedBody or TextBody, but then I got errors in the folder creation process. Is there anything else I am missing?
Doing a search filter on the body will likely be problematic. This goes back to how potentially large properties like Body are handled in contents tables. A query string search would likely work better, but you can't use a query string to create a search folder.

Send an integer into a server with GET method

I've been researching this problem for a while now and have been trying to use the POST method until recently when I figured out that the GET method will be sufficient for what I need to do.
My objective:
Take an integer from my app and send it into a php server to save it
For now, I just need to send one integer to get it working and to have a starting point to work from. Once I start getting the ball rolling and things start working, I will be sending maybe 20 integers maximum at a time, so I don't believe that I will have a problem with the data amount restrictions on the GET method.
I am working with a friend on this project right now because I am not as fluent in php, I have been exposed to it several times though, so I should know most of the terminology involved. ANYWAY, here is my php code that my friend wrote for me...
<?php
// A sample php file to demo passing parameters and getting POST data.
// This simply appends the specified value to the end of the 'sample' table.
// Call it like this: sample.php?val=4
// where 4 is the value you want to append to the table
// The code returns whether or not the sql query was performed with success or not.
// If successful, a boolean true (or 1) is returned.
// If not, then an error message is returned with the sql error.
include 'dbConnect.php';
$val = $_GET["val"]; // value to set to
$sql=
"INSERT INTO sample (`test`)
VALUES ('" . $val . "')
";
$result = mysql_query($sql,$con);
if(!$result){
die('Error: ' . mysql_error());
}
echo $val+1;
mysql_close($con);
?>
This code takes the sent value for the variable "val" and echoes that value plus one (so that the setting and the getting values are different from the site so I can more easily tell if my code works) This should work right?
Next, I believe I haven't quite finished the Xcode portion of the project yet, but I have a successful connection happening, I just haven't been able to change the value of the variable in the php server. In my project, I have an NSInteger variable called "num" and its value, set by the text field in my app, is the one I want to send in to the server. I also am using a button (called "postPressed") to initiate the function of the sending process. So here is my code...
NSURLRequest *request;
NSURLConnection *connection;
NSURL *url;
NSInteger num;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (IBAction)valueChange:(id)sender {
num = [_valueTF.text intValue];
}
- (IBAction)postPressed:(id)sender {
url = [NSURL URLWithString: [NSString stringWithFormat: #"http://jrl.teamdriven.us/source/scripts/2013/sample.php?val=%d", num]];
request = [NSURLRequest requestWithURL:url];
if (request) {
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_returnLbl.text = #"success!";
}
}
My returnLbl does change to be "success", so I know the connection works, I just think I'm missing some code on the setting the variable part. Please help me out, this has been a thorn in my side for about a month now. Also, I apologize for the length of this question, I'm just trying to get in all the details so that there doesn't have to be any clarifications.
So, it turns out that my code worked the whole time, it's just that when I looked up the data table generated by phpMyAdmin, I did not happen to notice that there was a page two of data because I had tested it so much in my browser. The integers were sent and saved successfully with the code above. I apologize for posting something like this and finding out how dumb of a mistake it truly was, but if anyone would like to give me any kinds of improvements, I am open to them. Thank you for taking your time to view this question.

Do views immediately reflect data changes in their underlying tables?

I have a view ObjectDisplay that is composed of two relevant tables: Object and State. State represents the state of an Object, and the view pulls some of the details from the most recent State for each Object.
On the page that is displaying this information, a user can enter some comments, which creates a new State. After creating the new State, I immediately pull the Object from ObjectDisplay and send it back to be dropped into a partial view and replace the Object in the grid on the page.
// Add new State.
db.States.Add(new State()
{
ObjectId = objectId,
Comments = comments,
UserName = username
});
// Save the changes (executes all of the above).
db.SaveChanges();
// Return the new Object information.
return db.Objects.Single(c => c.ObjectId == objectId);
According to my db trace, the Single call occurs about 70 ms after the SaveChanges call, and it occurs on the same SPID.
Now for the issue: The database defaults the value of RecordDate in State to GETUTCDATE() - I don't provide the date myself. What I'm seeing is that the Object returned has the State's RecordDate of the old State and the Comments of the new State information of the old State. I am seeing that the Object returned has the old State's information. When I refresh the page, all the correct information is there, but the wrong information is returned in the initial call from the database/EF.
So.. what could be wrong? Could the view not be updating quickly enough? Could something be going on with EF? I don't really know where to start looking.
If you've previously loaded the same Object entity in the same DbContext, EF will return the cached instance with the stale values, and ignore the values returned from SQL.
The simplest solution is to reload the entity before returning it:
var result = db.Objects.Single(c => c.ObjectId == objectId);
db.Entry(result).Reload();
return result;
This is indeed odd. In SQL Server views are not persisted by default and therefore show changes in the underlying data right away. You can create a clustered index on a view with effectively persists the query, but in that case the data is updated synchronously, so you should see the change right away.
If you are working with snapshot isolation level your changes might not be visible to other SPIDs right away, but as you are on the same SPID and do not use snapshot isolation, this cant be the culprit either.
The only thing left at this point is the application layer. Are you actually using the result of the Single call higher up in the call stack or does that get lost somewhere. I assume that a refresh of the page uses a different code path, which would explain why it is working there.