Passing values from native project to shared project Xamarin - xamarin

Im currently facing an issue with using a 3rd party authenticator for my xamarin forms app. The code to execute has to be done natively in the platform project. The issue im facing is how to get the information(successful login, token, email etc) from the ios/android native project to the shared project for me to access it and continue the application. Below is an example of how the code looks below in the ios native project.
var client = new Auth0Client(new Auth0ClientOptions
{
Domain = "example.us.auth0.com",
ClientId = "123456789"
});
var loginResult = await client.LoginAsync();

Related

Xamarin Forms with Xamarin Player OAuth2 NInterpretException

I'm currently on developing some little application for iOS and Android. Therefore I need an OAuth2 authentication.
How I proceeded (from here)
Create a new Xamarin.Forms project from the templates with the default Item and About page
Add Dependency for Xamarin.Auth
Use the button on the about page to trigger a function with the following:
var authenticator = new OAuth2Authenticator(
"CLIENTID"
,
"SCOPE",
new
Uri("AUTH_URL"),
new Uri("REDIRECT_URL)
null,
true);
Add the iOS initializer in the AppDelegate.cs global::Xamarin.Auth.Presenters.XamarinIOS.AuthenticationConfiguration.Init();
Add the URL Types in Info.plist
I'm using the Xamarin Live Player to deploy this on my iPhone 7. When I'm triggering the button, I get the following error message:
Uncaught Exception: Bad convert with overflow instruction 'IL_0001: conv.ovf.i.un' (NInterpretExcetion)
Some ideas how to fix this?

Open Native iOS app from Xamarin.Forms

I have an native iOS sample app installed in my iPad and also my sample xamarin.Forms App installed. I want to open native iOS app from Xamarin.forms when clicked on button. I have set URL schema in my native iOS app in info.plist.
How do I open native app from xamarin.forms on click of a button. I already tried
var request = Device.OnPlatform(
string.Format("native app url"),
string.Format("native app url"),
string.Format("native app url"));
Device.OpenUri(new Uri(request));
but its not working.
It's basically how you are doing it.
var url = Device.OnPlatform(iOSUrl, androidUrl, winPhoneUrl);
Device.OpenUri(new Uri(request));
Be aware that each platform have some requirements in the way to url is configured and parameters are sent.
Let say to get the maps app open in each platform you would use these urls schemes:
// iOS doesn't like %s or spaces in their URLs, so manually replace spaces with +s
var iOSUrl = string.Format("http://maps.apple.com/maps?q={0}&sll={1}", name.Replace(' ', '+'), loc);
var androidUrl = string.Format("geo:0,0?q={0}({1})", string.IsNullOrWhiteSpace(addr) ? loc : addr, name);
var winPhoneUrl = $"bingmaps:?cp={loc}&q={name}";
var url = Device.OnPlatform(iOSUrl, androidUrl, winPhoneUrl);
Also you cannot open any arbitrary app unless you know its Url scheme.
Anyway, if the Device.OpenUri() doesn't fulfill your requirements you are good to create your own implementations using the native APIs.
Please go through the below link and attached photo
Link:-launch-an-app-from-within-another-iphone
I am using below code in xamarin forms
NSUrl request = new NSUrl("Camera://");
var canOpen = UIApplication.SharedApplication.CanOpenUrl(new NSUrl(request.ToString()));
if (!canOpen)
{ Task.FromResult(false); }
else
{
Task.FromResult(UIApplication.SharedApplication.OpenUrl(new NSUrl(request.ToString())));
}

Android Xamarin.Auth 1.2.2 How to Update Uploaded Cloud Storage File LastModifiedDate?

With Xamarin.Forms, I am using OneDrive SDK on UWP to access OneDrive and it is working good. I am uploading/downloading small data files and I use the following code to change a file's LastModifiedDate:
Item itemUpdate1 = new Item();
itemUpdate1.FileSystemInfo = new Microsoft.OneDrive.Sdk.FileSystemInfo {LastModifiedDateTime = lastModifiedDateTime };
await oneDriveClient1.Drive.Items[item1.Id].Request().UpdateAsync(itemUpdate1);
On Android, I use Xamarin.Auth to access OneDrive and I cannot figure out how to update a file's LastModifiedDate. I am using the following code to sign in and upload the file:
var auth = new OAuth2Authenticator(clientId: clientId, scope: storageScopes1, authorizeUrl: new System.Uri("https://login.live.com/oauth20_authorize.srf"),
redirectUrl: new System.Uri("https://login.live.com/oauth20_desktop.srf"));
System.Uri dataFileUri = new System.Uri("https://api.onedrive.com/v1.0/drive/special/approot:/" + dataFileName1 + ":/content");
var requestUpload = new OAuth2Request("PUT", dataFileUri, null, account);
I would like to know if OAuth2Request can be used to update the file's LastModifiedDate or if there is another way to do it?
Thanks for your help.
Short answer is no. Xamarin.Auth is only to handle the Authentication between your App and the OneDrive Rest Api.
If you want to modify any of the properties of a file in OneDrive you will need to either use a OneDrive SDK for Android as you do in the UWP project or do these modification using the Rest API directly as you did to upload the file.
UPDATE 1
System.Uri dataFileUri = new System.Uri("https://api.onedrive.com/v1.0/drive/special/approot:/" + dataFileName1 + ":/content");
var requestUpload = new OAuth2Request("PUT", dataFileUri, null, account);
As you did in the code above, if you can get the endpoint for the OneDrive REST API to modify the file's properties (like LastModifiedDate) you could be able do it with OAuth2Request.
Go to the OneDrive Dev Portal and try to get that information from the documentation.

How can i use internal database from scratch

How can i using internal database for example (sqlite) for offline app in nativescript without using any plugin.
i'm searched every were how i can installed or used sqlite or other internal database for nativescript but i didn't have any answer.
Just like you would do with any code that you need to access the native APIs
e.g. (JavaScript) Android example
var query = "select sqlite_version() AS sqlite_version";
var db = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(":memory:", null);
var cursor = db.rawQuery(query, null);
var sqliteVersion = "";
if (cursor.moveToNext()) {
sqliteVersion = cursor.getString(0);
console.log(sqliteVersion);
}
The API references for SQLite in Android here and that said you can now follow a basic Android database tutorial and implement it step by step in your NativeScript application using JavaScript or TypeScript
Still, the plugin could provide all that wrapped in a ready-to-go functionality so unless you are lacking something it will be easier to use the nativescript-sqlite and avoid writing native code for Android and then for iOS.

Google service object for Google Calendar API

I am trying to use the Google Calendar API in .NET, specifically I am trying to get a list of events. According to the examples here, in different programming languages I need to create a 'service' object and an 'event' object. However, I can't find a clear explanation of what either of these objects is or how to initiate them. Does anyone have an explanation? Or can anyone provide any information or give me a link to where this is explained? It doesn't necessarily have to be in .NET
Here is the example in Java:
String pageToken = null;
do {
events = service.events().list('primary').setPageToken(pageToken).execute();
List<Event> items = events.getItems();
for (Event event : items) {
System.out.println(event.getSummary());
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
Following the advice answered, I am getting the following error:
Could not load file or assembly 'Microsoft.Threading.Tasks.Extensions.Desktop, Version=1.0.16.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Here is the code, the error occurs on the credentials = Await... line
Dim credential As UserCredential
Dim clientSecretsPath As String = Server.MapPath("~/App_Data/client_secret.json")
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(CalendarService.Scope.Calendar)
Using stream = New System.IO.FileStream(clientSecretsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None)
End Using
The problem with GoogleWebAuthorizationBroker is that it tries to launch a new instance of a web browser to go and get authorization where you have to click the "Grant" button.
Obviously if you're running a MVC project under IIS it's just going to get confused when the code tries to execute a web browser!
My solution:
Download the .net sample projects: https://code.google.com/p/google-api-dotnet-client/source/checkout?repo=samples
Build and run one of the projects relevant to you (Eg Calendar or Drive). Dont forget to include your client_secret.json file downloaded from the cloud console.
Run the project and it will open a new browser on your computer where you will have to click the "Grant" button. Do this once and then your MVC code will work because it will not try to open a web browser to grant the permissions.
I'm not aware of any other way to grant this permission to the SDK but it worked for me just great!
Good luck. This took me a good 5 hours to figure out.
Just had the same issue running VS2013 (using .net45 for my project):
After fetching the CalendarV3 API via NuGet you just have to manually add the reference to:
...packages\Microsoft.Bcl.Async.1.0.165\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll
to the project (because it is not inserted automatically via the NuGet-Script)!
That's it! Maybe #peleyal is correcting the script somewhen in future ;)
Remember that this sample is for Java. My recommendation is to do the following:
Take a look in our VB sample for the Calendar API which is available here
You should take a look also in other sample for C#, let's say Tasks API sample
Start a new project and add a NuGet reference to Google.Apis.Calednar.v3. Remember that it's prerelease version.
Your code should look like the following:
It's based on the 2 samples above, I didn't compile or test it but it should work.
UserCredential credential;
using (var stream = new System.IO.FileStream("client_secrets.json",
System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { CalendarService.Scope.Calendar },
"user", CancellationToken.None);
}
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YOUR APP NAME HERE",
});
var firstCalendar = (await service.CalendarList.List().ExecuteAsync()).Items().FirstOrDefault();
if (firstCalendar != null)
{
// Get all events from the first calendar.
var calEvents = await service.Events.List(firstCalendar.Id).ExecuteAsync();
// DO SOMETHING
var nextPage = calEvents.NextPage;
while (nextPage != null)
{
var listRequest = service.Events.List(firstCalendar.Id);
// Set the page token for getting the next events.
listRequest.PageToken = nextPage;
calEvents = await listRequest.EsecuteAsync();
// DO SOMETHING
nextPage = calEvents.NextPage;
}
}
I had the same error, and it was due to the app trying to launch the accept screen.
I first tried to get the vb.net example from google and ran that, which I did get to work, and change to my secret info, ran and got the accept screen. I then tried my app, and it still did not work.
I noticed that the dll was found here under my project installed from the nuget packages.
...packages\Microsoft.Bcl.Async.1.0.165\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll
but was not in the net45 dir. So I uninstalled the nuget packages (have to if changing the .net version) then changed my .net version for my project to 4.0 instead of 4.5, reinstalled the nuget packages, and then it worked!!

Resources