error creating tile for microsoft-band - microsoft-band

I have been getting errors when trying to create a tile on my band. I can't seem to get through it. Here is the error:
namespace Band_Test_3
{
#if !DISABLE_XAML_GENERATED_MAIN
public static class Program
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
static void Main(string[] args)
{
global::Windows.UI.Xaml.Application.Start((p) => new App());
}
}
#endif
partial class App : global::Windows.UI.Xaml.Application
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
private bool _contentLoaded;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
#if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
DebugSettings.BindingFailed += (sender, args) =>
{
global::System.Diagnostics.Debug.WriteLine(args.Message);
};
#endif
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
}
}
Using this code. The error is happening on the andClient.TileManager.AddTileAsync(tile) line:
private async void btnCreateTile_Click(object sender, RoutedEventArgs e)
{
txbMessage.Text = "";
// create a new Guid for the tile
// create a new tile with a new Guid
BandTile tile = new BandTile(tileGuid)
{
// enable badging (the count of unread messages)
IsBadgingEnabled = true,
// set the name
Name = "Band Test",
// set the icons
SmallIcon = await LoadIcon("ms-appx:///Assets/Certificate-WF Small.png"),
TileIcon = await LoadIcon("ms-appx:///Assets/Certificate-WF.png")
};
await bandClient.TileManager.AddTileAsync(tile);
}

The most common errors I have seen for failing to add a tile are:
Duplicate GUID for the tile as one already on the band. If you have installed the sample tiles with the sample apps then make sure you are using a GUID that is different from the sample apps. The best thing here is to generate your own GUID for your tile.
Maximum number of tiles are installed on the band. To check this, the exception should contain the error message, but you can query the number of tiles installed or you can look at the number installed via the Microsoft Health App in the Manage Tiles view (the number of tiles free is listed towards the top).
If those do now help, then please past in the exception you are getting.

Related

C# Console.WriteLine() not working in other thread after setting Console.SetOut()?

I'm working on a Windows Form application and within my Form, I've created a cross-thread safe TextWriter class that I use for Console.SetOut() to display writes to the Console in a RichTextBox, like so:
public class TextboxWriter : TextWriter
{
private RichTextBox box;
public TextboxWriter(RichTextBox b)
{
box = b;
}
public override Encoding Encoding => Encoding.ASCII;
public override void Write(string value)
{
Debug.WriteLine(value);
box.Invoke((MethodInvoker)delegate ()
{
box.Text += "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + value + "\n";
});
}
}
Console.SetOut() is called when the DiscordConsole class is created and loaded, and this is evident when I call Console.WriteLine() in the STAThread, or any other Thread, for example:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
DiscordConsole f = new DiscordConsole();
Thread t = new Thread(Separate);
t.Start();
Application.Run(f);
}
private static void Separate()
{
Thread.Sleep(1000);
Console.Write("Loading...");
// loading functions
Console.Write("Load complete!");
}
Those calls to Console.WriteLine() work fine. However, my loading function also creates multiple threads, yet in those threads, the call to Console.WriteLine() does not produce anything on the TextBox? Here's how I'm creating threads and starting them.
public static void LoadRegistry(bool downloadAgain)
{
List <Thread> threads = new List<Thread>();
string[] files = Directory.GetFiles(DataPath, "*.json");
float groupamountload = files.Length / (float)Groups;
for (int i = 0; i < Groups; i++)
{
int tmp = i;
Thread t = new Thread(() =>
{
Console.WriteLine("loading");
Debug.WriteLine("loading");
// loading code
});
threads.Add(t);
}
Application.ApplicationExit += delegate (object info, EventArgs e)
{
threads.ForEach(t => t.Abort());
};
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
}
To verify that my threads are running and loading my files, I placed the Debug.WriteLine() AND Console.WriteLine() statements in the threads. I see the Debug.WriteLine() text outputted to Visual Studio, but the RichTextBox is not updated with my Console.WriteLine(). Does anyone know what I'm doing wrong here?
SOLVED
The issue was almost unnoticeable, but I discovered why it wasn't working. My TextboxWriter class would only override the Write() function, but not the WriteLine() function. Adding an override to WriteLine(string) made it work!
I'm not sure why for some calls to Console.WriteLine() would work, and others would not but now they all work.

