C# Access denied after Contacts.CNContactStore().RequestAccess - cncontactstore

I use VS for Mac version 17.4.2
I would like to read all my own MacOs contacts.
I create a new Cocoa application (Mac -> App -> Xamarin).
I add the necessary parameter in info.plist :
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
I begin by requesting access, and that generates an error (see below).
In System preferences / Security/ Confidentiality, no app has asked access to Contacts.
How can I fix this issue? Thank you.
using AppKit;
using Contacts;
using Foundation;
using System;
namespace Upd2
{
public partial class ViewController : NSViewController
{
private CNContactStore store;
private CNAuthorizationStatus auth;
public ViewController(IntPtr handle) : base(handle)
{
store = new Contacts.CNContactStore();
auth = CNContactStore.GetAuthorizationStatus(CNEntityType.Contacts);
Console.WriteLine(string.Format("\nAuthorizationStatus : {0}", auth.ToString()));
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Do any additional setup after loading the view.
if (auth == CNAuthorizationStatus.NotDetermined)
{
store.RequestAccess(CNEntityType.Contacts, Handle_Contacts_RequestAccess);
}
}
private void Handle_Contacts_RequestAccess(bool granted, NSError error)
{
Console.WriteLine(string.Format("granted : {0}", granted.ToString()));
if (!granted)
{
Console.WriteLine(string.Format("Error : {0}", error.ToString()));
}
}
}
}
AuthorizationStatus : NotDetermined
granted : False
Error : Access Denied

Related

AdMob Banner wont show up, no error message with test ad and failed to load : 3 with real ad

