authentication with Xamarin. Android and Microsoft.Azure.Mobile.Client Microsoft provider error - azure-mobile-services

I had a code that worked unlit few days ago: this is an xamarin.android activity code
[Activity(Label = "AuthSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
Button login;
//Mobile Service Client reference
private MobileServiceClient client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient("https://XXXXXXX.azurewebsites.net");
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
login = FindViewById<Button>(Resource.Id.buttonLoginUser);
login.Click += onLoginClick;
}
private async void onLoginClick(object sender, EventArgs e)
{
// Load data only after authentication succeeds.
if (await Authenticate())
{
}
}
// Define a authenticated user.
private MobileServiceUser user;
private async Task<bool> Authenticate()
{
var success = false;
try
{
// Sign in with Microsoft login using a server-managed flow.
user = await client.LoginAsync(this,
MobileServiceAuthenticationProvider.MicrosoftAccount);
CreateAndShowDialog(string.Format("you are now logged in - {0}",
user.UserId), "Logged in!");
success = true;
}
catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}
return success;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
i did all the instruction in the tutorial.
the LoginAsync redirect me to the Microsoft login page, i am able to authenticate and after a successful authentication i get this error : "the page cannot be displayed because an internal server error has occured"
i am working with 3.1 azure sdk version

According to your description, I assumed that you could follow the steps below to troubleshoot this issue.
For Node.js backend
You could leverage App Service Editor or kudu for create the iisnode.yml file under root folder (D:\home\site\wwwroot) if not exists. Then add the following settings for enable logging to debug a Node.js web app in azure app service:
loggingEnabled: true
logDirectory: iisnode
Additionally, here is a similar issue about enable node.js logging, you could refer to it. Also, for more details about kudu and app service editor, you could refer to here.
For C# backend
you could edit App_Start\Startup.MobileApp.cs file and configure the IncludeErrorDetailPolicy as follows for capturing the error details:
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
For a simple way, you could access https://{your-app-name}.azurewebsites.net/.auth/login/{provider-name} via the browser, then check the detailed error message for locating the specific error.
UPDATE:
Based on your address, I checked your app and found I could log with my Microsoft Account via the browser. Then I checked with your table endpoint and found the follow error:
https://{your-app-name}.azurewebsites.net/tables/todoitem?ZUMO-API-VERSION=2.0.0
message: "An error has occurred.",
exceptionMessage: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)",
exceptionType: "System.Data.SqlClient.SqlException",
As I known, when following the quickstart to create the data store for your backend, downloading the C# backend, then deploy the backend to moible app. At this point, your created connection string via azure portal would not be exposed to your ASP.NET application, and the default connection string would use the localdb, you need to edit the Web.config file before deploying to azure mobile app as follows:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:{your-sqlserver-name}.database.windows.net,1433;Initial Catalog={db-name};User ID={user-id};Password={password}" providerName="System.Data.SqlClient" />
</connectionStrings>
Or configure the connection string when deploy your app to azure mobile app via VS as follows:

It seems that there was a problem in azure or in Microsoft authentication.
after two days of frustration everything just started to work again!!

Related

Cannot access https://dev.azure.com/<myOrg> Using TFS extended client version 15

We are migrating some code that used to run against an on premise TFS server but now needs to run against Azure DevOps (previously Team Services). The credentials I'm using have been validated to successfully authenticate to our DevOps organization instance, but running the following code after referencing the
Microsoft.TeamFoundationServer.ExtendedClient
NuGet package always results in TF30063: You are not authorized to access https://dev.azure.com/<myOrg> The code is posted below for authenticating via non-interactive authentication. Do I need to use a different authentication mechanism or different credentials type to get this working?
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(_userName, DecryptedPassword, _domain);
try
{
// Create TeamFoundationServer object
_teamFoundationCollection = new TfsTeamProjectCollection(_serverUrl, networkCredential);
_teamFoundationCollection.Authenticate();
}
catch (Exception ex)
{
// Not authorized
throw new TeamFoundationServerException(ex.Message, ex.InnerException)
}
Since you want to use .Net Client Libraries, you could refer to the following link:
https://learn.microsoft.com/en-us/azure/devops/integrate/concepts/dotnet-client-libraries?view=azure-devops
Patterns for use:
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
const String c_collectionUri = "https://dev.azure.com/fabrikam";
const String c_projectName = "MyGreatProject";
const String c_repoName = "MyRepo";
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

