How do I create my own ImageCell in Xamarin? - windows-phone-8.1

What I need:
A DataTemplate of Image, Title, Description.
What I tried:
I tried ImageCell but it's image size cannot be controlled and hence the Image goes out of screen (on Windows Phone 8.1)
I tried creating CustomRenderer, wasn't able to do it for WP8.1 (couldnt extract the UI Controls from DataTemplate in public override Windows.UI.Xaml.DataTemplate GetTemplate(Cell cell)
I created a ViewCell.View, put Image + two Labels in a Grid. BUT again, it doesnt work properly on WP8.1. When I scroll back up, the Text gets cut.
<ViewCell>
<ViewCell.View>
<StackLayout Padding="20,10,20,10">
<Grid ColumnSpacing="10" RowSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
</Grid.RowDefinitions>
<Label Text="{Binding Title}"
Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" FontSize="Medium"
XAlign="Start" HorizontalOptions="StartAndExpand" YAlign="Start" LineBreakMode="CharacterWrap" MinimumHeightRequest="60"
FontAttributes="Bold"
TextColor="Black">
</Label>
<Image Source="{Binding Image}"
Grid.Row="1" Grid.RowSpan="2" Grid.Column="0"
Aspect="AspectFill" HorizontalOptions="Start">
</Image>
<Label Text="{Binding Description}"
Grid.Row="1" Grid.RowSpan="2" Grid.Column="1"
FontSize="14" XAlign="Start" HorizontalOptions="StartAndExpand" YAlign="Start" LineBreakMode="CharacterWrap"
TextColor="Black">
</Label>
</Grid>
</StackLayout>
</ViewCell.View>
</ViewCell>
So, how do I create my own Cell or Control more attributes of ImageCell

This is a code that I once wrote to make a custom ViewCell, it has a label and an image, hope this helps you (I tested this on iOS, Android and WP):
public class ViewCellExtend : ViewCell
{
Label menuText;
Image menuImagen;
public ViewCellExtend()
{
menuText = new Label();
menuImagen = new Image()
{
Aspect = Aspect.AspectFit,
HeightRequest = 30,
WidthRequest = 30
};
StackLayout stContenedor = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Spacing = 20,
Children =
{
CreateCellBlock()
}
};
View = stContenedor;
}
Xamarin.Forms.Layout CreateCellBlock()
{
StackLayout st2 = new StackLayout
{
Orientation = StackOrientation.Horizontal,
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
new StackLayout
{
Padding = new Thickness(15,0,10,0),
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
Children =
{
menuImagen
}
},
new StackLayout
{
Padding = new Thickness(0,5,10,0),
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
Children =
{
menuText
}
}
}
};
st2.SetBinding(Layout.BackgroundColorProperty, new Binding("BackgroundColor"));
return st2;
}
public static BindableProperty BindableTextProperty = BindableProperty.Create<ViewCellExtend, string>(ctrl =>
ctrl.TextProperty,
defaultValue: string.Empty,
defaultBindingMode: BindingMode.TwoWay,
propertyChanging: (bindable, oldValue, newValue) =>
{
var ctrl = (ViewCellExtend)bindable;
ctrl.TextProperty = newValue;
});
public string TextProperty
{
get { return (string)GetValue(BindableTextProperty); }
set
{
SetValue(BindableTextProperty, value);
menuText.Text = value;
}
}
public static BindableProperty BindableImageProperty = BindableProperty.Create<ViewCellExtend, ImageSource>(ctrl =>
ctrl.ImageProperty,
defaultValue: default(ImageSource),
defaultBindingMode: BindingMode.Default,
propertyChanging: (bindable, oldValue, newValue) =>
{
var ctrl = (ViewCellExtend)bindable;
ctrl.ImageProperty = newValue;
}
);
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
System.Diagnostics.Debug.WriteLine(BindingContext.ToString());
}
public ImageSource ImageProperty
{
get { return (ImageSource)GetValue(BindableImageProperty); }
set
{
SetValue(BindableImageProperty, value);
menuImagen.Source = value;
}
}
}

