how to make DateTime and "SetWallpaperAsync" work together? - c#

I am trying to do a UWP app that changes wallpaper and lockscreen based on the time of the day (as a start). I am facing difficulties implementing this:
I have the task "SetWallpaperAsync" on main page (I am making sure it works before shifting it to a background task) as fallowing:
private async Task<bool> SetWallpaperAsync()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var imageID = DateTime.Now.Hour.ToString("HH");
var uri = new Uri($"ms-appx:///Dynamic/Dynamic-{imageID}.jpg");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file);
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file);
}
return success;
}
But it only worked once then it stopped, which lead me to believe that the imageID string is not returning the correct value (the value is between 00 and 23, corresponding to the hours in a day in a 24 format).
I have also tried to link a textblock to the same value and different formats, but it did not appear on the app homepage. I am not sure at all where its going wrong!
// Time format
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("hour");
DateTime dateToFormat = DateTime.Now;
var mydate = formatter.Format(dateToFormat);
TimeDescriptionTextBlock.Text = mydate.ToString();
// another try with the time
TimeHours.Text = DateTime.Now.ToString("HH:mm:ss");
How can I debug this code and see where its stopping?

If you output the imageID variable in the Output windows using Debug.Writeline:
var imageID = DateTime.Now.Hour.ToString("HH");
Debug.WriteLine(imageID);
You can see that the output is: HH.
The reason for this is that the format string HH works on DateTime variables, but you are actually calling it on the Hour variable only, which is just a number.
There are two possible solutions:
Remove the .Hour from the call: var imageID = DateTime.Now.ToString("HH");
Just use the Hour as a number: var imageID = DateTime.Now.Hour.ToString();
Both solutions are equivalent and will yield a 24-hour format hour number.

Related

Why am I not getting the correct value from my byte [] that is being sent by my BLE-device to my xamarin forms app?

I am sending this from my BLE device:
BTLEserial.print ("one");
BTLEserial.print (",");
BTLEserial.print ("two");
So what I am sending is: "one, two" and i am now trying to get this value but with my current code I get 54 and 44 instead and I do not quite know why.
I use this plugin: https://github.com/xabre/xamarin-bluetooth-le (Plugin.BLE)
This is how I read the data:
var adapter = CrossBluetoothLE.Current.Adapter;
await adapter.ConnectToDeviceAsync(mydevice);
var service = await mydevice.GetServiceAsync(Guid.Parse("6e400001-b5a3-f393-e0a9-e50e24dcca9e"));
var services = await mydevice.GetServicesAsync();
var RXcharacteristics = await service.GetCharacteristicAsync(Guid.Parse("6e400003-b5a3-f393-e0a9-e50e24dcca9e"));
var characteristics = await service.GetCharacteristicsAsync();
int whatResult = 0;
string valueone;
string valuetwo;
RXcharacteristics.ValueUpdated += (sender, e) =>
{
var result = e.Characteristic.Value;
foreach (var items in result)
{
if (whatResult == 0)
{
valueone = Convert.ToString(items);
System.Diagnostics.Debug.Writeline(valueone);
whatResult++;
}
else {
valuetwo = Convert.ToString(items);
System.Diagnostics.Debug.Writeline(valuetwo);
whatResult = 0;
}
}
};
await RXcharacteristics.StartUpdatesAsync();
How come I cannot get the correct data from the result I am receiving? I also tried with var result = e.Characteristic.StringValue; but with the same result.
I googled and came across a person with the same issue:
https://github.com/xabre/xamarin-bluetooth-le/issues/88
He for example said this, which showcase that my device has CanUpdate as true. And as I said above I succesfully get data from my code but I do not get the correct values.
The RXCharacteristic has CanWrite = false, CanRead = false, CanUpdate = true
If I use this app:
https://github.com/adafruit/Bluefruit_LE_Connect_v2
That is open source (coded with swift) I can succesfully get the correct value
The github documentation for this library indicates that the Value is a byte array
public override byte[] Value => _nativeCharacteristic.Value?.ToArray();
Which would mean that instead of using a foreach loop over each byte you should attempt to use a text encoding instead 1
var result = e.Characteristic.Value;
var str = System.Text.Encoding.UTF8.GetString(result,0,result.Length);
1. Andy0708, Fri Jan 06 2017, Oksana, "How convert byte array to string [duplicate]", Jul 25 '12 at 16:39, https://stackoverflow.com/a/11654825/1026459

