The given key was not found in the dictionary - windows-phone-7

I'm developing windows phone 8 application. In this, I have to integrate Twitter. So I have followed the below tutorial.
http://code.msdn.microsoft.com/wpapps/Latest-Twitter-integration-a42e8bb6
I've implemented successfully twitter in my application. I've tested this in Emulator and in device also. Everything was fine.
**Suddenly in the device the application is unable to open the twitter log in page. I'm getting the error in the below method at line started with .
void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
**OAuthTokenKey = parameters["oauth_token"];**
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = AppSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;
Dispatcher.BeginInvoke(() =>
{
this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute));
});
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
pi.IsVisible = false;
});
}
}
The given key was not present in the dictionary.
But in Emulator I'm successfully redirected to log in page if user is not logged in and posting the message.
I don't know what is the problem in the device.

This issue occurs when the the device you are using for testing the app is without simcard, as it the device without the simcard cannot match the timings of the twitter api server and this mismatch causes the authentication error, as for the api the credentials are invalid due to heavy difference in the timings between api server and device, hence try checking it on a device that has a simcard inside.

Related

ArcGIS version 100.3.0 android token

Below is the code I'm using for setting user credentials on ServiceFeatureTable.
ServiceFeatureTable featureTablePolygons = new ServiceFeatureTable(polygonUrl);
featureTablePolygons.setCredential(UserCredential.createFromToken(gisToken, referer));
//query feature from the table
final ListenableFuture<FeatureQueryResult> queryResultPolygons = featureTablePolygons.queryFeaturesAsync(query);
queryResultPolygons.addDoneListener(() -> {
try {
FeatureCollection featureCollection = new FeatureCollection();
FeatureQueryResult result = queryResultPolygons.get();
FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
featureCollectionTable.setRenderer(new SimpleRenderer(new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.translucent_red), new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 1))));
featureCollection.getTables().add(featureCollectionTable);
FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);
mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
if (result.iterator().hasNext()) {
Feature feature = result.iterator().next();
Envelope envelope = feature.getGeometry().getExtent();
mMapView.setViewpointGeometryAsync(envelope);
} else {
}
} catch (InterruptedException | ExecutionException e) {
Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
}
});
But this is not working. If I'm using AuthenticationManager then it's working fine but I don't want to use username and password in my code.
If you're manually getting the token, you can create a UserCredential object using createFromToken() and set it on the ServiceFeatureTable with setCredential().
However, many workflows for getting a token are handled by the Runtime (e.g. username + password, or OAuth via a Portal). Take a look at the AuthenticationManager documentation to get started.
Lastly, I think you'll get more eyes on your questions over at the ArcGIS Runtime SDK for Android forums.

Authenticating a Xamarin Android app using Azure Active Directory fails with 401 Unauthorzed

I am trying to Authenticate a Xamarin Android app using Azure Active Directory by following article here:
https://blog.xamarin.com/authenticate-xamarin-mobile-apps-using-azure-active-directory/
I have registered a native application with AAD; note that i havent given it any additional permissions beyond creating it.
Then i use the below code to authenticate the APP with AAD
button.Click += async (sender, args) =>
{
var authContext = new AuthenticationContext(commonAuthority);
if (authContext.TokenCache.Count > 0)
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().GetEnumerator().Current.Authority);
authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new PlatformParameters(this));
SetContentView(Resource.Layout.Main);
doGET("https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/OPSLABRG/providers/Microsoft.Compute/virtualMachines/LABVM?api-version=2015-08-01", authResult.AccessToken);
};
private string doGET(string URI, String token)
{
Uri uri = new Uri(String.Format(URI));
// Create the request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
// Get the response
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception ex)
{
Toast.MakeText(this, "Error from : " + uri + ": " + ex.Message, ToastLength.Long).Show();
return null;
}
}
This seems to be getting a token when using a Work account.
Using a valid hotmail account throws error A Bad Request was received.
However the main problem is when i try to retrieve VM details using REST.
the REST GET method fails with 401 Unauthorized error even when using the Work account.
I am not sure if the code is lacking something or if i need to give some additional permissions for the App. This needs to be able to support authenticating users from other tenants to get VM details.
Any guidance is appreciated.
note that i havent given it any additional permissions beyond creating
it.
This is the problem here.
In order for you to call the Azure Management API https://management.azure.com/, you must first register your application to have permissions to call this API.
You can do that as a part of your app registration like so:
Only at that point, will your app be authorized to call ARM, and your calls should start to work.
According to your description, I checked this issue on my side. As Shawn Tabrizi mentioned that you need to assign the delegated permission for accessing ARM Rest API. Here is my code snippet, you could refer to it:
var context = new AuthenticationContext($"https://login.windows.net/{tenantId}");
result = await context.AcquireTokenAsync(
"https://management.azure.com/"
, clientId, new Uri("{redirectUrl}"), platformParameter);
I would recommend you using Fiddler or Postman to simulate the request against ARM with the access_token to narrow this issue. If any errors, you could check the detailed response for troubleshooting the cause.
Here is my test for retrieving the basic information of my Azure VM:
Additionally, you could leverage jwt.io for decoding your access_token and check the related properties (e.g. aud, iss, etc.) as follows to narrow this issue.