Here's a very good demonstration of using custom ViewCellRenderer:
https://github.com/xamarin/xamarin-forms-samples/tree/master/WorkingWithListviewNative
Android:
public class NativeAndroidCellRenderer : ViewCellRenderer
{
protected override Android.Views.View GetCellCore (Xamarin.Forms.Cell item, Android.Views.View convertView, Android.Views.ViewGroup parent, Android.Content.Context context)
{
var x = (NativeCell)item;
var view = convertView;
if (view == null) {// no view to re-use, create new
view = (context as Activity).LayoutInflater.Inflate (Resource.Layout.NativeAndroidCell, null);
} else { // re-use, clear image
// doesn't seem to help
//view.FindViewById<ImageView> (Resource.Id.Image).Drawable.Dispose ();
}
view.FindViewById<TextView>(Resource.Id.Text1).Text = x.Name;
view.FindViewById<TextView>(Resource.Id.Text2).Text = x.Category;
// grab the old image and dispose of it
// TODO: optimize if the image is the *same* and we want to just keep it
if (view.FindViewById<ImageView> (Resource.Id.Image).Drawable != null) {
using (var image = view.FindViewById<ImageView> (Resource.Id.Image).Drawable as BitmapDrawable) {
if (image != null) {
if (image.Bitmap != null) {
//image.Bitmap.Recycle ();
image.Bitmap.Dispose ();
}
}
}
}
// If a new image is required, display it
if (!String.IsNullOrWhiteSpace (x.ImageFilename)) {
context.Resources.GetBitmapAsync (x.ImageFilename).ContinueWith ((t) => {
var bitmap = t.Result;
if (bitmap != null) {
view.FindViewById<ImageView> (Resource.Id.Image).SetImageBitmap (bitmap);
bitmap.Dispose ();
}
}, TaskScheduler.FromCurrentSynchronizationContext() );
} else {
// clear the image
view.FindViewById<ImageView> (Resource.Id.Image).SetImageBitmap (null);
}
return view;
}
}
iOS:
public class NativeiOSCellRenderer : ViewCellRenderer
{
static NSString rid = new NSString("NativeCell");
public override UIKit.UITableViewCell GetCell (Xamarin.Forms.Cell item, UIKit.UITableViewCell reusableCell, UIKit.UITableView tv)
{
var x = (NativeCell)item;
Console.WriteLine (x);
NativeiOSCell c = reusableCell as NativeiOSCell;
if (c == null) {
c = new NativeiOSCell (rid);
}
UIImage i = null;
if (!String.IsNullOrWhiteSpace (x.ImageFilename)) {
i = UIImage.FromFile ("Images/" + x.ImageFilename + ".jpg");
}
c.UpdateCell (x.Name, x.Category, i);
return c;
}
}
public class NativeiOSCell : UITableViewCell {
UILabel headingLabel, subheadingLabel;
UIImageView imageView;
public NativeiOSCell (NSString cellId) : base (UITableViewCellStyle.Default, cellId)
{
SelectionStyle = UITableViewCellSelectionStyle.Gray;
ContentView.BackgroundColor = UIColor.FromRGB (255,255,224);
imageView = new UIImageView();
headingLabel = new UILabel () {
Font = UIFont.FromName("Cochin-BoldItalic", 22f),
TextColor = UIColor.FromRGB (127, 51, 0),
BackgroundColor = UIColor.Clear
};
subheadingLabel = new UILabel () {
Font = UIFont.FromName("AmericanTypewriter", 12f),
TextColor = UIColor.FromRGB (38, 127, 0),
TextAlignment = UITextAlignment.Center,
BackgroundColor = UIColor.Clear
};
ContentView.Add (headingLabel);
ContentView.Add (subheadingLabel);
ContentView.Add (imageView);
}
public void UpdateCell (string caption, string subtitle, UIImage image)
{
imageView.Image = image;
headingLabel.Text = caption;
subheadingLabel.Text = subtitle;
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
imageView.Frame = new CoreGraphics.CGRect(ContentView.Bounds.Width - 63, 5, 33, 33);
headingLabel.Frame = new CoreGraphics.CGRect(5, 4, ContentView.Bounds.Width - 63, 25);
subheadingLabel.Frame = new CoreGraphics.CGRect(100, 18, 100, 20);
}
}

Related

How to create notification badge in tableview

