Query Parent by Child Relation ParseSwift - swift

I am looking to query my parent ParseObject by a child relation object. I have a parent named Matches which has a field Relation(Wrestlers). I want to find all matches that a wrestler belongs to. Any assistance is greatly appreciated as I can only find documentation for outdated version of the ParseSwift library and the playground doesn't seem to help as it only uses built in relationships and not custom objects.
This query does not return any results. Wrestler is set to an instance of the ParseObject I want to filter the relation on
let query = Match.query("wrestlers" == wrestler).includeAll()

The playgrounds for Roles and Relation states:
Using this relation, you can create many-to-many relationships with other ParseObjecs, similar to users and roles.
Essentially if you follow the Roles example, you should be able to create any relation and query. Specific for your use case (at least using the small amount of code you provided in your question):
let match = Match() // Next time, please provide the code for all of your ParseObjects in question.
let matchRelation = match.relation("wrestlers", child: wrestler)
do {
let wrestlers = try await match.relation.query(wrestler).includeAll().find()
print("Found related wrestlers: \(wrestlers)")
} catch {
print(error)
}
In ParseSwift 2.4.0+ you can do the following:
let matchRelation = match.relation("wrestlers", child: wrestler)
do {
let wrestlers = try await wrestler.relation.query("wrestlers", parent: match).includeAll().find()
print("Found related wrestlers: \(wrestlers)")
} catch {
print(error)
}
You can refer to the Playgrounds in the pending PR if more clarity is needed.
I can only find documentation for outdated version of the ParseSwift library and the playground doesn't seem to help as it only uses built in relationships and not custom objects.
This can't be true as the only documentation for the ParseSwift SDK is the API documentation and the Swift Playgrounds which are both up-to-date. If you are referring to the iOS SDK's documentation that is a completely different SDK than the ParseSwift SDK. The iOS SDK is an Objective-C SDK that bridges to Swift and the SDK's are not related.

Related

Get the user's home directory from XPC

My (non-sandboxed) app has an embedded XPC helper which runs as root.
I would like to reference the (real) user's home directory from inside my helper, but these usual suspects simply return /var/root:
FileManager.default.homeDirectoryForCurrentUser
NSHomeDirectory()
I can't simply pass Users/bob to my helper for security reasons — if an exploit managed to call my helper method with any URL it wished, and my helper did things based on that as root, I fear bad things could be achieved.
As vadian commented there are fundamental conceptual issues with what you're asking. What you probably actually want to do is be sure the process communicating with your helper tool is in fact trusted.
To do that you need to use SecCodeCreateWithXPCMessage and then use the resulting SecCode instance to validate the caller. For an example of how to do that, take a look at the acceptMessage function in the SecureXPC framework.
EDIT: Turns out there is a way to do this that does work from a Command Line Tool such as one installed with SMJobBless. This answer is adapted from Apple's Technical Q&A QA1133.
If you for whatever reason want to ignore the above, there's an approach you can take which may produce unexpected results if multiple users have active consoles. From Apple's documentation for SCDynamicStoreCopyConsoleUser: "Note that this function only provides information about the primary console. It does not provide any details about console sessions that have fast user switched out or about other consoles."
import SystemConfiguration
extension FileManager {
var homeDirectoryForConsoleUser: URL? {
var homeDirectory: URL?
if let consoleUser = SCDynamicStoreCopyConsoleUser(nil, nil, nil) as String?,
consoleUser != "loginwindow" {
homeDirectory = URL(fileURLWithPath: "/Users/\(consoleUser)")
}
return homeDirectory
}
}
And then you can make use of this anywhere in your helper tool:
if let homeDirectory = FileManager.default.homeDirectoryForConsoleUser {
// Do something useful here
}

Value of type 'MSTable?' has no member 'pullWithQuery'