How do you hand over files to the user?

in a #WASM / #UNO-platform project, how do you hand over files to the user?
In my case I’m generation locally a PDF and had to download it or display it in the browser.
Any clue?
Regards,
Michael
There's no API to do that directly, yet. But you can create a data: url on an anchor (a) HTML element.
For this you'll need to create some JavaScript. Here's how you can do it:
IMPORTANT: following code will only work with very recent version of Uno.UI. Version starting with v3.0.0-dev.949+
Create a ContentControl for the <a> tag
[HtmlElement("a")]
public partial class WasmDownload : ContentControl
{
public static readonly DependencyProperty MimeTypeProperty = DependencyProperty.Register(
"MimeType", typeof(string), typeof(WasmDownload), new PropertyMetadata("application/octet-stream", OnChanged));
public string MimeType
{
get => (string) GetValue(MimeTypeProperty);
set => SetValue(MimeTypeProperty, value);
}
public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register(
"FileName", typeof(string), typeof(WasmDownload), new PropertyMetadata("filename.bin", OnChanged));
public string FileName
{
get => (string) GetValue(FileNameProperty);
set => SetValue(FileNameProperty, value);
}
private Memory<byte> _content;
public void SetContent(Memory<byte> content)
{
_content = content;
Update();
}
private static void OnChanged(DependencyObject dependencyobject, DependencyPropertyChangedEventArgs args)
{
if (dependencyobject is WasmDownload wd)
{
wd.Update();
}
}
private void Update()
{
if (_content.Length == 0)
{
this.ClearHtmlAttribute("href");
}
else
{
var base64 = Convert.ToBase64String(_content.ToArray());
var dataUrl = $"data:{MimeType};base64,{base64}";
this.SetHtmlAttribute("href", dataUrl);
this.SetHtmlAttribute("download", FileName);
}
}
}
Use it in Your XAML Page
<myControls:WasmDownload FileName="test.txt" x:Name="download">
Click here to download
</myControls:WasmDownload>
Note you can put anything in the content of your control, as any other XAML ContentControl.
Set the File Content in Code Behind
Loaded += (sender, e) =>
{
download.MimeType = "text/plain";
var bytes = Encoding.UTF8.GetBytes("this is the content");
download.SetContent(bytes);
};
Result
Direct support by Uno
There is a PR #3380 to add this feature to Uno natively for all platforms. You can also wait for it instead of doing custom way.
The PR for FileSavePicker has been merged and the feature is now available in package Uno.UI since version 3.0.0-dev.1353.

Uno Platform camera preview control