GCP Pub/Sub throws "The Application Default Credentials are not available"

I am trying to publish to Google Pub/Sub topic using the following:
ProjectTopicName topicName = ProjectTopicName.of("my-project-id", "my-topic-id");
Publisher publisher = null;
try {
// Create a publisher instance with default settings bound to the topic
publisher = Publisher.newBuilder(topicName).build();
List<String> messages = Arrays.asList("first message", "second message");
for (final String message : messages) {
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Once published, returns a server-assigned message id (unique within the topic)
ApiFuture<String> future = publisher.publish(pubsubMessage);
// Add an asynchronous callback to handle success / failure
ApiFutures.addCallback(
future,
new ApiFutureCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
if (throwable instanceof ApiException) {
ApiException apiException = ((ApiException) throwable);
// details on the API exception
System.out.println(apiException.getStatusCode().getCode());
System.out.println(apiException.isRetryable());
}
System.out.println("Error publishing message : " + message);
}
#Override
public void onSuccess(String messageId) {
// Once published, returns server-assigned message ids (unique within the topic)
System.out.println(messageId);
}
},
MoreExecutors.directExecutor());
}
} finally {
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
I have changed the default values you see here to the particulars of the account I am hitting.
The environment variable points to the JSON file containing the pub/sub authentication credentials:
GOOGLE_APPLICATION_CREDENTIALS
was set using:
export GOOGLE_APPLICATION_CREDENTIALS=path/to/file.json
and verified with echo $GOOGLE_APPLICATION_CREDENTIALS - after a reboot.
But I am still encountering:
The Application Default Credentials are not available. They are available
if running in Google Compute Engine. Otherwise, the environment variable
GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining
the credentials. See https://developers.google.com/accounts/docs/application-
default-credentials for more information.
I believe this is related to the default environment that the application is running in, or rather what GCP object thinks the context is -runningOnComputeEngine:
com.google.auth.oauth2.ComputeEngineCredentials runningOnComputeEngine
INFO: Failed to detect whether we are running on Google Compute Engine.
also, a dialog displayed:
Unable to launch App Engine Server
Cannot determine server execution context
and there are no Google Cloud Platform settings in project (Eclipse 2019-3):
This is not an App Engine application.
How to set the environment that GCP objects point to -> Non App Engine.
For reference:
Server to Server (link in error message)
Publish
Google Cloud Tools for Eclipse
Java 7 application
Mac OS (Sierra)
The file permissions are set that app can read the file.
Google's documentation on this is terrible - it does not mention this anywhere.
The answer is to use:
// create a credentials provider
CredentialsProvider credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(new FileInputStream(Constants.PUB_SUB_KEY)));
// apply credentials provider when creating publisher
publisher = Publisher.newBuilder(topicName).setCredentialsProvider(credentialsProvider).build();
The Environment variable usage is either deprecated or the documentation is flat out wrong, or I'm missing something,... which is entirely possible given the poor documentation.

After Deploying, ASP.NET application showing Internal server error

I deployed my ASP.NET application to a remote server with a hosting company, and when i try to send data from Postman, i get the internal server error with no definite error message. I have set custom error mode to off in the web config file. please can anyone help me? I have checked for several solutions but nothing.
PS: i am new to ASP.NET deployment with other companies apart from Azure
In this case, you should log error to file to see what issues in deployment mode.
This way i implemented global error log.
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
//Log Critical errors
// You can use log4net library and configure log folder
}
}
In WebApiConfig.cs file you register it.
public static void Register(HttpConfiguration config)
{
// .....
config.Filters.Add(new ExceptionHandlingAttribute());
}

How can I use the service fabric actor model from MVC project?