How to make a notification badge on the table view?
If there is new data it will display the badge on the table view, and if there is new data again, the badge will automatically be added.
I can strongly recommend you use the following Framework: swift-badge
use_frameworks!
target 'Your target name'
pod 'BadgeSwift', '~> 4.0'
Easy to use:
let badge = BadgeSwift()
view.addSubview(badge)
// Position the badge ...
Customization:
// Text
badge.text = "2"
// Insets
badge.insets = CGSize(width: 12, height: 12)
// Font
badge.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
// Text color
badge.textColor = UIColor.yellow
// Badge color
badge.badgeColor = UIColor.black
// Shadow
badge.shadowOpacityBadge = 0.5
badge.shadowOffsetBadge = CGSize(width: 0, height: 0)
badge.shadowRadiusBadge = 1.0
badge.shadowColorBadge = UIColor.black
// No shadow
badge.shadowOpacityBadge = 0
// Border width and color
badge.borderWidth = 5.0
badge.borderColor = UIColor.magenta
// Customize the badge corner radius.
// -1 if unspecified. When unspecified, the corner is fully rounded. Default: -1.
badge.cornerRadius = 10
Also. If you don't want to use pods, here is the full and ready to use class It also includes functions I have created:
import UIKit
/**
Badge view control for iOS and tvOS.
Project home: https://github.com/marketplacer/swift-badge
*/
#IBDesignable public class BadgeSwift: UILabel {
/// Background color of the badge
#IBInspectable public var badgeColor = Colors.red {
didSet {
setNeedsDisplay()
}
}
/// Width of the badge border
#IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
/// Color of the bardge border
#IBInspectable public var borderColor = Colors.white {
didSet {
invalidateIntrinsicContentSize()
}
}
/// Badge insets that describe the margin between text and the edge of the badge.
#IBInspectable public var insets: CGSize = CGSize(width: 5, height: 2) {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: Badge shadow
// --------------------------
/// Opacity of the badge shadow
#IBInspectable public var shadowOpacityBadge: CGFloat = 0.5 {
didSet {
layer.shadowOpacity = Float(shadowOpacityBadge)
setNeedsDisplay()
}
}
/// Size of the badge shadow
#IBInspectable public var shadowRadiusBadge: CGFloat = 0.5 {
didSet {
layer.shadowRadius = shadowRadiusBadge
setNeedsDisplay()
}
}
/// Color of the badge shadow
#IBInspectable public var shadowColorBadge = Colors.black {
didSet {
layer.shadowColor = shadowColorBadge.cgColor
setNeedsDisplay()
}
}
/// Offset of the badge shadow
#IBInspectable public var shadowOffsetBadge: CGSize = CGSize(width: 0, height: 0) {
didSet {
layer.shadowOffset = shadowOffsetBadge
setNeedsDisplay()
}
}
/// Initialize the badge view
convenience public init() {
self.init(frame: CGRect())
}
/// Initialize the badge view
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
/// Initialize the badge view
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/// Add custom insets around the text
override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
var insetsWithBorder = actualInsetsWithBorder()
let rectWithDefaultInsets = rect.insetBy(dx: -insetsWithBorder.width, dy: -insetsWithBorder.height)
// If width is less than height
// Adjust the width insets to make it look round
if rectWithDefaultInsets.width < rectWithDefaultInsets.height {
insetsWithBorder.width = (rectWithDefaultInsets.height - rect.width) / 2
}
let result = rect.insetBy(dx: -insetsWithBorder.width, dy: -insetsWithBorder.height)
return result
}
/// Draws the label with insets
override public func drawText(in rect: CGRect) {
layer.cornerRadius = rect.height / 2
let insetsWithBorder = actualInsetsWithBorder()
let insets = UIEdgeInsets(
top: insetsWithBorder.height,
left: insetsWithBorder.width,
bottom: insetsWithBorder.height,
right: insetsWithBorder.width)
let rectWithoutInsets = UIEdgeInsetsInsetRect(rect, insets)
super.drawText(in: rectWithoutInsets)
}
/// Draw the background of the badge
override public func draw(_ rect: CGRect) {
let rectInset = rect.insetBy(dx: borderWidth/2, dy: borderWidth/2)
let path = UIBezierPath(roundedRect: rectInset, cornerRadius: rect.height/2)
badgeColor.setFill()
path.fill()
if borderWidth > 0 {
borderColor.setStroke()
path.lineWidth = borderWidth
path.stroke()
}
super.draw(rect)
}
private func setup() {
textAlignment = NSTextAlignment.center
clipsToBounds = false // Allows shadow to spread beyond the bounds of the badge
}
/// Size of the insets plus the border
private func actualInsetsWithBorder() -> CGSize {
return CGSize(
width: insets.width + borderWidth,
height: insets.height + borderWidth
)
}
/// Draw the stars in interface builder
#available(iOS 8.0, *)
override public func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
setNeedsDisplay()
}
}
func createBadge(_ who: BadgeSwift, _ view: UIView, _ value: String) {
if !view.subviews.contains(who) {
view.addSubview(who)
}
configureBadge(who, view, value)
positionBadge(who, view)
}
func removeBadge(_ who: BadgeSwift, _ view: UIView) {
if view.subviews.contains(who) {
who.removeFromSuperview()
}
}
func configureBadge(_ badge: BadgeSwift, _ view: UIView, _ value: String) {
badge.text = value
badge.insets = CGSize(width: 2, height: 2)
badge.font = UIFont.boldSystemFont(ofSize: 12)
badge.textColor = Colors.white
badge.badgeColor = Colors.badgeRed
}
func positionBadge(_ badge: UIView, _ view: UIView) {
badge.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(
item: badge,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.top,
multiplier: 1, constant: 5)
)
constraints.append(NSLayoutConstraint(
item: badge,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.right,
multiplier: 1, constant: -5)
)
view.addConstraints(constraints)
}
func calculateCount(_ items: [UITabBarItem]) -> String {
var countInt = 0
for i in items {
if let countString = i.badgeValue {
countInt = countInt + Int(countString)!
}
}
return String(countInt)
}
For your purpose to create a Badge inside a UITableViewCell, you could use:
let badge = BadgeSwift()
createBadge(badge, MyCell, "10")
That would give you a Badge of 10.