How can I add an camera preview in a uno XAML Page?
Could be like this example
https://learn.microsoft.com/en-us/windows/uwp/audio-video-camera/simple-camera-preview-access
But the CameraCapture.InitializeAsyn is not implemented on Uno.
When it runs the following exception is thrown:
System.NotImplementedException: The member IAsyncAction
MediaCapture.InitializeAsync() is not implemented in Uno.
If is possible to use native android code, this sample do what I need.
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/android50-camera2basic/
Thanks!
On Android, you have at least two ways for doing something similar:
You can use the following, with native android intents, that you'll need to make conditional with __ANDROID__:
public MainPage()
{
...
BaseActivity.Current.ActivityResult += Current_ActivityResult;
}
private void Current_ActivityResult(object sender, BaseActivity.ActivityResultEventArgs e)
{
if (e.Data != null)
{
var bitmap = (Bitmap)e.Data.Extras.Get("data");
image.Source = bitmap;
}
else
{
image.Source = null;
}
}
public void button_Click(object sender, RoutedEventArgs e)
{
var intent = new Intent(MediaStore.ActionImageCapture);
BaseActivity.Current.StartActivityForResult(intent, 0);
}
or using the CameraCaptureUI class:
{
try
{
var captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);
var photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo == null)
{
return;
}
else
{
var source = new BitmapImage(new Uri(photo.Path));
image.Source = source;
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
You can find the full examples for CameraCaptureUI, and native android.
Other types of camera capture are currently not implemented (as of Uno 3.0), and you'll need to go through native APIs to use them.

Mobile map package returns null for map

I downloaded Arcgis sample mmpk file and even I made a mmpk myself.
In both files I have 1 map(checked by debug) but when I try load the map (with codes in Esri guide page) it returns null for map.
Good to say that I can show online map in my map view and android studio shows no warning or error.
import static n.k.masoud.sbmap.R.id.mapView;
public class ActivityMain extends AppCompatActivity {
private MapView mMapView;
private ArcGISMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(mapView);
code and file from main site
try {File mmpkFile = new File(Environment.getExternalStorageDirectory(),"devlabs-package.mmpk");
String mmpkPath = mmpkFile.getAbsolutePath();
final MobileMapPackage mobileMapPackage=new MobileMapPackage(mmpkPath);
mobileMapPackage.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
this if gets false
if (mobileMapPackage.getLoadStatus() == LoadStatus.LOADED) {
showMessage(String.format("Number of maps = %d", mobileMapPackage.getMaps().size()));
map = mobileMapPackage.getMaps().get(0);
} else {
dealWithLoadFailure();
}
}
});
mobileMapPackage.loadAsync();
}
catch (Exception err){
Log.e("TAG", "onCreate: "+err);
}
map.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
if (map.getLoadStatus() == LoadStatus.LOADED) {
Log.e("TAG", "run: map loaded ok" );
// Once map is loaded, can check its properties and content
if (map.getBookmarks().size() > 0) {
}
} else {
dealWithLoadFailure();
}
}
});
map.loadAsync();
As I told part below works correctly
// for online maps
// ArcGISMap map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 29.453826, 60.852134,12);
mMapView.setMap(map);
mMapView.addLayerViewStateChangedListener(new LayerViewStateChangedListener() {
#Override
public void layerViewStateChanged(LayerViewStateChangedEvent layerViewStateChangedEvent) {
// Each layer may have more than one layer view state.
StringBuilder layerStatuses = new StringBuilder();
for (LayerViewStatus status : layerViewStateChangedEvent.getLayerViewStatus()) {
if (layerStatuses.length() > 0) {
layerStatuses.append(",");
} layerStatuses.append(status.name());
}
showMessage(String.format("Layer '%s' status=%s", layerViewStateChangedEvent.getLayer().getName(), layerStatuses.toString()));
} });
}
#Override
protected void onPause(){
mMapView.pause();
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
mMapView.resume();
}
}
if the line
if (mobileMapPackage.getLoadStatus() == LoadStatus.LOADED)
is returning false, then the mobile map package is not loaded and won't contain any maps.
In your dealWithLoadFailure() function you can retrieve the load error:
mobileMapPackage.getLoadError()
and see what it is. It should tell you what the error causing the load failure is.
One of my friends tried this way but didn't got any result just like me.
So he changed the official guide code to this and got well response.
I think he got code from Internet , so I don't know about it's copyright permission.
private void setupMobileMap() {
if (mMapView != null) {
File mmpkFile = new File(Environment.getExternalStorageDirectory(), "devlabs-package.mmpk");
final MobileMapPackage mapPackage = new MobileMapPackage(mmpkFile.getAbsolutePath());
mapPackage.addDoneLoadingListener(new Runnable() {
#Override
public void run() {
// Verify the file loaded and there is at least one map
if (mapPackage.getLoadStatus() == LoadStatus.LOADED && mapPackage.getMaps().size() > 0) {
mMapView.setMap(mapPackage.getMaps().get(0));
} else {
// Error if the mobile map package fails to load or there are no maps included in the package
//setupMap();
//Log for Error
}
}
});
mapPackage.loadAsync();
}
}