I tried to change client page size in Azure server
it's default is 50 and I want to make it bigger
so i use Microsoft tutorial in this link
https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-ios-how-to-use-client-library#querying
var client : MSClient?
let client = MSClient(applicationURLString: "AppUrl")
let table = client.tableWithName("TodoItem")
let query = table.query()
let pullSettings = MSPullSettings(pageSize: 3000)
but when I write
table.pullWithQuery(query, queryId:nil, settings: pullSettings) { (error) in
if let err = error {
print("ERROR ", err)
}
}
there are error "Value of type 'MSTable?' has no member 'pullWithQuery'"
what is the problem ?
is the function name changed ?
Two problems:
The documentation has not been updated for current versions of Swift
(an update request has been filed). The correct function name in modern Swift is pull rather than pullWithQuery.
The pullWithQuery function is on MSSyncTable, not MSTable. Pull is part of the offline sync system. The MSTable analog is read.
More details:
The SDK itself defines the function as MSSyncTable.pullWithQuery, but one of the features of Swift 3.0 is that it renames Objective C methods when it projects them into Swift to remove redundant arguments from the name, so verbWithX(X) becomes just verb(with:x) and pullWithQuery (MSQuery) becomes pull(with:MSQuery).
For more information on Swift 3 changes please see https://swift.org/blog/swift-3-0-released/ . I believe this particular change is SE-0005: Better Translation of Objective-C APIs Into Swift
If you download the Swift quickstart from your Azure Portal then you’ll get the correct modern pattern there:
self.table!.pull(with: self.table?.query(), queryId: "AllRecords")
or with your arguments:
self.table!.pull(with: self.table?.query(), queryId: nil, settings: pullSettings)

Get assembly metadata in NDepend

I am trying to create CQL query which will select assemblies created by my company.
In my opinion the easiest way is to check data generated in AssemblyInfo, but I cannot find how to access it in CQL.
What about the code query:
from a in Application.Assemblies
where a.Name.StartsWith("YourCompany.YourProduct")
select a
Or do you need something more sophisticated?
Ok, what about getting inspiration from this default rule:
// <Name>UI layer shouldn't use directly DB types</Name>
warnif count > 0
// UI layer is made of types in namespaces using a UI framework
let uiTypes = Application.Namespaces.UsingAny(Assemblies.WithNameIn("PresentationFramework", "System.Windows", "System.Windows.Forms", "System.Web")).ChildTypes()
// You can easily customize this line to define what are DB types.
let dbTypes = ThirdParty.Assemblies.WithNameIn("System.Data", "EntityFramework", "NHibernate").ChildTypes()
// Ideally even DataSet and associated, usage should be forbidden from UI layer:
// http://stackoverflow.com/questions/1708690/is-list-better-than-dataset-for-ui-layer-in-asp-net
.Except(ThirdParty.Types.WithNameIn("DataSet", "DataTable", "DataRow"))
from uiType in uiTypes.UsingAny(dbTypes)
let dbTypesUsed = dbTypes.Intersect(uiType.TypesUsed)
select new { uiType, dbTypesUsed }
Of course the sets uiTypes and dbTypes must be refined with assemblies from level N and assemblies from level N+1.

Phonegap and Nova Data Framework -

I am learning PhoneGap for an app project and need to use the database for certain aspects, I am trying out the Nova Data framework,
https://cordova.codeplex.com/wikipage?title=How%20to%20use%20nova.data
I am trying to use my code to put together a test entity, but I am getting a db error telling me there is a missing table. The documentation does not specify that the database should be created beforehand, but I am starting to think that may be the case. Has anyone out there used the Nova framework in a project? I just need a little guidance.
Here is my code I am using to kick off the DB Context:
var DataContext = function () {
nova.data.DbContext.call(this, "HealthDb", "1.0", "Health DB", 1000000);
this.Temperatures = new nova.data.Repository(this, Temperature, "Temperatures");
};
DataContext.prototype = new nova.data.DbContext();
DataContext.constructor = DataContext;
And my entity (Temperature) :
var Temperature = function () {
nova.data.Entity.call(this);
this.Value = 101;
};
Temperature.prototype = new nova.data.Entity();
Temperature.constructor = Temperature;
It is creating an empty database with the proper name, just no tables! I am grateful for any assistance!
Thanks for using our library. I have made the html5 sqlite as a standalone library. Please get it from github.
A live demo link is also available there. And the documentation is more complete. The lib itself has also been updated and a few bugs fixed.
Thanks,
Leo
Turns out I was trying to start up the dbcontext before I defined my entity classes....
Changed the order of my js files and it works.