Windows Phone 8 Can't Update listbox item in XML file after using hardware back button?

Hi All i have a list box and i am saving list box selected item in XML file thats working fine but the problem is that when i will close my app and reopen and add more value to list box my previous value is removed form the xml file and listbox also how i can save my current added value and previous value in xml file i am using following code :
and iam using following code
<Grid x:Name="ContentPanel" Grid.Row="2" Margin="15,10,15,0">
<ListBox Name="list_location" Tap="list_location_Tap" Foreground="Black">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="item_name" Text="{Binding description, Mode=OneWay}" Padding="5,15,5,15" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Name="list_locationAdd" Background="Red" Foreground="Black" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="item_name" Text="{Binding description, Mode=OneWay}" Padding="5,15,5,15" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeLarge}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
and my back end code is follow:
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = ISF.OpenFile(filename, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
serializer.Serialize(xmlWriter, data);
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
try
{
if (list_locationAdd != null)
{
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream str = ISF.OpenFile(filename, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
ObservableCollection<Prediction> data = (ObservableCollection<Prediction>)serializer.Deserialize(str);
if (list_locationAdd != null)
{
this.list_locationAdd.ItemsSource = data;
list_locationAdd.Visibility = Visibility.Visible;
}
}
}
}
}
catch (Exception ex)
{
}
}
Change in your code as per below :
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = ISF.OpenFile(filename, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
serializer.Serialize(xmlWriter, data);
}
}
Update in your current code :
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
if (isoStore.FileExists(filename))
{
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore))
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Prediction>));
ObservableCollection<Prediction> data = (ObservableCollection<Prediction>)serializer.Deserialize(isoStream);
this.list_locationAdd.ItemsSource = data;
}
}
catch(Exception ex)
{ }
}
else
{
try
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore))
{
XmlSerializer Serialize = new XmlSerializer(typeof(ObservableCollection<Prediction>));
using (XmlWriter writer = XmlWriter.Create(isoStream, x_W_Settings))
{
data.Add(new Prediction() { description = App.professionalId });
list_locationAdd.ItemsSource = data;
Serialize.Serialize(writer, data);
}
}
}
catch (Exception ex)
{ }
}
Hope this is helpful to you.