I have a Xamarin Forms application on which I would like to advertise via Admob. If I set my real ad-id, I get Ad failed to load : 3. When I use the id of a test-ad, there is no error message in the console, but there is also no ad.
Ive tried connecting with firebase, which worked well, but didn't fix the problem. Ive also changed the language of the app and specified in the google play console settings that my App uses ads (even through it isnt live yet).
I used a custom renderer:
Class in forms:
namespace test7
{
public class AdMobView : View
{
}
}
android implementation:
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
namespace test7.Droid
{
public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
{
public AdMobViewRenderer(Context context) : base(context) { }
string id = "ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyy"; //here was my real id and test id
private AdView CreateAdView()
{
var adView = new AdView(Context)
{
AdSize = AdSize.SmartBanner,
AdUnitId = id,
LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent)
};
adView.LoadAd(new AdRequest.Builder().Build());
return adView;
}
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
{
SetNativeControl(CreateAdView());
}
}
}
}
xaml:
<local:AdMobView x:Name="werbung" />
Any ideas how to fix this? Im lost :(
I suggest using this NuGet package. It sets everything up for you

Google OAuth Api not redirecting on Login

I try to authenticate my user using Google authentication services
When i run this code on local server its working fine (It redirects to google login and after successful login its hit call back on redirectPath).
But when publish this code on Production server then its not working.
When I debug this code, I found its redirect and open the google login page on hosted environment(Where application is published).
here is my code - Please help
string redirecrPath = "http://localhost:1212/Admin/YouTubeIntegration/Success";
UserCredential credential;
using (var stream = new FileStream(Server.MapPath("/XmlFile/client_secrets.json"), FileMode.Open, FileAccess.Read))
{
GoogleAuth.RedirectUri = redirecrPath;
credential = await GoogleAuth.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeReadonly, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
Please let me know if you need more information.
Thanks in Advance
The code to login from a web page is not the same as the code to login with an installed application. Installed applications can spawn the login screen directly on the current machine. If you tried to do that on a webserver it wouldnt work the following is the code for using web login
using System;
using System.Web.Mvc;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;
namespace Google.Apis.Sample.MVC4
{
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "PUT_CLIENT_ID_HERE",
ClientSecret = "PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { DriveService.Scope.Drive },
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override string GetUserId(Controller controller)
{
// In this sample we use the session to store the user identifiers.
// That's not the best practice, because you should have a logic to identify
// a user. You might want to use "OpenID Connect".
// You can read more about the protocol in the following link:
// https://developers.google.com/accounts/docs/OAuth2Login.
var user = controller.Session["user"];
if (user == null)
{
user = Guid.NewGuid();
controller.Session["user"] = user;
}
return user.ToString();
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
}
copied from here

Unable to load DLL 'e_sqlite3': The specified module could not be found

I have a Xamarin Forms solution. I added sqlite-net-pcl as reference to all projects. It works fine on Android but crashes on Windows 8.1 and Windows Phone 8.1. I have an IOS project but I don't have OSX at the moment to try it.
I use this in the Windows projects to access the database:
using System.IO;
using SQLite;
using Xamarin.Forms;
using HelloXamarin.Windows;
using Windows.Storage;
[assembly: Dependency(typeof(SQLiteDb))]
namespace HelloXamarin.Windows
{
public class SQLiteDb : ISQLiteDb
{
public SQLiteAsyncConnection GetConnection(string databaseName)
{
var documentsPath = ApplicationData.Current.LocalFolder.Path;
var path = Path.Combine(documentsPath, databaseName);
return new SQLiteAsyncConnection(path);
}
}
}
Here are my references:
I get this exception when trying to access the database:
The type initializer for 'SQLite.SQLiteConnection' threw an exception.
Unable to load DLL 'e_sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath)
at SQLitePCL.SQLite3Provider_e_sqlite3..ctor()
at SQLitePCL.Batteries_V2.Init() at SQLite.SQLiteConnection..cctor()
I have no idea how to solve this, please help me!
The whole solution is available on GitHub:
https://github.com/apspot/HelloXamarin
For me, it worked by adding the e_sqlite3 bundle to the executable project
By this time the issue is still open. So before they come with some solid fix, you can use this work around, to solve the issue for now.
Add one helper class
using System;
using System.Diagnostics;
using System.IO;
namespace SQLitePCL
{
public class NativeLibraryHack
{
public static bool Hacked { get; private set; }
public static bool DoHack()
{
if (Hacked) return true;
try
{
const string runtimeFolderName = "/runtimes";
var destinationPath = typeof(SQLitePCL.raw).Assembly.Location
.Replace("\\", "/");
var destinationLength = destinationPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var destinationDirectory = destinationPath.Substring(0, destinationLength) + runtimeFolderName;
var sourcePath = new Uri(typeof(SQLitePCL.raw).Assembly.CodeBase)
.AbsolutePath;
var sourceLength = sourcePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
var sourceDirectory = sourcePath.Substring(0, sourceLength) + runtimeFolderName;
if (Directory.Exists(sourceDirectory))
CopyFilesRecursively(new DirectoryInfo(sourceDirectory), new DirectoryInfo(destinationDirectory));
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
return false;
}
return (Hacked = true);
}
private static void CopyFilesRecursively(
DirectoryInfo source,
DirectoryInfo target
)
{
foreach (var dir in source.GetDirectories())
CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
foreach (var file in source.GetFiles())
{
try
{
var destinationFile = Path.Combine(target.FullName, file.Name);
if (!File.Exists(destinationFile))
file.CopyTo(destinationFile);
}
catch (Exception ex)
{
//Ignore Exception
Debug.WriteLine(ex.Message);
}
}
}
}
}
And add the hack before your db migration script, I am using web api 2
so i did on RouteConfig.RegisterRoutes
NativeLibraryHack.DoHack();
using (KSDBContext db = new KSDBContext())
{
db.Database.Migrate();
}
You need to add the SQLite Extensions.
Go to Tools > Extensions and Updates
Go to Online, then search for SQLite.
Download SQLite for Windows Runtime
In your Windows Project, Add Reference and ensure you add the extension.
Also remove Microsoft.VCLibs from your references.
Try referencing Visual C++ 2015 Runtime for Universal Windows Platform Apps. That sorted it out for me.
Go to References
Add Reference
Extensions.
Check"Visual C++ 2015 Runtime for Universal Windows Platform Apps"
OK

Cannot get any facebook permissions with C# facebook SDK

I have a fairly simple site which allow users to connect via facebook.
I am using C# facebook sdk MVC.
At first i didn't need any specific permission so there were no problems for users to connect. my code looked like this
public class FacebookController : BaseController
{
public FacebookSession FacebookSession
{
get { return (new CanvasAuthorizer().Session); }
}
public ActionResult Profile()
{
var client = new FacebookClient(this.FacebookSession.AccessToken);
dynamic me = client.Get("me");
ViewBag.Name = me.name;
ViewBag.Id = me.id;
return View();
}
}
and on my webconfig
<facebookSettings appId="XXXXXXXXXXXXXX" appSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>
After a while I needed more specific permissions so I added CanvasAuthorize to my action - as so
[CanvasAuthorize(Permissions = "user_about_me,user_relationships,email,publish_stream")]
public ActionResult Profile()
That got me this exception:
Exception Details: System.Exception: CanvasUrl is null or empty
So I added to my Webconfig the canvasUrl which got me the same error with out the canvasPage So now my web config has all 4
<facebookSettings appId="XXXXXXXXXX" appSecret="XXXXXXXXXXXXXXXXXXXXx" canvasUrl = "http://localhost:60606/" canvasPage = "https://apps.facebook.com/XXXXXXXXXXXX/"/>
So now my user can log in via facebook, my problem is that when he does log in he is getting redirect to my Facebook app (http://apps.facebook.com/XXXXXXXXX/facebook/profile)
instead back to my site(http://localhost:60606/facebook/profile)
How can I get the Permissions that i need and redirect my user back to my site after he logs in?
Thanks
Well, My bad
CanvasAuthorize is just as it sounds, authorization for canvas.
So you cannot use it without an app canvas on facebook.
What I should have done is use the FacebookOAuthClient
var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
oAuthClient.RedirectUri = new Uri("XXXXXXXXXXXXXX");
var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", null }, { "scope", "user_about_me,user_relationships,email" } });
return Redirect(loginUri.AbsoluteUri);

New AppDomain from MMC Snap-In does not get elevated privileges for UAC

I've created an MMC snap in that launches code in a new appdomain and part of the code checks for a registry key. If I check for the key in the snap in process it works, but the code in the new appdomain throws a security exception. If I load the code in a new appdomain from a console or windows app, it works fine.
Here is the code:
public class SimpleMMCSnapIn : SnapIn
{
public SimpleMMCSnapIn()
{
RegistryKey archerKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft", true); //this call works
Evidence baseEv = AppDomain.CurrentDomain.Evidence;
Evidence newEv = new Evidence(baseEv);
AppDomainSetup setup = new AppDomainSetup { ApplicationBase = "<pathtobin>" };
AppDomain domain = AppDomain.CreateDomain("MigratorDomain", newEv, setup);
domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
IWork migrator = (IWork)domain.CreateInstanceAndUnwrap("CheckRegistry", "CheckRegistry.CheckRegistry");
migrator.Work();
}
}
[Serializable]
public class CheckRegistry : MarshalByRefObject, IWork
{
public void Work()
{
RegistryKey archerKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft", true); //this call throws a security exception
}
}
Please note, if I load the code in a new appdomain from a console or windows app, it works fine. I think this is more of an MMC snap-in question than a UAC question.
Any insight would be much appreciated...
Thanks,
Brad
What do you see if you change your Work() method to do this?
WindowsPrincipal user = (WindowsPrincipal)Thread.CurrentPrincipal;
if ( user.IsInRole(WindowsBuiltInRole.Administrator) )
{
MessageBox.Show(string.Format("{0} is an Administrator", user.Identity.Name));
}
else
{
MessageBox.Show(string.Format("{0} is NOT an Administrator", user.Identity.Name));
}

Resources