Same code but getting different result

When I use below code I am getting different result on my developer pc and my remote server.
string _QsDateTime = "12.11.2016 21:30";
var _CountryZone = DateTimeZoneProviders.Tzdb["TUR"];
var _DatePattern = LocalDateTimePattern.CreateWithCurrentCulture("yyyy-MM-dd HH:mm:ss");
var _LocalTime = _DatePattern.Parse(_QsDateTime).Value;
var _LocalTime2TargetZoneTime = _LocalTime.InZoneStrictly(_CountryZone);
var _TargetZone2Utc = _LocalTime2TargetZoneTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc();
_QsDateTime = _TargetZone2Utc.ToString("yyyy-MM-dd HH:mm:ss");
Developer PC result is: "2016-11-12 19:30:00"
Remote server result is: "2016-12-11 19:30:00"
Remote server specs is Windows 2012 server English Developer PC specs is Windows 7 Turkish but both of them regional date time setting are same.
Why I am getting different result?
I'm not too much familiar with Noda Time but I have a few things to say:
DateTimeZoneProviders.Tzdb does not have a time zone identifier as TUR as far as I know, you should use Europe/Istanbul instead.
When you create a LocalDateTimePattern with CreateWithCurrentCulture method, it uses current culture settings and these are different in your both server. Be careful about that.
LocalDateTimePattern.Parse method use the rules of the current pattern. Your string is 12.11.2016 21:30 but your pattern is yyyy-MM-dd HH:mm:ss. You see my point, don't you?
If you really get different results in your servers, you shouldn't blame your last line since both en-US and tr-TR cultures uses GregorianCalendar as a Calendar property and that doesn't effect the result. You might wanna check LocalDateTimePattern.Parse method line instead.
For example;
using System;
using NodaTime;
using NodaTime.Text;
public class Program
{
public static void Main()
{
string _QsDateTime = "12.11.2016 21:30";
var _CountryZone = DateTimeZoneProviders.Tzdb["Europe/Istanbul"];
var _DatePattern = LocalDateTimePattern.CreateWithCurrentCulture("dd.MM.yyyy HH:mm");
var _LocalTime = _DatePattern.Parse(_QsDateTime).Value;
var _LocalTime2TargetZoneTime = _LocalTime.InZoneStrictly(_CountryZone);
var _TargetZone2Utc = _LocalTime2TargetZoneTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc();
_QsDateTime = _TargetZone2Utc.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(_QsDateTime);
}
}
generates
2016-11-12 19:30:00
Here a demonstration.

iCal Time Zone issue

I'm trying to allow a user to download an iCal for their calendar in ASP.Net, but am having a timezone issue.
If I download the file on my computer, the time appears correct and within the correct timeframe. However, when I try to download it on a phone, the timezone switches and it becomes 5 hours behind (aka 7:00 AM becomes 3:00 AM).
Does anyone know how to fix this issue/set the timezone?
Here is the code:
iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();
DateTime dt = (DateTime)Convert.ToDateTime(lblTicketDue.Text);
Console.Write(dt);
evt.Start = new iCalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
evt.End = new iCalDateTime((DateTime)Convert.ToDateTime(lblTicketDue.Text).AddMinutes(15.0));
Alarm alarm = new Alarm();
alarm.Action = AlarmAction.Display;
alarm.Summary = "Ticket due!";
Trigger t = new Trigger();
iCalDateTime icdt = new iCalDateTime(dt.Subtract(TimeSpan.FromMinutes(120.0)));
t.DateTime = icdt;
alarm.Trigger = t;
evt.Alarms.Add(alarm);
iCal.Events.Add(evt);
iCalendarSerializer serializer = new iCalendarSerializer();
string output = serializer.SerializeToString(iCal);
Response.ContentType = "text/calendar";
Response.Write(output);
Response.End();
Hard to tell without looking at the actual iCalendar stream that gets generated but it is quite likely that you are generating your DTSTART/DTEND using floating time (e.g. "20160517T070000" ).
If the event is not recurring (no RRULE), what you want to do is convert your datetime to UTC and use the "date with UTC time" format described in https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5
i.e. something like "20160517Txx0000Z"
If the event is recurring you would then need to use the last form (date with local time and timezone reference).