Navigation Property Filter

My question is this: How can you implement a default server-side "filter" for a navigation property?
In our application we seldom actually delete anything from the database. Instead, we implement "soft deletes" where each table has a Deleted bit column. If this column is true the record has been "deleted". If it is false, it has not.
This allows us to easily "undelete" records accidentally deleted by the client.
Our current ASP.NET Web API returns only "undeleted" records by default, unless a deleted argument is sent as true from the client. The idea is that the consumer of the service doesn't have to worry about specifying that they only want undeleted items.
Implementing this same functionality in Breeze is quite simple, at least for base entities. For example, here would be the implementation of the classic Todo's example, adding a "Deleted" bit field:
// Note: Will show only undeleted items by default unless you explicitly pass deleted = true.
[HttpGet]
public IQueryable<BreezeSampleTodoItem> Todos(bool deleted = false) {
return _contextProvider.Context.Todos.Where(td => td.Deleted == deleted);
}
On the client, all we need to do is...
var query = breeze.EntityQuery.from("Todos");
...to get all undeleted Todos, or...
var query = breeze.EntityQuery.from("Todos").withParameters({deleted: true})
...to get all deleted Todos.
But let's say that a BreezeSampleTodoItem has a child collection for the tools that are needed to complete that Todo. We'll call this "Tools". Tools also implements soft deletes. When we perform a query that uses expand to get a Todo with its Tools, it will return all Tools - "deleted" or not.
But how can I filter out these records by default when Todo.Tools is expanded?
It has occurred to me to have separate Web API methods for each item that may need expanded, for example:
[HttpGet]
public IQueryable<Todo> TodoAndTools(bool deletedTodos = false, bool deletedTools = false)
{
return // ...Code to get filtered Todos with filtered Tools
}
I found some example code of how to do this in another SO post, but it requires hand-coding each property of Todo. The code from the above-mentioned post also returns a List, not an IQueryable. Furthermore this requires methods to be added for every possible expansion which isn't cool.
Essentially what I'm looking for is some way to define a piece of code that gets called whenever Todos is queried, and another for whenever Tools is queried - preferably being able to pass an argument that defines if it should return Deleted items. This could be anywhere on the server-side stack - be it in the Web API method, itself, or maybe part of Entity Framework (note that filtering Include extensions is not supported in EF.)
Breeze cannot do exactly what you are asking for right now, although we have discussed the idea of allowing the filtering of "expands", but we really need more feedback as to whether the community would find this useful. Please add this to the breeze User Voice and vote for it. We take these suggestions very seriously.
Moreover, as you point out, EF does not support this.
But... what you can do is use a projection instead of an expand to do something very similar:
public IQueryable<Object> TodoAndTools(bool deleted = false
,bool deletedTools = false) {
var baseQuery = _contextProvider.Context.Todos.Where(td => td.Deleted == deleted);
return baseQuery.Select(t => new {
Todo: t,
Tools: t.Tools.Where( tool => tool.Deleted = deletedTools);
});
}
Several things to note here:
1) We are returning an IQueryable of Object instead of IQueryable of ToDo
2) Breeze will inspect the returned payload and automatically create breeze entities for any 'entityTypes' returned (even within a projection). So the result of this query will be an array of javascript objects each with two properties; 'ToDo' and 'Tools' where Tools is an array of 'Tool' entities. The nice thing is that both ToDo and Tool entities returned within the projection will be 'full' breeze entities.
3) You can still pass client side filters based on the projected property names. i.e.
var query = EntityQuery.from("TodoAndTools")
.where("Todo.Description", "startsWith", "A")
.using(em);
4) EF does support this.