Autosuggestbox not displaying results WP8.1 Universal App

Results template in autosuggestbox are not showing and I don't know why. I'm using MVVM Light in the app. Let's go with the code :)
In the page:
<AutoSuggestBox x:Name="txtBusqueda" x:Uid="txtBusqueda"
ItemsSource="{Binding Lugares}"
Grid.Row="1" Margin="24 24 24 12"
MaxSuggestionListHeight="4" AutoMaximizeSuggestionArea="True"
TextMemberPath="Nombre"
>
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="TextChanged">
<core:InvokeCommandAction Command="{Binding ChangeTextCommand}" CommandParameter="{Binding Text, ElementName=txtBusqueda}" />
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
<AutoSuggestBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Nombre}" TextWrapping="Wrap" />
</DataTemplate>
</AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>
In the VM:
private List<LugarInfo> lugares;
public List<LugarInfo> Lugares
{
get { return this.lugares; }
set
{
if (this.lugares == value) return;
this.lugares = value;
RaisePropertyChanged(() => Lugares);
}
}
public RelayCommand<string> ChangeTextCommand { get; set; }
this.ChangeTextCommand = new RelayCommand<string>(async (s) =>
{
var result = await Api.GetInfoLugares(texto);
List<LugarInfo> lugares = new List<LugarInfo>();
foreach (var lugar in result)
{
lugares.Add(new LugarInfo()
{
Id = int.Parse(lugar.Id),
Tipo = lugar.Tipo,
Nombre = lugar.Nombre
});
}
this.Lugares = lugares;
});
So, as you can see, not too much trouble.
The results are returned and assigned to the property:
The problem is results are not displayed in control as you can see in the image.
Help will be appreciated.
your Lugares property will never raise RaisePropertyChanged because in your code you are adding your objects in lugares and than assigning it to This.Lugares which in setter is same so it will not raise the property change and and UI is not updated. change your code to as follows.
var myLugares = new List<LugarInfo>();
foreach (var lugar in result)
{
myLugares.Add(new LugarInfo()
{
Id = int.Parse(lugar.Id),
Tipo = lugar.Tipo,
Nombre = lugar.Nombre
});
}
this.Lugares = myLugares;

Barcode Scanning for windows phone 8.1 store apps using Zxing is not working every time

