How can I databind an image using XAML?
Specifically, I have a stream object that I would like to convert into an image.
However, I just cannot find a basic example of how to do this.
1. What does the viewmodel property look like?
Do I use an ImageSource?
Do I need a value converter?
2. What does the XAML look like?
Forms has a StreamImageSource you can use to do this. However, I don't think you can use it in XAML without writing a custom converter. To use it in code, you would do something like this:
image1.Source = ImageSource.FromStream(() =>
{
// whatever you need to do to create your stream
return stream;
});
The demo illustrates the binding via code. For a XAML implementation you need something along the lines of:-
<Image Source="{Binding MyImageAsBytes, Converter={StaticResource MyByteToImageSourceConverter}}" />
Once you have your byte[] in your ViewModel, you will need a converter to convert this byte array, that contains the image, to a Xamarin.Forms ImageSource.
The converter, takes the byte[] array and converts to an ImageSource via:-
objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));
Example:-
StackLayout objStackLayout = new StackLayout();
byte[] bytImage = { your image as a byte collection }
this.BindingContext = new MyImageViewModel()
{
MyImageAsBytes = bytImage
};
Image objImage = new Image();
objImage.SetBinding(Image.SourceProperty, "MyImageAsBytes", converter: new MyByteToImageSourceConverter());
objStackLayout.Children.Add(objImage);
ViewModel:-
public class MyImageViewModel
: Xamarin.Forms.View
{
public static readonly BindableProperty MyImageAsBytesProperty = BindableProperty.Create<MyImageViewModel, byte[]>(p => p.MyImageAsBytes, default(byte[]));
public byte[] MyImageAsBytes
{
get { return (byte[])GetValue(MyImageAsBytesProperty); }
set { SetValue(MyImageAsBytesProperty, value); }
}
}
Converter:-
public class MyByteToImageSourceConverter
: IValueConverter
{
public object Convert(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
{
ImageSource objImageSource;
//
if (pobjValue != null)
{
byte[] bytImageData = (byte[])pobjValue;
//
objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));
}
else
{
objImageSource = null;
}
//
return objImageSource;
}
public object ConvertBack(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
{
throw new NotImplementedException();
}
}
Related
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.
Is it possible to ignore ExpandoObject properties, in particular those of Delegate type, when using JsonConvert(expando, formatting, serializerSettings)?
Essentially I'm trying to ignore all parsing of the func property in this example expando object:
//{
// func: () => {}
//}
Action func = () => {};
dynamic expando = new ExpandoObject();
expando.func = func;
// should be empty object {}
string json = JsonConvert(expando, formatting, serializerSettings);
The first thing I tried was overriding the converter. Unfortunately this doesn't work, as I see CanConvert called recursively for Action -> DelegateEntry -> some generic type -> RuntimeMethodInfo.
private class ExpandoObjectIgnoreConverter : ExpandoObjectConverter
{
public override bool CanConvert(Type objectType)
{
if (typeof(Delegate).IsAssignableFrom(objectType))
{
return false;
}
return base.CanConvert(objectType);
}
}
A method that works is using an error handler in serialization settings and a contract resolver. When I throw the error, all further processing of the property is ignored, i.e. Action -> DelegateEntry -> some generic type -> RuntimeMethodInfo. However, I'd like to do this more elegantly than throwing an exception if possible.
Error handler:
serializationSettings.Error = (sender, args) =>
{
if (args.ErrorContext.Error is InvalidCastException)
{
args.ErrorContext.Handled = true;
}
}
Contract resolver:
private class ExpandoObjectContractResolver : DefaultContractResolver
{
public override JsonContract ResolveContract(Type type)
{
if (typeof(Delegate).IsAssignableFrom(type))
{
throw new InvalidCastException();
}
else
{
return base.ResolveContract(type);
}
}
}
I'm using the edge library to script nodejs from within a C# process. I'm trying to remove functions from the returned javascript objects from within C#, as they are assigned a Delegate type that doesn't play nicely with JsonConvert.
ExpandoObjectConverter does not have any custom code to write an ExpandoObject. Instead it overrides JsonConverter.CanWrite to return false thereby allowing the expando to be serialized generically as an IDictionary<string, object>.
Thus you can override CanWrite and WriteJson() yourself to filter undesired key/value pairs before serialization:
public class FilteredExpandoObjectConverter : ExpandoObjectConverter
{
public override bool CanWrite { get { return true; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var expando = (IDictionary<string, object>)value;
var dictionary = expando
.Where(p => !(p.Value is System.Delegate))
.ToDictionary(p => p.Key, p => p.Value);
serializer.Serialize(writer, dictionary);
}
}
Then use the converter in settings as follows:
var formatting = Formatting.Indented;
var serializerSettings = new JsonSerializerSettings
{
Converters = { new FilteredExpandoObjectConverter() },
};
var json = JsonConvert.SerializeObject(expando, formatting, serializerSettings);
Note this will only filter delegates values directly owned by an ExpandoObject. If you have a collection containing some delegates, or delegate-valued members in some POCO, they will not be filtered by this code.
Sample fiddle.
If I have this controller:
public class SomeController : ApiController
{
public SomeInfoDto Get()
{
return new SomeInfoDto();
}
}
When I call /api/Some with a get request I will get JSON in the Content Body because JSON.NET has been kind enough to serialise it for me.
However, if I wanted to send a 500 HTTP code and some JSON I thought I could do this:
public HttpResponseMessage Get()
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = // not sure what to put here
}
}
So I googled to find out what to put for the Content and found this resource
public class JsonContent : HttpContent
{
private readonly JToken _value;
public JsonContent(JToken value)
{
_value = value;
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
protected override Task SerializeToStreamAsync(Stream stream,
TransportContext context)
{
var jw = new JsonTextWriter(new StreamWriter(stream))
{
Formatting = Formatting.Indented
};
_value.WriteTo(jw);
jw.Flush();
return Task.FromResult<object>(null);
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
Which I can easily modify to fit my purposes.
However, my question is, if I get SerializeToStreamAsync to use JsonConvert.SerializeObject(_value) further down the Web Api pipeline will it be serialised again?
I have set the GlobalConfiguration.Configuration like this:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
My Implementation for the SerializeToStreamAsync is this:
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.WriteAsync(JsonConvert.SerializeObject(this.value)).Wait();
streamWriter.FlushAsync().Wait();
}
return Task.FromResult<object>(null);
}
EDIT: Providing a concrete sample with formatter.
If you want to send JSON content with Http Status Code 500, you can use the extension method HttpRequestMessage.CreateResponse. There is no need for any advanced serialization and formatting. More info on that here.
https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.createresponse%28v=vs.118%29.aspx
Request.CreateResponse(HttpStatusCode.InternalServerError, new string[] { "value1", "value2" }, new JsonMediaTypeFormatter())
(Or)
Request.CreateResponse(HttpStatusCode.InternalServerError, new string[] { "value1", "value2" }, 'application/json')
I have a requirement to load images from a folder in the project to a stackpanel. Under each image a name should also be shown. The image folder can change at any time and the number of images can also change.(with a maximum of 50 images) I want to know if I can use data binding to handle this. I thought of having image ID's, their sources and the name for each image in an XML so that I can change that XML file whenever the image folder changes, without changing the rest of the code. Is that feasible? If so how? Can someone please guide me? Thank you in advance.
One solution would be to use a Filepicker to let the user select the images inside the folder, and then bind the selected images to an Itemscontrol. That itemscontrol can then be put inside the Stackpanel. Here's a quick sample using that solution.
Here's the codebehind for picking the image files:
private List<EditableImage> availableImagesList = new List<EditableImage>();
private async void FilePicker_Clicked(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
//TODO: add supported image file types
openPicker.FileTypeFilter.Add("jpg,png,gif");
// We prompt the user to pick one or more files
IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
if (files.Count > 0)
{
availableImages.DataContext = null;
String fp = ""; // The path of the picked image
int index = availableImagesList.Count;
foreach (StorageFile file in files)
{
// Copying the selected image to local app data folder
//TODO: check if the selected file is actually and image
if (file != null )
{
StorageFile fileCopy = await file.CopyAsync(ApplicationData.Current.LocalFolder, file.DisplayName + file.FileType, NameCollisionOption.ReplaceExisting);
fp = fileCopy.Path;
}
//Creating the image
CustomImage picToAdd = new CustomImage(index+1, file.DisplayName, fp);
//Adding the image as an UI element to the app bar
availableImagesList.Add(picToAdd);
}
availableImages.DataContext = availableImagesList;
}
}
The CustomImage model:
public class CustomImage
{
private static Uri _baseUri = new Uri("ms-appx:///");
private int _id;
public int Id
{
get { return _id; }
set
{
this.SetProperty(ref this._id, value);
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
this.SetProperty(ref this._name, value);
}
}
private string _imgPath;
public string ImgPath
{
get { return _imgPath; }
set
{
this.SetProperty(ref this._imgPath, value);
}
}
private String _imagePath = null;
private ImageSource _image = null;
public ImageSource Image
{
get
{
if (this._image == null && this._imagePath != null)
{
this._image = new BitmapImage(new Uri(CustomImage._baseUri, this._imagePath));
}
return this._image;
}
set
{
this._imagePath = null;
this.SetProperty(ref this._image, value);
}
}
public void SetImage(String path)
{
this._image = null;
this._imagePath = path;
this.OnPropertyChanged("Image");
}
public CustomImage(int id, string name, string imagepath)
{
SetImage(imagepath);
_id = id;
_name = name;
}
}
Here's the XAML for the ItemsControl inside the Stackpanel:
<StackPanel x:Name="loadedImages" HorizontalAlignment="Left" Orientation="Horizontal">
<!--Displaying the selected images in stackpanel-->
<ItemsControl ItemsSource="{Binding}" ItemsPanel="{StaticResource LoadedItemsPanel}">
<ItemsControl.ItemTemplate>
<!--The template for each object that is displayed as an UI element-->
<DataTemplate>
<Grid Height="88" Margin="2,0" Width="88" >
<Image Source="{Binding Image}"/>
<TextBlock Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
In your page resources, you must also define:
<ItemsPanelTemplate x:Key="LoadedItemsPanel">
<WrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
I'm looking for the best way to create an RSS feed via MVC4 (and/or WebAPI). This post seemed the most applicable http://www.strathweb.com/2012/04/rss-atom-mediatypeformatter-for-asp-net-webapi/. But it was written in the pre-Release days of WebAPI. I've used Nuget to bring all packages up-to-date but attempting to build the project tosses:
Error 2 The type or namespace name 'FormatterContext' could not be found (are you missing a using directive or an assembly reference?) G:\Code\MvcApplication-atomFormatter\MvcApplication-atomFormatter\SyndicationFeedFormatter.cs 38 129 MvcApplication_syndicationFeedFormatter
I've found a number of articles explaining that the MediaTypeFormatter has changed significantly since beta but I have found details on the adjustments required to the code snippet in question.
Is there an updated resource showing the construction of an RSSFormatter?
thx
Yes I wrote that tutorial against Beta.
Below is the code updated to RTM version.
One advice, if I may, is that this example uses a simple "whitelist" of concrete types for which RSS/Atom feed is build (in this case my Url model). Ideally in more complex scenarios, you'd have the formatter set up against an interface, rather than a concrete type, and have all Models which are supposed to be exposed as RSS to implement that interface.
Hope this helps.
public class SyndicationFeedFormatter : MediaTypeFormatter
{
private readonly string atom = "application/atom+xml";
private readonly string rss = "application/rss+xml";
public SyndicationFeedFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(atom));
SupportedMediaTypes.Add(new MediaTypeHeaderValue(rss));
}
Func<Type, bool> SupportedType = (type) =>
{
if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
return true;
else
return false;
};
public override bool CanReadType(Type type)
{
return SupportedType(type);
}
public override bool CanWriteType(Type type)
{
return SupportedType(type);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
if (type == typeof(Url) || type == typeof(IEnumerable<Url>))
BuildSyndicationFeed(value, writeStream, content.Headers.ContentType.MediaType);
});
}
private void BuildSyndicationFeed(object models, Stream stream, string contenttype)
{
List<SyndicationItem> items = new List<SyndicationItem>();
var feed = new SyndicationFeed()
{
Title = new TextSyndicationContent("My Feed")
};
if (models is IEnumerable<Url>)
{
var enumerator = ((IEnumerable<Url>)models).GetEnumerator();
while (enumerator.MoveNext())
{
items.Add(BuildSyndicationItem(enumerator.Current));
}
}
else
{
items.Add(BuildSyndicationItem((Url)models));
}
feed.Items = items;
using (XmlWriter writer = XmlWriter.Create(stream))
{
if (string.Equals(contenttype, atom))
{
Atom10FeedFormatter atomformatter = new Atom10FeedFormatter(feed);
atomformatter.WriteTo(writer);
}
else
{
Rss20FeedFormatter rssformatter = new Rss20FeedFormatter(feed);
rssformatter.WriteTo(writer);
}
}
}
private SyndicationItem BuildSyndicationItem(Url u)
{
var item = new SyndicationItem()
{
Title = new TextSyndicationContent(u.Title),
BaseUri = new Uri(u.Address),
LastUpdatedTime = u.CreatedAt,
Content = new TextSyndicationContent(u.Description)
};
item.Authors.Add(new SyndicationPerson() { Name = u.CreatedBy });
return item;
}
}