Xamarin.Android Notifications not working correctly - c#

Using AlarmManager application creates a notification in concrete time. We faced with a problem, from users' words notifications not appear or appear without any sound (settings are fine).
Please tell us what can it be connected with (users say that messengers applications create notifications without any problem)?
Can be the reason of it that we use NOT Notification.Builder and NotificationManager, but AppCompat alternatives: NotificationCompat.Builder and NotificationManagerCompat?
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using System.Threading;
using Android.Support.V4.Content;
using ME.Leolin.Shortcutbadger;
using Android.Media;
namespace WeeklyApp
{
[BroadcastReceiver]
public class WeeklyAlarmReceiver : WakefulBroadcastReceiver
{
private NotificationCompat.Builder builder;
private NotificationManagerCompat manager;
public static readonly int millisForPause = 1000;
private SettingsWorker settingsWorker;
private DealsDBWorker dealsDBWorker;
private int notificationValue;
private int soundValue;
private int badgeValue;
private DateTime currentDate;
private string currentStringDate;
private long currentTime;
private List<Task> currentDayTasks;
private Task notificationTask;
private DateTime startingUnixTime = new DateTime(1970, 1, 1);
private string defaultTitleText;
private string applicationName;
private string notificationText;
private string dealNotificationTime;
private int pendingIntentId = 0;
private int maxDealTextLength = 100;
private string dealNotificationText;
private DealsDBWorker dbWorker;
private DatesWorker datesWorker;
public static int notificationNumber = 0;
public static List<int> taskIDS;
private Intent mainIntent;
private static int currentAPIVersion = (int)Build.VERSION.SdkInt;
public WeeklyAlarmReceiver()
{
defaultTitleText = Application.Context.GetString(Resource.String.NotificationDefaultText);
applicationName = Application.Context.GetString(Resource.String.ApplicationName);
}
public override void OnReceive(Context context, Intent intent)
{
settingsWorker = new SettingsWorker();
dealsDBWorker = new DealsDBWorker();
mainIntent = new Intent(Application.Context, typeof(MainActivity));
mainIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);
mainIntent.SetFlags(ActivityFlags.BroughtToFront | ActivityFlags.ClearTop);
notificationValue = settingsWorker.GetNotificationsValue();
soundValue = settingsWorker.GetSoundValue();
badgeValue = settingsWorker.GetShowCounterValue();
if (builder == null)
{
builder = new NotificationCompat.Builder(context);
}
builder.SetContentTitle(applicationName);
manager = NotificationManagerCompat.From(Application.Context);
if (currentAPIVersion >= 21)
{
builder.SetSmallIcon(Resource.Drawable.ic_notification);
}
else
{
builder.SetSmallIcon(Resource.Drawable.ic_launcher);
}
GetCurrentNotificationTask();
if (taskIDS == null)
{
taskIDS = new List<int>();
}
if (notificationTask != null)
{
CreateNotification(context);
}
}
private void CreateNotification(Context context)
{
mainIntent.PutExtra("DealIdToShow", notificationTask.Id);
DateTime date = DateTime.Parse(notificationTask.TaskDate);
PendingIntent pendingIntent = PendingIntent.GetActivity(context, notificationTask.Id, mainIntent, PendingIntentFlags.UpdateCurrent);
builder.SetContentIntent(pendingIntent);
GetDealNotificationTime();
GetDealNotificationText();
notificationText = string.Format(defaultTitleText, dealNotificationTime, dealNotificationText);
builder.SetContentText(notificationText);
builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notificationText));
builder.SetAutoCancel(true);
SetNotification();
}
private void SetNotification()
{
if (soundValue != 0)
{
builder.SetVibrate(new long[] { 10, 1200 });
builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
}
if (notificationValue != 0)
{
notificationNumber++;
taskIDS.Add(notificationTask.Id);
if (Build.Manufacturer.Equals("Xiaomi", StringComparison.InvariantCultureIgnoreCase) && badgeValue != 0)
{
ShortcutBadger.RemoveCount(Application.Context);
manager.Cancel(101);
if(notificationNumber != 0)
{
//ShortcutBadger.ApplyNotification(Application.Context, resultNotification, notificationNumber);
ShortcutBadger.ApplyNotification(Application.Context, builder.Build(), notificationNumber);
}
else
{
ShortcutBadger.RemoveCount(Application.Context);
}
}
manager.Notify(101, builder.Build());
}
}
private void GetDealNotificationText()
{
int textLength = notificationTask.Text.Length;
if (textLength <= maxDealTextLength)
{
dealNotificationText = notificationTask.Text;
}
else
{
dealNotificationText = $"{notificationTask.Text.Substring(0, maxDealTextLength)}...";
}
}
private void GetDealNotificationTime()
{
DateTime resultTime = startingUnixTime.AddSeconds(notificationTask.TaskTime);
string defaultString = "{0}:{1}";
if (resultTime.Minute < 10)
{
defaultString = "{0}:0{1}";
}
dealNotificationTime = string.Format(defaultString, resultTime.Hour, resultTime.Minute);
}
private Task GetCurrentNotificationTask()
{
currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
currentStringDate = currentDate.Date.ToString().Remove(10, 8);
currentDayTasks = dealsDBWorker.GetTasks(currentStringDate, true);
currentTime = (long)(currentDate - startingUnixTime).TotalSeconds;
if (currentDayTasks != null)
{
notificationTask = Array.Find(currentDayTasks.ToArray(), (a => a.TaskTime == currentTime));
if (notificationTask != null && (notificationTask.TaskTime % 10) != 0)
{
notificationTask = null;
}
}
else
{
notificationTask = null;
}
return notificationTask;
}
}
}