Is it possible to run background transfer from background audio agent?

I want to run Background file transfer from Background audio agent but I get error with example code which runs correct in foreground app.
Here is example:
string transferFileName = #"http://www.reggaeavenue.com/MP3/leave%20short.mp3";
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = "result.mp3";
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception)
{
MessageBox.Show("Unable to add background transfer request.");
}
On the line with adding transferRequest to BackgroundTransferService I get error:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferRequest.SubmitHelper()
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferRequest.Submit()
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Add(BackgroundTransferRequest request)
at Project.AudioPlaybackAgent.AudioPlayer.CreateBackgroundTransfer()
So is it possible to run transferm from background agent? How can I fix this? Thanks
According to MSDN some API's (including background transfer) are not supported in background agents. Even if you manage to do some things, your app can fail certification tests.
Why not download files in main UI or play it directly from web source?

Can't singin into SkyDrive account. WP7

I am making SkyDrive integration in my app for Windows phone. Every time after login screen in signInButton_SessionChanged it gives me e.Status = Unknown with e.Error = "".
I tried download some examples for SkyDrive integration
http://rabeb.wordpress.com/2012/01/07/using-skydrive-in-your-windows-phone-applications-part-1/
, but it gives the same result.
private void signInButton1_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
infoTextBlock.Text = "Signed in.";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
I tried to change App ID ond Live account also, but nothing helps. Please help.
This can happen if in application settings at Live Connect Developer Center you haven't specified that it is a Mobile client app:

HttpWebRequest and WebClient returning NotFound on Windows Phone 7 but not i normal console application

I'm trying to download a regular JSON string from this url https://valueboxtest.lb.dk/mobile/categories from a Windows Phone 7 Application.
I have tried to both use WebClient and HttpWebRequest. They both throw an exception
“The remote server returned an error: NotFound”
This is the code for using the WebClient
var webClient = new WebClient();
webClient.DownloadStringCompleted += (client_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("https://valueboxtest.lb.dk/mobile/categories"));
The eventhandler then just show the content, but e.Result throws the above mentioned exception:
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled) MessageBox.Show(e.Result);
}
For the HttpWebRequest my code looks as follows:
var httpReq = (HttpWebRequest)WebRequest.Create(new Uri("https://valueboxtest.lb.dk/mobile/categories"));
httpReq.BeginGetResponse(HTTPWebRequestCallBack, httpReq);
With the following callback:
private void HTTPWebRequestCallBack(IAsyncResult result)
{
var httpRequest = (HttpWebRequest)result.AsyncState;
var response = httpRequest.EndGetResponse(result);
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
this.Dispatcher.BeginInvoke(
new delegateUpdate(update),
new Object[] { reader.ReadToEnd() }
);
}
And with the delegate method
delegate void delegateUpdate(string content);
private void update(string content)
{
MessageBox.Show(content);
}
Running it in a console application
Everything works just fine and the JSON string is returned with no problems and I am able to print the result to the console.
Different URL does work on WP7
The weird thing is that the URL http://mobiforge.com/rssfeed actually works fine in both of the above mentioned scenarios.
This issue occurs both in the Emulator and on an actual device.
What could be wrong? Is the REST service returning the data in misbehaving way? I really hope you can help me!
Note: I'm not running Fiddler2 at the same time!
The reason is because that site does not have a valid certificate. Just try it on Mobile Internet Explorer and you'll get the prompt about an issue with the certificate.
How to ignore SSL certificates
Mobile devices are stricter when it comes to SSL certificates.
If you want to get this app into a production environment, you'll either need to write a wrapper for this server (if it's not your own), or get a valid certificate. In the short-term, for testing, you can add a certificate into your device.
Here's a tool which might help you install a certificate.

Resources