Warning: Expression following 'return' is treated as an argument of the 'return' - swift

I get this warning in my code and I can't figure out what it means and what I need to do to fix it.
The warning says the following:
Expression following 'return' is treated as an argument of the 'return'
And it's shown on this line:
// Tell Realm to use this new configuration object for the default Realm
Can someone explain what I'm doing wrong? See code part below.
Some background info, the code is part of a database manager class which I use to migrate a unencrypted realm database to an encrypted one, if the encrypted db doesn't exist yet.
If the encrypted db already exists, it configures realm to use this one as default. If it cannot open it (e.g. because of wrong encryption key) it creates a new database.
let exists = self.encryptedDatabaseExists(config)
if exists {
//Try to open Realm with new config. If unsuccessful, it needs to be removed and a new one created
do {
_ = try RLMRealm(configuration: config)
// Tell Realm to use this new configuration object for the default Realm
RLMRealmConfiguration.setDefaultConfiguration(config)
RLMRealm.defaultRealm()
} catch let err {
Log.error("Encrypted DB could not be opened: \(err)")
self.createNewEncryptedDatabase(config)
}
} else {
self.migrateToEncryptedDatabase(config)
}

Swift 5
Easy way enjoy it
//MARK:- Use it like function its will work
return()

NB: Adding this here since I've encountered the issue before.
According to the swift docs, if an expression follows immediately after the return statement, it will be returned/run as well.
In this case there's a return statement followed by other code expressions that gets treated as an argument.
To prevent this just add a ; after the return and code execution will stop.
return;

Related

How to force JSonSerialiser to handle reference loops?

I'm trying to configure the SignalR JSon serializer to handle reference loops in my objects graph.
I have seen similar questions on SO, and borrowed the code below from there.
Following is the relevant part of the ConfigureServices method:
services.AddSignalR().AddJsonProtocol(options =>
{
options.PayloadSerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
});
Unfortunately, even with this configuration, trying to send data on the wire throws the following exception:
Self referencing loop detected for property 'Vehicule' with type 'A.B.C.Vehicle'. Path ...
Obviously this code is not enough, but I can't figure out what to do.
Any help appreciated.
Add ShouldSerializePROPERTYNAME entry to your model source file:
public bool ShouldSerializeVehicule()
{
return false;
}
or apply the attribute [JsonIgnore] to Vehicule.
This tells Json to skip it.

How to add a field to the schema of a Realm database?

I am seeking to add another property to my Realm database scheme (pointed to by the arrow) while at the same time learn how to use the migration functionality.
class FeesPaid: Object {
dynamic var fileNumber = ""
dynamic var forMonth = ""
dynamic var amount: Float = 0.0
dynamic var balance: Float = 0.0 <-------
dynamic var date = ""
}
I have been following the instructions at Realm.io and I have copied the code in the first block and placed it into the my "application(application:didFinishLaunchingWithOptions:)" function which is located in the "AppDelegate.swift" file.
let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 1,
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
}
)
// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config
// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let clients = try! Realm()
The statement just below this block on the Realm web site states:
"At the very minimum all we need to do is to update the version with an empty block to indicate that the schema has been upgraded (automatically) by Realm."
(This statement of nothing else needing to be done seems to be supported by the comments within the if statement, above.)
Yet when I run my app I keep getting the error:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Migration is required for object type 'FeesPaid' due to the following errors:
- Property 'balance' has been added to latest object model." UserInfo={NSLocalizedDescription=Migration is required for object type 'FeesPaid' due to the following errors:
- Property 'balance' has been added to latest object model.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/ErrorType.swift, line 50
So what am I doing wrong?
I don't need to enumerate or pre-fill in any values in the new field. I simply need the new field in my scheme.
I compared your code against the examples in the docs and the sample code and it looks fine. By all accounts that should be working.
The only thing I can think of is that that Realm object may be getting called elsewhere in your app before it's been configured in your app delegate. This is possible if your app employs storyboards and you have any Realm code in a view controller viewDidLoad method as this gets loaded before your app delegate is triggered. If that's the case, it's usually quite easy to solve as all you need to do is manually set up and present your storyboard at the end of application(application:didFinishLaunchingWithOptions:)
Failing that, what esthepiking said is correct. You can increment the schema version during testing, or if you know your schema changes are going to be very volatile during development, you can also simply delete it each time on app launch.