Related

How to write working servers to the .txt file?

I have Pinger Application that gets all ping informations of servers written in the Servers.txt file
Half of them working servers, half of them not. I want to make my application write working servers to the another .txt file called WorkingServers.txt located in C:\Program Files\Servers folder
Here is my code:
using System;
using System.IO;
using System.Threading;
namespace AnchovyMultiPing
{
class Program
{
static void Main(string[] args)
{
var servers = File.ReadAllLines(#"C:\Program Files\Servers\Servers.txt");
foreach (var line in servers)
{
string currentServer = line;
if (args == null) throw new ArgumentNullException("args");
var waiter = new ManualResetEventSlim(false);
var pingData = new MultiPing(new[] { line }, waiter, 300);
waiter.Wait();
Console.WriteLine(pingData.GetPingInformation());
}
Console.WriteLine();
Console.WriteLine("- * - * - The Job is Done - * - * -");
Console.ReadLine();
}
}
}
and MultiPing.cs:
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
namespace AnchovyMultiPing
{
internal sealed class MultiPing : AbstractMultiPing
{
private int Timeout { get; set; }
private string[] Hosts { get; set; }
private int _count;
private ManualResetEventSlim Waiter { get; set; }
private readonly byte[] _buffer = Encoding.ASCII.GetBytes("aaa");
private Dictionary<string, long> _table = new Dictionary<string, long>();
private class Parameters
{
public String Host { get; set; }
public ManualResetEventSlim Event { get; set; }
}
public MultiPing(string[] hosts, ManualResetEventSlim waiter, int timeout = 12000)
{
Hosts = hosts;
Waiter = waiter;
Timeout = timeout;
RequestTime();
}
public override IMultiPings RequestTime()
{
try
{
_count = 0;
_table = new Dictionary<string, long>();
foreach (string host in Hosts)
{
using (var pingSender = new Ping())
{
pingSender.PingCompleted += PingCompletedCallback;
var options = new PingOptions(64, true);
try
{
pingSender.SendAsync(host, Timeout, _buffer, options,
new Parameters {Host = host, Event = Waiter});
}
catch
{
_count += 1;
if (_count == Hosts.Length)
Waiter.Set();
}
}
}
}
catch (MultiPingException ex)
{
Console.Write("RequestTime Exception");
Console.ReadKey();
}
return this;
}
//[MethodImpl(MethodImplOptions.Synchronized)] leaving this in favour of the operating system scheduler for better performance.
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
try
{
_count += 1;
PingReply reply = e.Reply;
if (reply != null && reply.Address != null && reply.Address.ToString() != "0.0.0.0")
{
if (_count > 0)
{
try
{
if (!_table.ContainsKey(reply.Address.ToString()))
_table.Add(((Parameters) e.UserState).Host, reply.RoundtripTime);
}
catch (NullReferenceException ex)
{
// catch null exception
throw new MultiPingException("Ping round trip time is null");
}
}
}
if (_count == Hosts.Length)
{
((Parameters) e.UserState).Event.Set();
}
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
Console.WriteLine(e.Error.ToString());
((ManualResetEventSlim) e.UserState).Set();
}
}
catch (MultiPingException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
}
public override String GetPingInformation()
{
var build = new StringBuilder();
foreach (string host in _table.Keys)
{
build.AppendLine(string.Format("{0} : {1}", host, _table[host]));
}
return build.ToString();
}
public override String GetIp()
{
string ip = "";
long time = -1L;
foreach (string host in _table.Keys)
{
long roundTime = _table[host];
if ((time == -1L) || (roundTime >= 0 && roundTime < time))
{
time = roundTime;
ip = host;
}
}
return ip;
}
}
}
Declare new string at the beginning var log = string.Empty; At the end of the iteration add the server name to it, if the ping is successful. I don't know how the MultiPing class looks like, so I added artificial IsSuccessful, but what I mean is something like this:
waiter.Wait();
if(pingData.IsSuccessful)
{
log += line;
}
Console.WriteLine(pingData.GetPingInformation());
Then as the last line of your program save everything to the other file.
File.AppendAllText("C:\Program Files\Servers\WorkingServers.txt", log);