How to add recurring entry Google Calendar

I would like to add a recurring event with C#. I found on the Web that the following should work. When I run the method to insert the entry, It fails on the
EventEntry insertedEntry = service.Insert(calendarUri, entry); statement !
I get this error :
"Execution of request failed:
https://www.google.com/calendar/feeds/user#gmail.com/private/full?gsessionid=6eGsOTuhQ-YUVWp2BV_25g"
When I remove the recurrence code, everything works fine ! I noticed that this piece of code is pretty old ! How can I simply add a recurring event on Google Calendar with the .NET library ?
EventEntry entry = new EventEntry();
entry.Title.Text = "Hello World !";
// Recurring event:
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010;BYDAY=SU\r\n";
Recurrence recurrence = new Recurrence();
recurrence.Value = recurData;
entry.Recurrence = recurrence;
string htmlDescription = "Woww, really ?";
if (htmlDescription != null && htmlDescription.Length > 0)
{
entry.Content.Type = "html";
entry.Content.Content = htmlDescription;
}
Where eventLocation = new Where();
eventLocation.ValueString = "Somewhere";
entry.Locations.Add(eventLocation);
DateTime start = DateTime.Now;
When eventTime = new When();
eventTime.StartTime = start;
DateTime endTime = DateTime.Now.AddHours(2);
eventTime.EndTime = endTime;
entry.Times.Add(eventTime);
eventTime.AllDay = true;
EventEntry insertedEntry = service.Insert(calendarUri, entry);
Straight from Google (click the .NET example if it doens't come up as a default):Create Recurring Events
Hopefully this will give you some ideas if not out-right answer your question.
Cheers.
Your recurrence string telling it when to end requires a full time entry. You simply said UNTIL=20131010. The question is 20131010 where? We can assume you want midnight, but then... midnight where?
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010T000000-05:00;BYDAY=SU\r\n";
The above change should make your event recur until Midnight US Eastern time on 2013-10-10.

WebClient SendValues() method changes datetime value

I use WebClient class to send a response acknowledge message in an mvc 3 project. Message is sending from one action method on a project to another projects action method.
Surprisingly the date parameter is 3 hours later, on recieving data.
For example if my sending date is receving data is "2012-08-14 13:42:50Z" i see "2012-08-14 16:42:50Z" on the other side.
Here is a simplified code sample of my case;
NameValueCollection ack = new NameValueCollection();
ack.Add("RESID", form.RESPONSE.ID.ToString());
ack.Add("A_DateTime", DateTime.Now.ToString("u")); //2012-08-14 13:42:50Z
using (var client = new WebClient())
{
client.Encoding = System.Text.Encoding.UTF8;
var result = client.UploadValues("http://localhost:11578/HPM/ResponseAck", ack);
}
//HPM Controller:
ResponseAck(HttpPostResponseAckMessage response)
{
//Here response.Date vale is 2012-08-14 16:42:50Z ???
}
It seems to me its about sneaky little serialization monsters changing it cause of some culture specific issue. But i don't know the real cause so the solution.
Edit:
public class HttpPostResponseAckMessage
{
public int RESID { get; set; }
public DateTime A_DateTime { get; set; }
}
You should either change the culture of the current thread or convert and process all dates in a fixed format such as UTC.
You can change the current culture of the thread using the following code:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-EN");
Ok, I think its about expecting mvc model binder to parse a formated datetime.
With the "u" format model binder thinks the datetime is UTC.
So my solution will be changing the type of property A_DateTime to string and will parsing it internaly.
Hope this helps someone else like me.
Thanks all.

Categories