I used the stateful actor template in visual studio 2015 to create a service fabric service. In the same solution I created an MVC app and in the about controller I attempted to copy the code from the sample client. When I run the web app and execute about action it just hangs. I don't get an exception or anything that indicates why it didn't work. Running the sample client console app where I got the code works just fine. Any suggestions on what may be wrong?
public ActionResult About()
{
var proxy = ActorProxy.Create<IO365ServiceHealth>(ActorId.NewId(), "fabric:/O365Services");
try
{
int count = 10;
Console.WriteLine("Setting Count to in Actor {0}: {1}", proxy.GetActorId(), count);
proxy.SetCountAsync(count).Wait(); /* Hangs here */
Console.WriteLine("Count from Actor {0}: {1}", proxy.GetActorId(), proxy.GetCountAsync().Result);
}
catch (Exception ex)
{
Console.WriteLine("{0}", ex.Message);
}
ViewBag.Message = "Your application description page.";
return View();
}
Is the MVC app hosted within Service Fabric? If not then it won't be able to access Service Fabric information unless it's exposed in some way (e.g. through an OwinCommunicationListener on a service).

Mobile Services (.Net backend) using incorrect connection string

I am struggling to make the .Net backend of Mobile Services use the correct connectionString. When I publish the service I select the correct connection string for "MS_TableConnectionString". If I check the web.config on the server (via FTP) I see what I would expect:
web.config on server:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:[ServerAddress].database.windows.net,1433;Initial Catalog=[MyMobileService_db];Integrated Security=False;User ID=[correctUserName];Password=[CorrectPassword];Connect Timeout=30;Encrypt=True" providerName="System.Data.SqlClient" />
In my context it is configured to use a connection string called MS_TableConnectionString:
private const string connectionStringName = "Name=MS_TableConnectionString";
public MyMobileServiceContext() : base(connectionStringName)
{
Schema = "MyMobileService";
}
To see what connection string is actually being used I added this to an example controller:
Example Client Code:
public class ExampleController : ApiController
{
MyMobileServiceContext context;
public ApiServices ApiServices { get; set; }
public ExampleController()
{
context = new MyMobileServiceContext();
}
public async Task<IHttpActionResult> PostExample(ExampleItem item)
{
ApiServices.Log.Warn("ConnectionString: " + context.Database.Connection.ConnectionString);
...
}
And when I look at the Log Entry on Mobile Services I see a different UserName and Password:
[2014-04-15T12:26:33.1410580Z] Level=Warn, Kind=Trace, Category='PostExampleItem', Id=00000000-0000-0000-0000-000000000000, Message='ConnectionString: Data Source=[SameServerAddress].database.windows.net;Initial Catalog=[SameDatabaseName];User ID=[DifferentUserName];Password=[DifferentPassword];Asynchronous Processing=True;TrustServerCertificate=False;'
The different username and password are the same as I see in the original .PublishSettings file that I downloaded under the name of SQLServerDBConnectionString but I have no idea where this is stored on the server?
Because of the different username and password I see the following exception in the log:
[2014-04-15T13:18:11.2007511Z] Level=Error, Kind=Trace, Category='App.Request', Id=d7ec6d25-f3b7-4e88-9024-217be40ae77f, Exception=System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: Cannot open database "master" requested by the login. The login failed.
Login failed for user '[DifferentUserName]'.
This session has been assigned a tracing ID of '[GUID]'. Provide this tracing ID to customer support when you need assistance.
Any help would be much appreciated as at the moment I am having to hard code the whole connection string in the constructor of the Context to make it work.
Thanks
F
UPDATE: 15th April 2014 15:23
I deleted all my publisher profiles and created a copy of the original .PublishSettings file. From this I deleted all but one profile. I then deleted the SQLDBConnectionString attribute to confirm that it is not because I was sending this that was causing the problem. The result was no change, it is still using the DifferentUserName and Password so it must be reading it from the server somewhere.
We have a hole at the moment in that we pick up the connection string from the portal yet don't expose the ability to set or modify connection strings there.
The work-around is to set an application setting in the portal and then use that in your code using the ApiServices class, something like this (in your controller)
string connectionString = this.Services.Settings["YourConnectionStringAsAppSetting"];
I know it is confusing... we'll make it easier to access and modify the connection strings.
Henrik