I tried with static image and it works fine but when i use camera the barcodeReader.Decode returns null most of the time and only few times i am getting result. I have tried with FocusSettings as well but same issue.
Xaml code:
<Grid>
<Canvas Margin="0"
Height="400"
Width="600"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<CaptureElement x:Name="VideoCapture" Stretch="UniformToFill" />
<Image x:Name="CaptureImage" Width="480" Height="640" Visibility="Collapsed" />
</Canvas>
<TextBlock x:Name="Error" VerticalAlignment="Bottom" FontSize="32" Width="480" TextAlignment="Center" Margin="0,400,0,37" />
<TextBlock x:Name="ScanResult" VerticalAlignment="Bottom" TextAlignment="Center" FontSize="32" Width="480"/>
</Grid>
CS.code
private readonly MediaCapture _mediaCapture = new MediaCapture();
private Result _result;
private bool _navBack;
public Scan1xaml()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
InitCameraPreviewAction();
//await DecodeStaticResource();
//return;
}
private async void InitCameraPreviewAction()
{
#if _TestCatpureImage_
await DecodeStaticResource();
return;
#endif
var canUseCamera = true;
try
{
var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (cameras.Count < 1)
{
Error.Text = "No camera found, decoding static image";
await DecodeStaticResource();
return;
}
MediaCaptureInitializationSettings settings;
if (cameras.Count == 1)
{
settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id }; // 0 => front, 1 => back
}
else
{
settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[1].Id }; // 0 => front, 1 => back
}
await _mediaCapture.InitializeAsync(settings);
FocusSettings focusSetting = new FocusSettings()
{
Mode = FocusMode.Continuous,
AutoFocusRange = AutoFocusRange.Normal,
DisableDriverFallback = false,
WaitForFocus = true
};
_mediaCapture.VideoDeviceController.FocusControl.Configure(focusSetting);
await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
SetResolution();
VideoCapture.Source = _mediaCapture;
try
{
//should update CurrentOrientation
_mediaCapture.SetPreviewRotation(VideoRotationLookup(DisplayProperties.CurrentOrientation, false));
//set flash close
_mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
}
catch (Exception e)
{
App.WpLog(e);
}
await _mediaCapture.StartPreviewAsync();
var count = 0;
while (_result == null && !_navBack)
{
count++;
App.WpLog(count);
var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName);
await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);
var stream = await photoStorageFile.OpenReadAsync();
// initialize with 1,1 to get the current size of the image
var writeableBmp = new WriteableBitmap(1, 1);
writeableBmp.SetSource(stream);
// and create it again because otherwise the WB isn't fully initialized and decoding
// results in a IndexOutOfRange
writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
stream.Seek(0);
writeableBmp.SetSource(stream);
_result = ScanBitmap(writeableBmp);
await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
await _mediaCapture.StopPreviewAsync();
VideoCapture.Visibility = Visibility.Collapsed;
CaptureImage.Visibility = Visibility.Visible;
ScanResult.Text = _result.Text;
}
catch (Exception ex)
{
Error.Text = ex.Message;
App.WpLog("use camera fail: " + ex);
canUseCamera = false;
}
if (canUseCamera || _navBack) return;
//tips error
}
private async System.Threading.Tasks.Task DecodeStaticResource()
{
#if _TestCatpureImage_
var file = await KnownFolders.PicturesLibrary.GetFileAsync("scan_test.jpg");
var image = new BitmapImage();
image.SetSource(await file.OpenAsync(FileAccessMode.Read));
CaptureImage.Source = image;
CaptureImage.Visibility = Visibility.Visible;
return;
#else
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"Assets\bar.png");
//var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"Assets\TestZXing.png");
var stream = await file.OpenReadAsync();
// initialize with 1,1 to get the current size of the image
var writeableBmp = new WriteableBitmap(1, 1);
writeableBmp.SetSource(stream);
// and create it again because otherwise the WB isn't fully initialized and decoding
// results in a IndexOutOfRange
writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
stream.Seek(0);
writeableBmp.SetSource(stream);
CaptureImage.Source = writeableBmp;
VideoCapture.Visibility = Visibility.Collapsed;
CaptureImage.Visibility = Visibility.Visible;
_result = ScanBitmap(writeableBmp);
if (_result != null)
{
ScanResult.Text += _result.Text;
}
return;
#endif
}
private Result ScanBitmap(WriteableBitmap writeableBmp)
{
try
{
var barcodeReader = new BarcodeReader
{
TryHarder = true,
AutoRotate = true
};
var result = barcodeReader.Decode(writeableBmp);
if (result != null)
{
CaptureImage.Source = writeableBmp;
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
private Windows.Media.Capture.VideoRotation VideoRotationLookup(
Windows.Graphics.Display.DisplayOrientations displayOrientation,
bool counterclockwise)
{
switch (displayOrientation)
{
case Windows.Graphics.Display.DisplayOrientations.Landscape:
return Windows.Media.Capture.VideoRotation.None;
case Windows.Graphics.Display.DisplayOrientations.Portrait:
return (counterclockwise) ? Windows.Media.Capture.VideoRotation.Clockwise270Degrees :
Windows.Media.Capture.VideoRotation.Clockwise90Degrees;
case Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped:
return Windows.Media.Capture.VideoRotation.Clockwise180Degrees;
case Windows.Graphics.Display.DisplayOrientations.PortraitFlipped:
return (counterclockwise) ? Windows.Media.Capture.VideoRotation.Clockwise90Degrees :
Windows.Media.Capture.VideoRotation.Clockwise270Degrees;
default:
return Windows.Media.Capture.VideoRotation.None;
}
}
//This is how you can set your resolution
public async void SetResolution()
{
System.Collections.Generic.IReadOnlyList<IMediaEncodingProperties> res;
res = this._mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
uint maxResolution = 0;
int indexMaxResolution = 0;
if (res.Count >= 1)
{
for (int i = 0; i < res.Count; i++)
{
var vp = (VideoEncodingProperties)res[i];
App.WpLog(vp.Width + " _ " + vp.Height);
if (vp.Width > maxResolution)
{
indexMaxResolution = i;
maxResolution = vp.Width;
Debug.WriteLine("Resolution: " + vp.Width);
}
}
await this._mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, res[res.Count - 1]);
}
}
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
try
{
_navBack = true;
VideoCapture.Visibility = Visibility.Collapsed;
await _mediaCapture.StopPreviewAsync();
VideoCapture.Source = null;
}
catch (Exception exception)
{
App.WpLog(exception);
}
}

ExtJs Tree Panel not loaded from .NET webservice JSON response

I am making a ExtJS tree panel to load it from JSON response from .NET web service.
it seems I got the correct json response, as when I directly apply the response to store it shows the tree, can any one help me where I am doing wrong.
following is my code:
Ext.onReady(function () {
var mystore = Ext.create('Ext.data.TreeStore',
{
autoLoad: true,
root: {
text: 'Root',
expanded: true//,
//id: 'ID'
},
proxy: {
type: 'ajax',
url: 'FirstService.asmx/GetTreeNodes',
reader:
{
type: 'json'
}
}
});
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 300,
useArrows: true,
rootVisible: false,
store: mystore,
renderTo: 'mydiv'
});
});
My websrevice code is like:
public class TreeNode
{
public int ID { get; set; }
public string text { get; set; }
public bool leaf { get; set; }
public List<TreeNode> children { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
public void GetTreeNodes()
{
List<TreeNode> list = new List<TreeNode>();
for (int i = 1; i <= 4; i++)
{
TreeNode parent = new TreeNode();
parent.ID = i;
parent.text = "Nodes." + i;
parent.leaf = false;
parent.children = new List<TreeNode>();
for (int j = 1; j <= 2; j++)
{
TreeNode child = new TreeNode();
child.ID = i * 10 + j;
child.text = "Nodes." + child.ID;
child.leaf = true;
parent.children.Add(child);
}
list.Add(parent);
}
string jsonResult = new JavaScriptSerializer().Serialize(list.ToList());
//{"success": true,"root":[{"ID":1,"text":"Nodes.1","leaf":false,"children":[{"ID":11,"text":"Nodes.11","leaf":true,"children":null},{"ID":12,"text":"Nodes.12","leaf":true,"children":null}]},{"ID":2,"text":"Nodes.2","leaf":false,"children":[{"ID":21,"text":"Nodes.21","leaf":true,"children":null},{"ID":22,"text":"Nodes.22","leaf":true,"children":null}]},{"ID":3,"text":"Nodes.3","leaf":false,"children":[{"ID":31,"text":"Nodes.31","leaf":true,"children":null},{"ID":32,"text":"Nodes.32","leaf":true,"children":null}]},{"ID":4,"text":"Nodes.4","leaf":false,"children":[{"ID":41,"text":"Nodes.41","leaf":true,"children":null},{"ID":42,"text":"Nodes.42","leaf":true,"children":null}]}]}
//{ root: { expanded: true, children:
jsonResult = "{ root: { expanded: true, children: " + jsonResult + "}}";
System.Web.HttpContext.Current.Response.ContentType = "application/json";
System.Web.HttpContext.Current.Response.Write(jsonResult);
}
Myjson response is like, what i see in FF consol window
{ root: { expanded: true, children: [{"ID":1,"text":"Nodes.1","leaf":false,"children":[{"ID":11,"text":"Nodes.11","leaf":true,"children":null},{"ID":12,"text":"Nodes.12","leaf":true,"children":null}]},{"ID":2,"text":"Nodes.2","leaf":false,"children":[{"ID":21,"text":"Nodes.21","leaf":true,"children":null},{"ID":22,"text":"Nodes.22","leaf":true,"children":null}]},{"ID":3,"text":"Nodes.3","leaf":false,"children":[{"ID":31,"text":"Nodes.31","leaf":true,"children":null},{"ID":32,"text":"Nodes.32","leaf":true,"children":null}]},{"ID":4,"text":"Nodes.4","leaf":false,"children":[{"ID":41,"text":"Nodes.41","leaf":true,"children":null},{"ID":42,"text":"Nodes.42","leaf":true,"children":null}]}]}}
if I directly use this response in Store it loads the tree, please kindly help me here. thanks