Issue with ADAL in windows Universal Apps - windows

I'm building Universal Application,I'm using Azure Active Directory for authentication. I'm using Microsoft.IdentityModel.Clients.ActiveDirectory for SSO. for both Windows 8.1 and Window 10 store App. I've been referring to following URL for connecting to my Azure Active Directory and authenticating user
http://www.cloudidentity.com/blog/2014/08/28/use-adal-to-connect-your-universal-apps-to-azure-ad-or-adfs/
public login()
{
this.InitializeComponent();
redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.
GetCurrentApplicationCallbackUri();
authContext = new AuthenticationContext(authority);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// When the app starts, fetch the user's To Do list from the service.
GetTodoList();
}
private async void GetTodoList()
{
AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.windows.net", "e11a0451-ac9d-4c89-afd8-d2fa3322ef68", new Uri("http://li"));
if (result.Status != AuthenticationStatus.Success)
{
if (result.Error == "authentication_canceled")
{
// The user cancelled the sign-in, no need to display a message.
}
else
{
MessageDialog dialog = new MessageDialog(string.Format("If the error continues, please contact your administrator.\n\nError: {0}\n\nError Description:\n\n{1} {2}", result.Error, result.ErrorDescription, s1), "Sorry, an error occurred while signing you in.");
await dialog.ShowAsync();
}
return;
}
I replaced clientID, authority and resource url according to my project. When I run Application from Windows phone , it works perfectly. When I run the same code in Windows 10 and same logic ported in windows 8.1 , Application prompts for user id and password,after entering these credentials I'm getting following error
"We can't connect to the service you need right now. Check your network connection or try this again later"
I see in the output windows of Visual Studio 2015 while running application as below.
"The type 'Page' is defined in an assembly that is not referenced. You must add a
reference to assembly 'Windows.Foundation.UniversalApiContract,
Version=1.0.0.0, Culture=neutral, Pub
The type 'IUICommand' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Foundation.UniversalApiContract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'licKeyToken=null,
ContentType=WindowsRuntime'. "
I also tried to test same windows store on Windows 8.1, even their also it fails to authenticate User.
I have added all the capabilities like internet and intert client server

Add the following to config.xml:
<preference name="adal-use-corporate-network" value="true" />
The value is false by default.
More info here:
https://github.com/AzureAD/azure-activedirectory-library-for-cordova

this issue got resolved by adding useCorpnetnetwork = true for authenticationcontext along with changes in manifest like internet,internetclientsever,shared certificate . I missed shared certification in package

Related

Integrating Facebook Audience Network in Xamarin

I have been trying to integrate Facebook Audience Network so as to load native ads in my Xamarin Native iOS application. When I debug my application the code enters method "NativeAdDidFail" and the NSError says "No fill" and No other information is printed in the console.
This is what I have done:
Created a resource in business manager and Selected iOS as the target platform.
I left out the payment/mediation and app store URL since my app is not published.
Added an ad placement for native ads and Added one test device in the Monetization manager by adding my iphones IDFA.
Enabled testing, Checked the checkbox for "use real ads", I also clicked on the "choose ad type" but it doesnt seem to be saved?
Added one test user in business manager and Assigned access to the created property.
Downloaded native Facebook app and Enabled tracking in the background for the native facebook app.
Logged in on the native app with the email of the test user that I added.
Added "SkadNetworkIdentifier" and LSApplicationQueriesSchemes in info.plist-> v9wttpbfk9.skadnetwork & n38lu8286q.skadnetwork
Downloaded Xamarin.Facebook.Audiencenetwork.ios
This is my code:
AdSettings.SetAdvertiserTrackingEnabled(false);
AdSettings.ClearTestDevices();
AdSettings.AddTestDevice("74312C38-4958-4187-B385-9FCFE68FRRA9");
nativeAd = new NativeAd("CAROUSEL_IMG_SQUARE_LINK#611875720420055_511995483752412")
{ Delegate = this };
nativeAd.LoadAd();
[Export("nativeAdDidLoad:")]
public void NativeAdDidLoad(NativeAd nativeAd)
{
}
[Export("nativeAd:didFailWithError:")]
public void NativeAdDidFail(NativeAd nativeAd, NSError error)
{
var errorcode = error.Code;
Console.WriteLine($"{nameof(NativeAdDidFail)} - Native ad failed to load with error: {error.LocalizedDescription}");
//AppDelegate.ShowMessage("Native Ad Error", error.LocalizedDescription, NavigationController);
}
[Export("nativeAdDidClick:")]
public void NativeAdDidClick(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdDidClick)} - Native ad was clicked.");
[Export("nativeAdDidFinishHandlingClick:")]
public void NativeAdDidFinishHandlingClick(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdDidFinishHandlingClick)} - Native ad did finish click handling.");
[Export("nativeAdWillLogImpression:")]
public void NativeAdWillLogImpression(NativeAd nativeAd) =>
Console.WriteLine($"{nameof(NativeAdWillLogImpression)} - Native ad impression is being captured.");
Here's the tutorial I am trying to follow
According to the Facebook Audience Network, this could be the possible reasons:

Authentication failed with Azure Active Directory in Windows Phone

I am follow the window phone authentication tutorial with Add authentication to your Mobile Services app. And I choose using Azure Active Directory way to make authentication. But the question is: it always fails and shows The remote procedure call failed. (Exception from HRESULT: 0x800706BE) at the following code
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await Authenticate();//here throws System.Exception in mscorlib.ni.dll
await RefreshMissionTable();
}
And I make sure there is nothing wrong in my Azure setting. The weird thing is that when I choose windows phone universal app sample, and do the same procedure again, it can work in the windows 8.1 emulator! But still can't work in the windows phone 8.1 emulator .
And the break point stays here
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
}
}
this might be related to a known problem with the WebAuthenticationBroker on Windows Phone 8.1: it cannot be invoked until the full UX of the app has been loaded. Please take a look to this thread for a description of the issue and proposed workarounds: https://social.msdn.microsoft.com/Forums/vstudio/en-US/95c6569e-2fa2-43c8-af71-939e006a9b27/mobile-services-loginasync-remote-procedure-call-failed-hresult-0x800706be?forum=azuremobile
HTH
V.

Running executable program with no UI from windows service

I am running a console application with no UI and generate thumbmail images from pdf files. The compile file for this application works fine. However I have to call this compile file from windows service application that implement the the FileSystemWatcher class to detect when new pdf files are uploaded into the directory.
and I am using the suggestion from this link
How to run console application from Windows Service?
ProcessStartInfo info = new ProcessStartInfo(appName);
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
if (!process.HasExited)
{
LogEvent(process.ProcessName + "has started and called Thumbnail application");
}
else
{ LogEvent(process.ProcessName + "has been terminated"); }
I can see the process involking the "pdfThumbnail.exe" but I am getting this error when the application try to execute.
"System.Exception: Cannot create ActiveX component.
at Microsoft.VisualBasic.Interaction.CreateObject(String ProgId, String ServerName)
at PDFThumbnailCsharp.Main(String[] args)
"
As I have said above the pdfThumbnail.exe execute fine when i run the exe file.
Updates
This is the error from the SysInternals' Process Monitor
The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {FF76CB60-2E68-101B-B02E-04021C009402} and APPID
Unavailable to the user NT AUTHORITY\LOCAL SERVICE SID (S-1-5-19) from address LocalHost (Using LRPC). This security permission can be modified using the Component Services administrative tool.
I have changed the ownership of this CLSID to Administrator with Full control as described on this link
http://social.technet.microsoft.com/Forums/en-US/windowsserver2008r2general/thread/e303c7e1-16de-42fd-a1a4-7512c1261957
However I am still getting the same error.
Any help will be appreciated.
Thanks
This CLSID {FF76CB60-2E68-101B-B02E-04021C009402} is for Acrobat.Excha.PDDoc on my computer registry. Further investigation with Acrobat on this link https://forums.adobe.com/thread/1467460 revealed that Acrobat cannot be run from service.
What I have done for now until I have a better approach is to create a windows Task Scheduler that listen to an event raised by the windows service when new pdf are created and then trigger the console app that create the thumbnails.

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!!

Silverlight Business Application Windows Authentication

I cannot seem to get Windows Authentication to work in the Silverlight Business Application.
I have made the changes required see below
Changed to Windows authentication in App.xaml
public App()
{
InitializeComponent();
// Create a WebContext and add it to the ApplicationLifetimeObjects
// collection. This will then be available as WebContext.Current.
WebContext webContext = new WebContext();
//webContext.Authentication = new FormsAuthentication();
webContext.Authentication = new WindowsAuthentication();
this.ApplicationLifetimeObjects.Add(webContext);
}
Changed to Windows authentication in web.config
<authentication mode="Windows"/>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>
I put a breakpoint on the Application_UserLoaded event but nothing happens:-
private void Application_UserLoaded(LoadUserOperation operation)
{
foreach (var r in WebContext.Current.User.Roles)
{
//do something
}
}
Can anyone suggest what is going wrong. I have made no other changes to the project at all.
This happened to me previously as well. It turned out that Silverlight debugging wasn't enabled in the properties of the Web project. Right click on the .Web project and click on properties. Next click on the Web tab and on the bottom ensure the Silverlight checkbox is checked.
You must have this line in the Application_Startup:
WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);
This will automatically authenticate a user when using Windows authentication.

Resources