This question already has answers here:
PreferenceManager getDefaultSharedPreferences deprecated in Android Q
(9 answers)
Closed 8 months ago.
I recently updated the nugget packages in my Android project and now I get a message in this line of code:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
CS0618: PreferenceManager.GetDefaultSharedPreferences(Context?) is obsolete: deprecated
enter image description here
Is it necessary to change something? Will my code not work correctly like this? Should I completely remove private void storeToken(String token)? I'm not sure if I still need private void storeToken(String token).
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Firebase.Messaging;
using System.Collections.Generic;
using Android.Preferences;
using Android.Media;
using AndroidX.Core.App;
namespace AndroidVersion
{
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnNewToken(string token)
{
Log.Debug(TAG, "Refreshed token: " + token);
storeToken(token);
}
private void storeToken(String token)
{
//saving the token on shared preferences
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_token", token);
editor.Apply();
}
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
var body = message.GetNotification().Body;
var title = message.GetNotification().Title;
Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotification(body, title, message.Data);
}
void SendNotification(string messageBody, string Title, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(Activity1));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this,
Activity1.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, Activity1.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle(Title)
.SetContentText(messageBody)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
.SetVibrate(new long[] { 1000, 1000, 0, 0, 0 })
.SetLights(Android.Graphics.Color.Red, 3000, 3000)
.SetPriority((int)NotificationPriority.High)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(Activity1.NOTIFICATION_ID, notificationBuilder.Build());
}
}
}
I use implementation 'androidx.preference:preference-ktx:1.1.1'
successfully replaced the deprecated android.preference.PreferenceManager in my project
Use using AndroidX.Preference; instead of using Android.Preferences;
Related
I have been trying to use Cognito Sign In for my application at ASP.NET C# and I have managed to make the user sign up. However, when I am trying to implement the codes for Sign In there are 2 errors at these lines below :
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
this line result in "CognitoUser does not contain a constructor that contain 4 arguments error"
and the 2nd error at this part :
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
this line result in "CognitoUser does not contain definition for StartWithSrpAuthAsync and No Extension Method…accepting a first argument of type ” could be found" error
This is my full code :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using System.Threading.Tasks;
using System.Configuration;
using Amazon.Extensions.CognitoAuthentication;
namespace WebApplication2
{
public partial class WebForm5 : System.Web.UI.Page
{
const string PoolID = "poolid";
const string ClientID = "clientid";
static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USEast1;
protected void Page_Load(object sender, EventArgs e)
{
string username = "user1";
string password = "pass";
string email = "email1";
SignInUser(username,password);
}
static async Task SignInUser(string username, string password)
{
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
CognitoUserPool userPool = new CognitoUserPool(PoolID, ClientID, provider);
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = password
};
AuthFlowResponse authResponse = null;
try
{
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
}
catch(Exception ex)
{
Console.WriteLine("Logon Failed: {0}\n", ex.Message);
return;
}
GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;
}
}
Any help will be appreciated.
Thank You
I'm attempting to initiate a call with the Microsoft Graph SDK Create call API using the code sample below. The attempt fails with a Not Found exception.
I have registered the bot application, added the API call permissions and I am able to receive incoming calls from Teams.
It's not clear from the Microsoft documentation whether Teams users can be called directly or whether they have to be allocated a VoIP number. Has anyone been able to use the Graph SDK to call a Teams User? Is there some special configuration a User needs to have in order to be able to receive a call?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Graph.Communications.Common.Telemetry;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Communications.Calls;
using Microsoft.Graph.Communications.Calls.Media;
using Microsoft.Graph.Communications.Client;
using Microsoft.Skype.Bots.Media;
namespace sipbotcaller
{
class Program
{
private static string APP_NAME = "";
private static string APP_ID = "";
private static string APP_SECRET = "";
private static string TENANT_ID = "";
private static string CALLBACK_URI = "";
private static string CERTIFICATE_THUMBPRINT = "";
private static int MEDIA_PORT = 10000;
private static string PUBLIC_IP = "";
private static string HOSTNAME = "";
static async Task Main(string[] args)
{
Console.WriteLine("Teams Call Console:");
GraphLogger graphLogger = new GraphLogger(APP_NAME);
graphLogger.DiagnosticLevel = System.Diagnostics.TraceLevel.Verbose;
ILogger logger = new ConsoleLogger(graphLogger);
AuthenticationProvider authProvider = new AuthenticationProvider(
APP_NAME,
APP_ID,
APP_SECRET,
TENANT_ID,
graphLogger);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var users = await graphClient.Users.Request().GetAsync();
foreach (var user in users)
{
Console.WriteLine($"user Id: {user.Id}.");
Console.WriteLine($"user Display Name: {user.DisplayName}.");
}
var mediaPlatformSettings = new MediaPlatformSettings()
{
MediaPlatformInstanceSettings = new MediaPlatformInstanceSettings()
{
CertificateThumbprint = CERTIFICATE_THUMBPRINT,
InstanceInternalPort = MEDIA_PORT,
InstancePublicIPAddress = IPAddress.Parse(PUBLIC_IP),
InstancePublicPort = MEDIA_PORT,
ServiceFqdn = HOSTNAME,
},
ApplicationId = APP_ID,
};
var builder = new Microsoft.Graph.Communications.Client.CommunicationsClientBuilder(
APP_NAME,
APP_ID,
graphLogger);
builder
.SetAuthenticationProvider(authProvider)
.SetNotificationUrl(new Uri(CALLBACK_URI))
.SetMediaPlatformSettings(mediaPlatformSettings)
.SetServiceBaseUrl(new Uri(CALLBACK_URI));
var client = builder.Build();
AudioSocketSettings audioSockSettings = new AudioSocketSettings {
CallId = Guid.NewGuid().ToString(),
SupportedAudioFormat = AudioFormat.Pcm16K,
StreamDirections = StreamDirection.Sendrecv
};
AudioSocket audioSock = new AudioSocket(audioSockSettings);
var mediaConfig = MediaPlatform.CreateMediaConfiguration(audioSock);
Console.WriteLine($"media config: {mediaConfig}");
Console.WriteLine($"Attempting to call {users.First().DisplayName}.");
var call = new Call
{
CallbackUri = CALLBACK_URI,
TenantId = TENANT_ID,
Targets = new List<InvitationParticipantInfo>()
{
new InvitationParticipantInfo
{
Identity = new IdentitySet
{
User = new Identity
{
DisplayName = users.First().DisplayName,
Id = users.First().Id
},
}
}
},
RequestedModalities = new List<Modality>()
{
Modality.Audio
},
MediaConfig = new AppHostedMediaConfig()
{
Blob = mediaConfig.ToString(Newtonsoft.Json.Formatting.None)
},
};
var callResult = await client.Calls().AddAsync(call);
Console.WriteLine($"Call result {callResult.Id}.");
Console.WriteLine("Finished.");
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
Result:
<snip>
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Info
StatefulCall: Error {
"error": {
"code": "itemNotFound",
"message": "Unexpected exception returned from the service.\r\nStatus Code: NotFound"
}
}
StatefulCall: Info
i am new to C# and I would like to make a bot mixing Luis services and customvision.
I would like the user to be able to send an image or text to the bot.
I am starting from the microsoft bot framework "core bot"* and the imageprocessing bot** (*https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/13.core-bot, **https://github.com/mandardhikari/ImageProcessingBot )
for the moment, i do have this code which is mix between the two samples
#region References
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.IO;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Recognizers.Text.DataTypes.TimexExpression;
#endregion
namespace ImageProcessingBot
{
public class ImageProcessingBot : IBot
{
private readonly FlightBookingRecognizer _luisRecognizer;
protected readonly ILogger Logger;
private readonly ImageProcessingBotAccessors _accessors;
private readonly IConfiguration _configuration;
private readonly DialogSet _dialogs;
public ImageProcessingBot(ImageProcessingBotAccessors accessors, IConfiguration configuration)
{
_accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_dialogs = new DialogSet(_accessors.ConversationDialogState);
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
Activity reply = null;
HeroCard card ;
StringBuilder sb;
switch(turnContext.Activity.Type)
{
case ActivityTypes.ConversationUpdate:
foreach(var member in turnContext.Activity.MembersAdded)
{
if(member.Id != turnContext.Activity.Recipient.Id)
{
reply = await CreateReplyAsync(turnContext, "Welcome. Please select and operation");
await turnContext.SendActivityAsync(reply, cancellationToken:cancellationToken);
}
}
break;
case ActivityTypes.Message:
int attachmentCount = turnContext.Activity.Attachments != null ? turnContext.Activity.Attachments.Count() : 0;
var command = !string.IsNullOrEmpty(turnContext.Activity.Text) ? turnContext.Activity.Text : await _accessors.CommandState.GetAsync(turnContext, () => string.Empty, cancellationToken);
command = command.ToLowerInvariant();
if(attachmentCount == 0)
{
var luisResult = await _luisRecognizer.RecognizeAsync<FlightBooking>(turnContext, cancellationToken);
switch (luisResult.TopIntent().intent)
{
case FlightBooking.Intent.Weather:
// We haven't implemented the GetWeatherDialog so we just display a TODO message.
var getWeatherMessageText = "TODO: get weather flow here";
var getWeatherMessage = MessageFactory.Text(getWeatherMessageText, getWeatherMessageText, InputHints.IgnoringInput);
await turnContext.SendActivityAsync(getWeatherMessage, cancellationToken);
var attachments = new List<Attachment>();
var reply = MessageFactory.Attachment(attachments);
reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
default:
// Catch all for unhandled intents
var didntUnderstandMessageText = $"Sorry, I didn't get that. Please try asking in a different way (intent was {luisResult.TopIntent().intent})";
var didntUnderstandMessage = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput);
await turnContext.SendActivityAsync(didntUnderstandMessage, cancellationToken);
break;
}
}
else
{
HttpClient client = new HttpClient();
Attachment attachment = turnContext.Activity.Attachments[0];
...// then it stays as in https://github.com/mandardhikari/ImageProcessingBot/blob/master/ImageProcessingBot/ImageProcessingBot/ImageProcessingBot.cs
I am getting these logs.
1>ImageProcessingBot.cs(78,41,78,46): error CS0136: A local or parameter named 'reply' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
1>ImageProcessingBot.cs(72,33,72,67): error CS0163: Control cannot fall through from one case label ('case FlightBooking.Intent.Weather:') to another
I am new to c#, so any insights on the above would be greatly appreciated!
This is essentially repeating what #stuartd says above in the comments.
The method MessageFactory.Attachemnt returns an IMessageActivity so probably best to use a second variable rather than your Activity reply to avoid casting
case FlightBooking.Intent.Weather:
// We haven't implemented the GetWeatherDialog so we just display a TODO message.
var getWeatherMessageText = "TODO: get weather flow here";
var getWeatherMessage = MessageFactory.Text(getWeatherMessageText, getWeatherMessageText, InputHints.IgnoringInput);
await turnContext.SendActivityAsync(getWeatherMessage, cancellationToken);
var attachments = new List<Attachment>();
meesageReply = MessageFactory.Attachment(attachments); //new variable
messageReply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
break;
I have wrapped the C# FCM AdminSDK in a WCF. When I publish the code to my local using debug everything works as expected. When I publish the code using release I get a "Object reference not set to an instance of an object." when attempting to instantiate the "Message" object. Why does this happen?
The exception happens on the line "var fcmMessage = new Message()"
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using ID.Service.PushNotification.Enums;
using ID.Service.PushNotification.Models;
using ID.Service.PushNotification.ServiceHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Hosting;
namespace ID.Service.PushNotification.Helpers
{
public class FcmHelper
{
readonly static FirebaseApp app = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(HostingEnvironment.MapPath(#"~/App_Data/jq4bb-37597f7301.json"))
});
public static void BulkPushNotification(List<EnrolmentModel> enrolments, string message, int messageId, DeepLink path = DeepLink.None)
{
foreach (EnrolmentModel enrolment in enrolments)
{
PushNotification(enrolment, message, messageId, path);
}
}
public static async void PushNotification(EnrolmentModel enrolment, string message, int messageId, DeepLink path = DeepLink.None)
{
try
{
var pathLink = (path != DeepLink.None) ? path.GetPath() : "";
var registrationToken = Encoding.UTF8.GetString(Convert.FromBase64String(enrolment.DeviceToken));
LogHelper.Error("rt: " + registrationToken);
LogHelper.Error("msg: " + message);
LogHelper.Error("pl" + pathLink);
var fcmMessage = new Message()
{
Token = registrationToken,
Android = new AndroidConfig()
{
Notification = new AndroidNotification()
{
Body = message,
Title = "Title",
Sound = "bing"
//ClickAction = "rewards",
//Color = "#CA5151",
//Icon="",
},
Priority = Priority.Normal,
TimeToLive = TimeSpan.FromSeconds(2419200),
//Data = new Dictionary<string, string>()
//{
// { "deepLinkPath", pathLink }
//},
}
};
// Send a message to the device corresponding to the provided
// registration token.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(fcmMessage);
bool successfullySent = false;
if (response.ToLower().Contains("projects/com-app/messages/0:"))
{
successfullySent = true;
}
ResultFeedbackServiceHelper.SaveResultFeedback(
response,
Convert.ToInt32(messageId),
Convert.ToInt32(enrolment.DeviceId),
successfullySent,
new List<string> { enrolment.DeviceToken }
);
}
catch (Exception ex)
{
ResultFeedbackServiceHelper.SaveResultFeedback(
ex.Message,
Convert.ToInt32(messageId),
Convert.ToInt32(enrolment.DeviceId),
false,
new List<string> { enrolment.DeviceToken }
);
LogHelper.Error("Error sending push messages to (fcm) gcn " + ex.ToString());
}
}
}
}
Exception:''2019-03-05 15:09:55,637 Thread:'[13]' Level:'ERROR' Message:'Error sending push messages to (fcm) gcn System.NullReferenceException: Object reference not set to an instance of an object.
at ID.Service.PushNotification.Helpers.FcmHelper.d__2.MoveNext() in D:\BuildAgents\Agent1_work\475\s\PNS\Main\ID.Service.PushNotification\Helpers\FCMHelper.cs:line 49'
I am trying to convert a users input in Edit text to LatLng when the Search button is clicked. This will then update the camera and move tot hat position.
Here is my code in the main:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using Android.Locations;
using System.Linq;
namespace SafeandSound
{
[Activity(Label = "SafeandSound", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private GoogleMap mMap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
SetUpMap();
}
private void SetUpMap()
{
if (mMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
}
}
public void OnMapReady(GoogleMap googleMap)
{
mMap = googleMap;
}
// Button to Search for Address//
public void onMapSearch(View view)
{
EditText address = (EditText)FindViewById(Resource.Id.searchText);
var addressnew = address.Text;
if (addressnew != null)
{
addressnew = address.Text;
}
Geocoder geoCoder = new Geocoder(this);
IList<Address> coordinates = geoCoder.GetFromLocationName(addressnew, 0);
Address gotAddress = coordinates.FirstOrDefault();
LatLng latLng = new LatLng(gotAddress.Latitude, gotAddress.Longitude);
CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
builder.Target(latLng);
builder.Zoom(10);
CameraPosition cameraPosition = builder.Build();
CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
}
}
}
When I use this right now, I get an exception error. Please HELP!!!
First you need to check if the Geocoder service is available on the device/emulator via the static method:
Geocoder.isPresent
Note: The use of Geocoder requires Internet access and Google Play services to be installed...
Next you are requesting zero results in the "maxResults" parameter:
GetFromLocationName(addressnew, 0);
int: max number of results to return. Smaller numbers (1 to 5) are recommended
Also you might need to retry the request to obtain results. You should not hammer the service as you will get throttled. Use a retry delay that increasing after each attempt.
Example:
if (!Geocoder.IsPresent)
{
Log.Error("SO", "Geocoder is not present");
}
else
{
var geocoder = new Geocoder(this);
var retry = 0;
do
{
var addressList = await geocoder.GetFromLocationNameAsync("Starbucks 523 Pine Street, Seattle, WA, 98101", 5);
if (addressList.Count > 0)
{
foreach (var address in addressList)
{
Log.Debug("SO", $"{address.Latitude}:{address.Longitude} - {address.FeatureName} : {address.GetAddressLine(0)} : {address.GetAddressLine(1)}");
}
break;
}
retry++;
Log.Warn("SO", $"No addresses returned...., retrying in {retry * 2} secs");
await Task.Delay(retry * 1000);
} while (retry < 5);
}
Output:
[SO] 47.611423:-122.337519 - Starbucks : Starbucks : 400 Pine Street
[SO] 47.611848:-122.335693 - Starbucks : Starbucks : 515 Pine Street