Add single record to mongo collection with meteor

I am a new user to JavaScript and the meteor framework trying to understand the basic concepts. First of all I want to add a single document to a collection without duplicate entries.
this.addRole = function(roleName){
console.log(MongoRoles.find({name: roleName}).count());
if(!MongoRoles.find({name: roleName}).count())
MongoRoles.insert({name: roleName});
}
This code is called on the server as well as on the client. The log message on the client tells me there are no entries in the collection. Even if I refresh the page several times.
On the server duplicate entries get entered into the collection. I don't know why. Probably I did not understand the key concept. Could someone point it out to me, please?
Edit-1:
No, autopublish and insecure are not installed anymore. But I already published the MongoRoles collection (server side) and subscribed to it (client side). Furthermore I created a allow rule for inserts (client side).
Edit-2:
Thanks a lot for showing me the meteor method way but I want to get the point doing it without server side only methods involved. Let us say for academic purposes. ;-)
Just wrote a small example:
Client:
Posts = new Mongo.Collection("posts");
Posts.insert({title: "title-1"});
console.log(Posts.find().count());
Server:
Posts = new Mongo.Collection("posts");
Meteor.publish(null, function () {
return Posts.find()
})
Posts.allow({
insert: function(){return true}
})
If I check the server database via 'meteor mongo' it tells me every insert of my client code is saved there.
The log on the client tells me '1 count' every time I refresh the page. But I expected both the same. What am I doing wrong?
Edit-3:
I am back on my original role example (sorry for that). Just thought I got the point but I am still clueless. If I check the variable 'roleCount', 0 is responded all the time. How can I load the correct value into my variable? What is the best way to check if a document exists before the insertion into a collection? Guess the .find() is asynchronous as well? If so, how can I do it synchronous? If I got it right I have to wait for the value (synchronous) because I really relay on it.
Shared environment (client and server):
Roles = new Mongo.Collection("jaqua_roles");
Roles.allow({
insert: function(){return true}
})
var Role = function(){
this.addRole = function(roleName){
var roleCount = Roles.find({name: roleName}).count();
console.log(roleCount);
if(roleCount === 0){
Roles.insert({name: roleName}, function(error, result){
try{
console.log("Success: " + result);
var roleCount = Roles.find({name: roleName}).count();
console.log(roleCount);
} catch(error){
}
});
}
};
this.deleteRole = function(){
};
}
role = new Role();
role.addRole('test-role');
Server only:
Meteor.publish(null, function () {
return Roles.find()
})
Meteor's insert/update/remove methods (client-side) are not a great idea to use. Too many potential security pitfalls, and it takes a lot of thought and time to really patch up any holes. Further reading here.
I'm also wondering where you're calling addRole from. Assuming it's being triggered from client-side only, I would do this:
Client-side Code:
this.addRole = function(roleName){
var roleCount = MongoRoles.find({name: roleName}).count();
console.log(roleCount);
if (roleCount === 0) {
Meteor.call('insertRole', roleName, function (error, result) {
if (error) {
// check error.error and error.reason (if I'm remembering right)
} else {
// Success!
}
});
}
}
How I've modified this code and why:
I made a roleCount variable so that you can avoid calling MongoRoles.find() twice like that, which is inefficient and consumes unneeded resources (CPU, disk I/O, etc). Store it once, then reference the variable instead, much better.
When checking numbers, try to avoid doing things like if (!count). Using if (count === 0) is clearer, and shows that you're referencing a number. Statements like if (!xyz) would make one think this is a boolean (true/false) value.
Always use === in JavaScript, unless you want to intentionally do a loose equality operation. Read more on this.
Always use open/closed curly braces for if and other blocks, even if it contains just a single line of code. This is just good practice so that if you decide to add another line later, you don't have to then wrap it in braces. Just a good practice thing.
Changed your database insert into a Meteor method (see below).
Side note: I've used JavaScript (ES5), but since you're new to JavaScript, I think you should jump right into ES6. ES is short for ECMAScript (which is what JS is based on). ES6 (or ECMAScript 2015) is the most recent stable version which includes all kinds of new awesomeness that JavaScript didn't previously have.
Server-side Code:
Meteor.method('insertRole', function (roleName) {
check(roleName, String);
try {
// Any security checks, such as logged-in user, validating roleName, etc
MongoRoles.insert({name: roleName});
} catch (error) {
// error handling. just throw an error from here and handle it on client
if (badThing) {
throw new Meteor.Error('bad-thing', 'A bad thing happened.');
}
}
});
Hope this helps. This is all off the top of my head with no testing at all. But it should give you a better idea of an improved structure when it comes to database operations.
Addressing your edits
Your code looks good, except a couple issues:
You're defining Posts twice, don't do that. Make a file, for example, /lib/collections/posts.js and put the declaration and instantiation of Mongo.Collection in there. Then it will be executed on both client and server.
Your console.log would probably return an error, or zero, because Posts.insert is asynchronous on the client side. Try the below instead:
.
Posts.insert({title: "title-1"}, function (error, result) {
console.log(Posts.find().count());
});