Xamarin.Forms and Plugin.Media: after about 20 photos something crashes

I have a problem with Xamarin.Forms ver. 2.3.4.224 and Plugin.Media ver. 2.6.2. The problem occurs after taking about 20 photos (depends from the device): basically the app crashes without any apparently reason.
If you want to replicate the error, I created a test project for you on GitHub. With my iPad Air or iPad Pro after about 30 photos (video iPad Air - iPad Pro). All devices are iOS ver. 10.3.1 and they have enough space to storage photos.
The app is very simple: you have two buttons one for taking a picture and the other one to pick a photo. If you take photos one after another, after about 20 (32 in an iPad Air) the app crashes. I'm just take photos with the Plugin.Media nothing more.
Any ideas are welcome.
Update
In my project I had a reference to Refractored.MvvmHelpers and I noticed if I remove it, I can take more pictures. I created my BaseViewModel with INotifyPropertyChanged and I noticed I can take more photos.
I created then a new project (you can find it on GitHub under cameratesteasy) without MVVM and there is just the code to take a photo like:
public partial class cameratesteasyPage : ContentPage
{
int count = 0;
public cameratesteasyPage()
{
InitializeComponent();
CrossMedia.Current.Initialize();
}
void UpdateCount()
{
count++;
CountLabel.Text = $"{count} times";
}
async void StartCameraTapped(object sender, System.EventArgs args)
{
using (var file = await CrossMedia.Current.TakePhotoAsync(
new StoreCameraMediaOptions {}))
{
if (file == null)
return;
UpdateCount();
}
}
async void StartCameraTakeTapped(object sender, System.EventArgs args)
{
var file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
return;
UpdateCount();
}
}
In this case the app shut down after 52 photos. I saved the log for Xcode and you can see it here.
I used Xamarin Profile and the memory level is always low. After about 30 photos, an error occurs in Xamarin Profiler
Finally I could create a Xamarin Profiler file
Also I noticed this kind of error occurs on iPads. The same app in an iPhone is working fine (apparently) or I didn't find up to now the number of photos before crashing.
Update /2
I decided to implement a native function for taking photo.
Interface
public interface ICamera
{
void TakePicture();
}
Implementation
using System;
using cameratest.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(Camera_iOS))]
namespace cameratest.iOS
{
public class Camera_iOS : ICamera
{
static UIImagePickerController picker;
static Action<NSDictionary> _callback;
static void Init()
{
if (picker != null)
return;
picker = new UIImagePickerController();
picker.Delegate = new CameraDelegate();
}
class CameraDelegate : UIImagePickerControllerDelegate
{
public override void FinishedPickingMedia(
UIImagePickerController picker, NSDictionary info)
{
var cb = _callback;
_callback = null;
picker.DismissModalViewController(true);
cb(info);
}
}
public static void TakePicture(UIViewController parent,
Action<NSDictionary> callback)
{
Init();
picker.SourceType = UIImagePickerControllerSourceType.Camera;
_callback = callback;
parent.PresentModalViewController(picker, true);
}
public static void SelectPicture(UIViewController parent,
Action<NSDictionary> callback)
{
Init();
picker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
_callback = callback;
parent.PresentModalViewController(picker, true);
}
public void TakePicture()
{
var rc = UIApplication.SharedApplication.KeyWindow.RootViewController;
TakePicture(rc, (obj) =>
{
var photo = obj.ValueForKey(
new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
var documentsDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
// hardcoded filename, overwritten each time
string jpgFilename = System.IO.Path.Combine(documentsDirectory,
"Photo.jpg");
NSData imgData = photo.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " +
jpgFilename + " because" + err.LocalizedDescription);
}
});
}
}
}
With this code after about 30 photos, the app crashes. The only difference is with this code I can receive some alert from ReceiveMemoryWarning. If you have an interest, I updated the code on GitHub.

Resources