Xamarin Loop (Thread) in Foreground Service not continue when device is unplugged

Hi i've a problem getting location each 1-5 minutes with a Foreground Service, when I unplug the device and turn off the screen, the thread stops but the service notification is visible all time,
how can i prevent this?
i was reading about to use AlarmManager (is a real solution), how can i do it ? or should only foreground service do it by self
this is my code:
using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;
using Android.Text.Format;
using Invima.VehiculosApp.ViewModels;
using Java.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace Invima.VehiculosApp
{
[Service(Label = "LocationUpdatesService", Enabled = true, Exported = true)]
[IntentFilter(new string[] { "com.Antss.InvimaVehiculos.Service" })]
public class LocationService : Service
{
IBinder Binder;
public override IBinder OnBind(Intent intent)
{
return Binder;
}
public const int ServiceRunningNotifID = 9000;
Ruta ruta;
Thread hiloUbicacion;
private System.Timers.Timer timer;
public override void OnCreate()
{
Notification notif = DependencyService.Get<INotification>().ReturnNotif();
StartForeground(ServiceRunningNotifID, notif);
_ = TomarUbicaciones();
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
string rutaStr = intent.GetStringExtra("ruta");
this.ruta = JsonConvert.DeserializeObject<Ruta>(rutaStr);
var autoEvent = new AutoResetEvent(false);
// i tried this but ... the same problem
timer = new System.Timers.Timer(30000);
timer.Elapsed += async (object sender, System.Timers.ElapsedEventArgs e) =>
{
using (HttpClient cl = new HttpClient())
{
await cl.GetAsync("https://webhook.site/a718fef4-769b-4871-87a8-ec1ccd83fc50");
}
};
timer.Start();
return StartCommandResult.Sticky;
}
public int TomarUbicaciones()
{
hiloUbicacion = new Thread(TomarUbicacionAsync);
hiloUbicacion.Start();
return 1;
}
int contador = 0;
public async void TomarUbicacionAsync()
{
while (true)
{
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Medium);
var location = await Geolocation.GetLocationAsync(request);
if (location != null && ruta != null)
{
Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
App.BD.RutaUbicacion.Add(new RutaUbicacion
{
Fecha = DateTime.Now,
IdRuta = ruta.IdRuta,
Latitud = (decimal)location.Latitude,
Longitud = (decimal)location.Longitude,
Altitud = (decimal)location.Altitude
});
App.BD.SaveChanges();
App.Sincronizar();
}
Device.BeginInvokeOnMainThread(() =>
{
DependencyService.Get<IMessage>().ShortAlert("Done!");
});
}
catch (Exception ex)
{
}
Thread.Sleep(60000); // each minute
}
}
public override void OnDestroy()
{
try
{
hiloUbicacion.Abort();
}
catch { }
base.OnDestroy();
}
public override bool StopService(Intent name)
{
try
{
hiloUbicacion.Abort();
}
catch { }
return base.StopService(name);
}
}
}