How to make EF log sql queries globally?

How do I "tell" EF to log queries globally? I was reading this blog post: EF logging which tells in general how to log sql queries. But I still have a few questions regarding this logger.
Where would I need to place this line context.Database.Log = s =>
logger.Log("EFApp", s);?
Can it be globally set? Or do I have to place it everywhere I do DB
operations?
In the "Failed execution" section, the blogger wrote that, and I
quote:
For commands that fail by throwing an exception, the output contains the message from the exception.
Will this be logged too if I don't use the context.Database.Log?
Whenever you want the context to start logging.
It appears to be done on the context object so it should be done every time you create a new context. You could add this line of code in your constructor though to ensure that it is always enabled.
It will not log if you do not enable the logging.
I don't recommend to use that's functionality, because, it hasn't reason to exists in the real case.
Thats it use a lot of to debug code only. But, wether you wanna know more than details ... access link... https://cmatskas.com/logging-and-tracing-with-entity-framework-6/
In this case you can put code like this
public void Mylog()
{
//Thats a delegate where you can set this property to log using
//delegate type Action, see the code below
context.Database.Log = k=>Console.Write("Any query SQL")
//Or
context.Database.Log = k=>Test("Any query SQL")
}
public void Test(string x){
Console.Write(x)
}
I hope thats useufull

How do I resolve "No views were found in assemblies or could be generated for Table"?

I am working with a database first model in Entity Framework 5 and when I attempt to add a row, I get the following error:
"No views were found in assemblies or could be generated for Table 'ui_renewals'."
The table exists in my EDMX and the template generated a ui_renewals class. I've deleted the table from the EDMX and added it again using the Update Model from Database option and I get the same error. Creating a separate connection for it resolves the issue, but that seems like a less-than-ideal solution (more like a kludge) not to mention it makes it more difficult to maintain in the future.
Any ideas on how to fix this so that I can add or update (I've tried both) a row in ui_renewals?
Here is the code I'm currently using - only difference before was using db as a DBContext instead of ui (yes, receipt is misspelled - gotta love legacy stuff)
[HttpPost]
public bool UpdateTeacher(string login_id, string password, UIRenewal data)
{
if (ModelState.IsValid)
{
// map from UIRenewal VM to ui_renewal
ui_renewals Renewal = Mapper.Map<UIRenewal, ui_renewals>(data);
// check to see if this is a new entry or not
var tmp = ui.ui_renewals.Find(Renewal.reciept);
if (tmp == null)
ui.ui_renewals.Add(Renewal);
else
{
// mark as modified
db.Entry(Renewal).State = EntityState.Modified;
}
// save it
try
{
ui.SaveChanges();
}
catch (DBConcurrencyException)
{
return false;
}
return true;
}
return false;
}
I should mention that I do have a view in the model (v_recent_license).
I know this is a very old question, however as I haven't found any other topics like this, I'll post my answer.
I have had the same Exception thrown. I found that, in a failed attempt to optimize EF performance, following the advices found here, I left behind this piece of code in EF .edmx code-behind:
<EntityContainerMapping StorageEntityContainer="XXXModelStoreContainer" CdmEntityContainer="YYYEntities" GenerateUpdateViews="false">
I removed the GenerateUpdateViews="false" string, and all is working again.
(The Exception message is a little misleading in my opinion).