Xamarin SQLIteConnection: method "Get" throw exception if key doesn't exist - sqlite

When I try run this code:
var l=_sqliteconnection.Get<Preferences> (x=>x.Key=="Login");
I have got exception, because entity in table "Preferences" with key "Login" doesn't exist, but if entity exist, it's ok.
I can use try/catch blocks, but can I do it without try and catch?
Thank you.

From Get<TClass> class documentation on returns:
The object that matches the given predicate. Throws a not found exception if the object is not found
If you don't want the exception it's better to use Find<TClass> that get the object with the given primary key or null if the object is not found.

Related

How to override ValidateAudienceRestriction in SamlSecurityTokenAuthenticator

I'm using .Net 4.5, running ASP.net Service configured with an Identity provider. I would like to alter the AudienceUri validation algorithm to allow wildcards or configure it to ignore subdomains.
In this page:
http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.samlsecuritytokenauthenticator.allowedaudienceuris(v=vs.100).Aspx
it says in the remarks:
Optionally, override the ValidateAudienceRestriction method to specify
the validation algorithm to use for the allowed URI.
I understand that I need to create a new class, inherit from SamlSecurityTokenAuthenticator and override the method.
But I'm not sure how do I apply this override, I believe that I should instantiate the new class and assign it to a static member of some class, such as FederationAuthentication, but I couldn't find the appropriate class.
Can anybody please clarify how to approach this?
There is a workaround for this.
If the RP validation of the received security token fails due to audience:
[System.InvalidOperationException]: {"ID1032: At least one 'audienceUri' must be specified in the SamlSecurityTokenRequirement when the AudienceUriMode is set to 'Always' or 'BearerKeyOnly'. Either add the valid URI values to the AudienceUris property of SamlSecurityTokenRequirement, or turn off checking by specifying an AudienceUriMode of 'Never' on the SamlSecurityTokenRequirement."}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
HResult: -2146233079
InnerException: null
Message: "..."
StackTrace: ..
TargetSite: ..
}
This exception (and many others) can be handled in Application_Error, determine the exception using Server.GetLastError().
I noticed that:
FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived
Fired right before this exception is thrown. This callback has SecurityTokenReceivedEventArgs, which has the SessionToken, where you can find all the audienceUri(s).
You can implement the logics you need there and add the relevant AudienceUri to:
FederatedAuthentication.ClaimsAuthorizationModule.FederationConfiguration.
IdentityConfiguration.AudienceRestriction.AllowedAudienceUris
As I said this is just a workaround, if you got can pour more information for my original question that will be great :)
Thanks.

EditorFor(..) throws an exception when my model is null in my ASP.NET MVC application

I've got a really simple ASP.NET MVC View which has a simple string as the model.
eg.
#model string
When I do the following, the view throws an exception, if the model value is null (which occurs when the user first lands on this view/page/resource).
Value cannot be null or empty.
Parameter name: name
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Value cannot be null or empty.
Parameter name: name
<td>#Html.EditorFor(model => model)</td>
How can I create an input box using EditorFor(..) when the string-model value is null?
It appears the problem is that it cannot determine what it should use as the name of the field that you are creating. I would recommend passing in a ViewModel with a single string property in it instead of just passing a string directly. This will give you an opportunity to use data annotations to provide additional data about the field if necessary as well.

Workaround for Entity Framework Context.Refresh bug?

I ran into this problem using EF4 and a self-referential table (implementing an adjacency list hierarchy).
NOTE: not a many-to-many reference, just a one-to-many on a single table.
Attempts to resolve an intermittent InvalidOperationException ("...The ObjectContext might be in an inconsistent state...") using Context.Refresh fail due to an apparent bug in EF4.
I saw, from following Shimmy's connect.microsoft.com link, on the aforementioned post, that the bug is still outstanding.
Can anyone recommend a workaround?
What do you do if your database and Entity Framework get out of sync?
EDIT
Some more facts that may help:
When I get the InvalidOperationException and the message says "The changes to the database were committed successfully...", it is not true. They weren't.
I tried to change an object's ParentId from 1 to null (ParentId of type int?).
My object's ParentId attribute is correctly changed to the expected value (null). I call Context.SaveChanges(). Then, the exception is thrown. I check the DB, and the value has not been updated. In this case, ParentId is still 1 in the database.
Inside the catch, if I try to requery the object via myObj = Context.MyObjects.SingleOrDefault(o => o.Id == id), the object's ParentId remains the same. It does not get updated by the (incorrect) database value!
Now I think, Okay, that seems weird, but maybe if I save again the db will be corrected.
Calling a subsequent Context.SaveChanges() from inside the catch still does not update the database. (But this time, an exception is not thrown.)
If I make a new call to my SetParent method,
myObj = Context.MyObjects.SingleOrDefault(o => o.Id == id),
correcly populates the object's ParentId parameter to 1, the value from the database.
Additionally, for giggles, I set the object's ParentId to it's own Id, instead of null, to denote parentlessness. This worked fine and did not cause the InvalidOperationException. But, it's a PITA for other reasons. E.g., the object reports having itself as an extra child.
So, the questions are:
What is it about trying to set my self-referential int? ParentId to null that causes an exception?
Why does the db not get updated before the exception?
And why, inside the catch, can't I resync?!
Requery the object from the database through the context...
EDIT - in response to your update, if you submit changes for an object within a context, an an error happens, using the same context most likely is the problem. Try recreating the context in the catch to requery and reupdate, and see if that works any better.

asp.net mvc: more info on UpdateModel exception

i sometimes get an error with the UpdateModel function.
However, i can't seem to locate the exact message which field(s) is/are causing the problem.
For example this one:
"The model of type 'Enquete' was not successfully updated."
it has an innerexception of NULL, and no further description. Is there a way to find out what is causing the problem?
Michel
EDIT:
i see this in my output window:
"A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll"
Steve Sanderson has a wonderful article on using the MVC source to help you debug your application.
I think this will help you get more info.
Kindness,
Dan
Just a wild guess: You are trying to bind null to a value type. Check in your model for int, float, DateTime, structs, ... data types that you try to bind to null.
I was getting this type of exception and from my experience i got what was causing it...
We have one primary key field or identity field in the entity...
If we try to display that field in the view using html control like text box and all then at that time updateModel throws exception
otherwise it wont throw exception
Use TryUpdateModel instead. It won't throw exception, but then you can inspect ModelState for errors.
I know it is late but to help others.

Trouble creating new Entity Data Model

I'm trying to add a new ADO.Net Entity Data Model to an MVC project I am working on.
When I complete the wizard, choosing my db and tables (just a single table for now) I get an error ""Exception has been thrown by the target of an invocation." and it throws me back the add new item dialog.
At this point, an empty Data Model has been created in my project. If I then choose "Update Model From Database" and complete the wizard again, I get a similar error.
An exception of type 'System.Reflection.TargetInvocationException' occurred while attempting to update from the database. The exception message is: 'Exception has been thrown by the target of an invocation.'.
Any ideas? I have tried doing this in an empty project also and still no dice!
Alex
You could try creating the Entity Data Model manually using the EdmGen.exe tool. Hopefully that will give a bit more information about the error.
Try turning on the include exception faults behaviour
namespace DataService
{
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class mydataservice : DataService<DataContext>
{
blah blah
I had similar issue. Look for similar names and missing mapping of forgen keys
I have had the same exeption, in my case it was my db(MySql) that had a table without a primary key, I just added a column "ID" and made it the primary key and voila! the exeption was gone :)

Resources