Change a label on a form from another class

My problem might be a dumb one but after hours of searching, I have to ask you for help.
I have a WPF form LoginPage that features a Label ,(called AlertText) that displays messages to the user and I need to change his content from another class.
To change the content I use AlertText.Content = "content" and it works perfectly.
But when I'm on another class and I want to change it that doesn't do anything.
Both class are under the same namespace.
I've tried this :
LoginPage lg = new LoginPage();
lg.AlertText.Content = "content";
The object is created but the second line isn't executed.
I've tried to create a public function SetAlertText() in my LoginPage class but that doesn't worked either.
I made it static and called it by LoginPage.SetAlertText() but same problem persists.
I've added this in my LoginPage :
public static LoginPage instance;
public LoginPage()
{
instance = this;
}
And called it by
LoginPage.instance.SetAlertText();
and
LoginPage.instance.AlertText.Content = "content";
but neither worked.
I also tried :
public LoginPage()
{
instance = new LoginPage();
}
What can I do ?
Edit :
Here's the full code of both classes :
namespace TMClientWPF
{
/// <summary>
/// Logique d'interaction pour LoginPage.xaml
/// </summary>
public partial class LoginPage : Page
{
ClientTCP client;
bool isConnected = false;
public RegisterPage registerPage;
public static LoginPage instance;
public LoginPage()
{
instance = this;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AlertText.Content = "";
try
{
if (isConnected == false)
{
client = new ClientTCP();
client.Connect();
isConnected = true;
}
client.SEND_LOGINS(UsernameText.Text, PasswordText.Password.ToString());
}
catch (NullReferenceException)
{
AlertText.Visibility = Visibility.Visible;
AlertText.Content = "Failed to connect to server, please try again later.";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
registerPage = new RegisterPage();
this.NavigationService.Navigate(registerPage);
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
public void SetAlertText(string text)
{
AlertText.Visibility = Visibility.Visible;
AlertText.Content = "Welcome Home";
}
}
}
///////////////////////////////
namespace TMClientWPF
{
public class ClientHandlePackets
{
public static ByteBuffer playerBuffer;
private delegate void Packet_(byte[] data);
private static Dictionary<long, Packet_> packets;
private static long pLength;
public static void HandleData(byte[] data)
{
InitializePackets();
byte[] Buffer;
Buffer = (byte[])data.Clone();
if (playerBuffer == null)
{
playerBuffer = new ByteBuffer();
}
playerBuffer.WriteBytes(Buffer);
if (playerBuffer.Count() == 0)
{
playerBuffer.Clear();
return;
}
if (playerBuffer.Length() >= 8)
{
pLength = playerBuffer.ReadLong(false);
if (pLength <= 0)
{
playerBuffer.Clear();
return;
}
}
while (pLength > 0 & pLength <= playerBuffer.Length() - 8)
{
if (pLength <= playerBuffer.Length() - 8)
{
playerBuffer.ReadLong(); //read out the packet identifier
data = playerBuffer.ReadBytes((int)pLength); //get the full package length
HandleDataPackets(data);
}
pLength = 0;
if (playerBuffer.Length() >= 8)
{
pLength = playerBuffer.ReadLong(false);
if (pLength < 0)
{
playerBuffer.Clear();
return;
}
}
}
}
private static void HandleDataPackets(byte[] data)
{
long packetIdentifier;
ByteBuffer buffer;
Packet_ packet;
buffer = new ByteBuffer();
buffer.WriteBytes(data);
packetIdentifier = buffer.ReadLong();
buffer.Dispose();
if (packets.TryGetValue(packetIdentifier, out packet))
{
packet.Invoke(data);
}
}
private static void InitializePackets()
{
packets = new Dictionary<long, Packet_>();
packets.Add((long)ServerPackets.S_INFORMATION, PACKET_INFORMATION);
packets.Add((long)ServerPackets.S_EXECUTEMETHODONCLIENT, PACKET_EXECUTEMETHOD);
packets.Add((long)ServerPackets.S_LOGCALLBACK, Packet_LogCallback);
}
#region packets
private static void PACKET_INFORMATION(byte[] data)
{
ByteBuffer buffer = new ByteBuffer();
buffer.WriteBytes(data);
long packetIndentifier = buffer.ReadLong();
string msg1 = buffer.ReadString();
string msg2 = buffer.ReadString();
int level = buffer.ReadInteger();
buffer.Dispose();
ClientTCP.instance.SEND_THANKYOU();
}
private static void PACKET_EXECUTEMETHOD(byte[] data)
{
ClientTCP client = new ClientTCP();
}
private static void Packet_LogCallback(byte[] data)
{
ByteBuffer buffer = new ByteBuffer();
buffer.WriteBytes(data);
buffer.ReadLong();
string message = buffer.ReadString();
string username = buffer.ReadString();
buffer.Dispose();
if(message == "true")
{
// LoginPage.SetAlertText("Welcome Home.");
}
else
{
LoginPage lg = new LoginPage();
LoginPage.instance.SetAlertText("Invalid logins.");
}
}
#endregion
}
}

String building and form component access from class

Background
I am writing a program, which collects different events (key press, mouse position, and others) and sends a single string to a serial port.
There is a small part of the program, where a key is pressed, to control movement (forward - W key; left - A key, Forward-left - WA key).
When an event happens, a method is invoked, which grabs a numeric string and processes in the FinalStringClass Class. On the main form , there is a method, which assigns collected value to a label.
However, I am encountering a problem with code due to lack of experience in programming :(
Main Form:
Serial port;
FinalStringClass fstr;
public Form1()
{
InitializeComponent();
//... Serial port settings
timer.Start();
fstr = new FinalStringClass(UpdateLabel2);
}
public void UpdateLabel2(string x, string y, string speed, string mvm) //
{
label2.Text = "x: " + x + "y: " + y + "speed: " + speed + "mvm: " + mvm;
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
if (left.IsPressed)
{
if (up.IsPressed == true) // if W and A keys are pressed, ->
{
fstr.mvmMethod("7"); // this method is triggered
return;
}
if (down.IsPressed)
{
fstr.mvmMethod("9");
return;
}
if (right.IsPressed)
{
fstr.mvmMethod("1");
return;
}
fstr.mvmMethod("4"); //if W key is pressed, then this method is triggered
}
//... (other if condition statements)
label2.Text = fstr.FinalStringBuilder();
port.Write(fstr.FinalStringBuilder());
}
External Class:
class FinalStringClass
{
private Action<string, string, string, string> updateLabel2;
Action<String> _x, _y, _speed, _mvm;
string xF, yF, speedF, mvmF;
public FinalStringClass(Action<string, string, string, string> updateLabel2)
{
this.updateLabel2 = updateLabel2;
}
public FinalStringClass(Action<String> x, Action<String> y, Action<String> speed, Action<String> mvm)
{
_x = x;
_y = y;
_speed = speed;
_mvm = mvm;
}
public void xMethod(string x)
{
_x(x);
xF = x;
}
public void yMethod(string y)
{
_y(y);
yF = y;
}
public void speedMethod(string speed)
{
_speed(speed);
speedF = speed;
}
public void mvmMethod(string mvm)
{
_mvm(mvm);
mvmF = mvm;
}
public string FinalStringBuilder()
{
return xF + yF + speedF + mvmF;
}
}
When working with a single parameter, everything works fine. But dealing with multiple parameters causes a problem :(
Example of working with a single parameter (full working code):
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FFApp
{
public partial class Form1 : Form
{
SerialPort port;
MyClass outside;
public Form1()
{
InitializeComponent();
timer.Start();
outside = new MyClass(UpdateLabel);
}
public void UpdateLabel(string str)
{
label1.Text = str;
}
private void init()
{
port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 115200;
try
{
port.Open();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
public struct KeyStateInfo
{
private Keys key;
private bool isPressed;
private bool isToggled;
public KeyStateInfo(Keys key, bool ispressed, bool istoggled)
{
this.key = key;
isPressed = ispressed;
isToggled = istoggled;
}
public static KeyStateInfo Default
{
get
{
return new KeyStateInfo(Keys.None, false, false);
}
}
public Keys Key
{
get { return key; }
}
public bool IsPressed
{
get { return isPressed; }
}
public bool IsToggled
{
get { return isToggled; }
}
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
Keyboard kb = new Keyboard();
if (left.IsPressed)
{
if (up.IsPressed == true)
{
outside.MyMethod("7");
return;
}
if (down.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("4");
}
if (right.IsPressed)
{
if (up.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("8");
return;
}
if (left.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("5");
}
if (up.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("7");
return;
}
if (right.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("2");
}
if (down.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("8");
return;
}
if (up.IsPressed)
{
outside.MyMethod("9");
return;
}
outside.MyMethod("3");
}
if (!right.IsPressed && !left.IsPressed && !up.IsPressed && !down.IsPressed)
{
outside.MyMethod("1");
}
}
public class KeyboardInfo
{
[DllImport("user32")]
private static extern short GetKeyState(int vKey);
private KeyboardInfo()
{
}
public static KeyStateInfo GetKeyState(Keys key)
{
short keyState = GetKeyState((int)key);
int low = Low(keyState), high = High(keyState);
bool toggled = low == 1;
bool pressed = high == 1;
return new KeyStateInfo(key, pressed, toggled);
}
private static int High(int keyState)
{
return keyState > 0 ? keyState >> 0x10
: (keyState >> 0x10) & 0x1;
}
private static int Low(int keyState)
{
return keyState & 0xffff;
}
}
}
}
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FFApp
{
class MyClass
{
Action<String> labelSetter;
public MyClass(Action<String> labelSetter)
{
this.labelSetter = labelSetter;
}
public string MyProperty { get; set; }
public void MyMethod(string text)
{
labelSetter(text);
MyProperty = text;
}
}
}
Or is it possible within this code, to get changing values (store in a variable), when pressed W/A/D/S/W+A/W+D etc keys in order to allow building final string? ex: string finalstring = x + y + speed + pressed_key;

Checking and editing a value in isolated storage in windows phone 7

I am trying to check for the word "Alarm" in my isolated storage before saving.
If the word "Alarm" is exist i will change the "Alarm" to "Alarm1" then if "Alarm1" is exist will change to "Alarm2".
How should i go about doing it?
Below is my code but it is not working:
if (labelTextBox.Text == "")
{
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string label in storage.GetFileNames("*"))
{
MessageBox.Show(label);
}
}
}
catch (Exception)
{
}
int i = 0;
i++;
labelTextBox.Text = "Alarm" + i;
alarmLabel = (labelTextBox.Text.ToString()).Replace(" ", "_");
}
You could use the IsolatedStorageSettings.ApplicationSettings, which is more appropriated for object (e.r. string) handling.
I made a small sample which makes use of this class:
using System;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;
namespace SidekickWP7
{
public partial class Page1 : PhoneApplicationPage
{
const string MYALARM = "MyAlarm";
public Page1()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Page1_Loaded);
}
void Page1_Loaded(object sender, RoutedEventArgs e)
{
int intAlarm = 0;
Int32.TryParse(Load(MYALARM).ToString(), out intAlarm);
intAlarm++;
MessageBox.Show(intAlarm.ToString());
Save(MYALARM, intAlarm);
}
private static object Load(string strKey)
{
object objValue;
if (IsolatedStorageSettings.ApplicationSettings.TryGetValue<object>(strKey, out objValue) == false)
{
objValue = String.Empty;
}
return objValue;
}
private static void Save(string strKey, object objValue)
{
IsolatedStorageSettings.ApplicationSettings[strKey] = objValue;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
}
try this:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
int highestNumberFound = -1;
foreach (var fileName in store.GetFileNames())
{
if (fileName.StartsWith("alarm"))
{
if (fileName == "alarm")
{
if (highestNumberFound < 0)
{
highestNumberFound = 0;
}
}
else if (fileName.Length > 5)
{
int numb;
if (int.TryParse(fileName.Substring(5), out numb))
{
if (numb > highestNumberFound)
{
highestNumberFound = numb;
}
}
}
}
}
string toCreate = "alarm";
if (++highestNumberFound > 0)
{
toCreate += highestNumberFound.ToString();
}
store.CreateFile(toCreate);
}
Not pretty but it should work.
I storngly suspect that creating empty files with different names isn't the best way to achieve whatever it is that you're trying to do though.

Categories

Resources