Generate barcode using Zxing in xamarin.forms - xamarin

I am trying to display a barcode in my app using binding in my xaml. My question is how can I convert the barcode to be used in the xaml Image source. I have tried using a byte property but I get this compile error : "Cannot implicitly convert Zxing barcode image view to 'byte'". Any guidance on how to achieve this will be appreciate, thanks.
Cards.cs
public class Cards
{
public int CustomerID { get; set; }
public int DiscountLevelID { get; set; }
public string DiscountLevel { get; set; }
public double DiscountLevelAmount { get; set; }
public bool StoreCustomerGiftCard { get; set; }
public bool StoreCustomerLoyalty { get; set; }
public int LoyaltyLevelID { get; set; }
public string LoyaltyLevel { get; set; }
public double LoyaltyLevelRatio { get; set; }
public double Balance { get; set; }
public int StoreNumber { get; set; }
public string CardNumber { get; set; }
public bool IsError { get; set; }
public object ErrorMessage { get; set; }
public string CompanyName { get; set; }
public string CustomerLogo { get; set; }
public byte BarCode { get; set; }
}
Cards.xaml.cs
ZXingBarcodeImageView barcode;
barcode = new ZXingBarcodeImageView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };
barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE;
barcode.BarcodeOptions.Width = 300;
barcode.BarcodeOptions.Height = 300;
barcode.BarcodeOptions.Margin = 10;
barcode.BarcodeValue = i.CardNumber;
i.BarCode = barcode;
Cards.xaml
<Image Source="{Binding BarCode}" />

ZXingBarcodeImageView inherits directly from Image, so you use it as an alternative to Image, not as a source for Image
xmlns:zx="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
xmlns:zxcm="clr-namespace:ZXing.Common;assembly=zxing.portable"
<zx:ZXingBarcodeImageView
BarcodeFormat="QR_CODE"
BarcodeValue="{Binding CardNumber}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<zx:ZXingBarcodeImageView.BarcodeOptions>
<zxcm:EncodingOptions Width="300" Height="300" />
</zx:ZXingBarcodeImageView.BarcodeOptions>
</zx:ZXingBarcodeImageView>

Related

Xamarin ListView not show json results from api

same as title,my listview doesn't show me anything,i think my model in that app is not good
help! deseeerialized json in jsonObject then create a list of objectModel but not show me
thanks
public class Marvel
{
}
public class TextObject
{
public string type { get; set; }
public string language { get; set; }
public string text { get; set; }
}
public class Url
{
public string type { get; set; }
public string url { get; set; }
}
public class Series
{
public string resourceURI { get; set; }
public string name { get; set; }
}
public class Variant
{
public string resourceURI { get; set; }
public string name { get; set; }
}
public class Date
{
public string type { get; set; }
public DateTime date { get; set; }
}
public class Price
{
public string type { get; set; }
public double price { get; set; }
}
public class Thumbnail
{
public string path { get; set; }
public string extension { get; set; }
}
public class Image
{
public string path { get; set; }
public string extension { get; set; }
}
public class Item
{
public string resourceURI { get; set; }
public string name { get; set; }
public string role { get; set; }
public string type { get; set; }
}
public class Creators
{
public int available { get; set; }
public string collectionURI { get; set; }
public List<Item> items { get; set; }
public int returned { get; set; }
}
public class Characters
{
public int available { get; set; }
public string collectionURI { get; set; }
public List<Item> items { get; set; }
public int returned { get; set; }
}
public class Stories
{
public int available { get; set; }
public string collectionURI { get; set; }
public List<Item> items { get; set; }
public int returned { get; set; }
}
public class Events
{
public int available { get; set; }
public string collectionURI { get; set; }
public List<object> items { get; set; }
public int returned { get; set; }
}
public class Result
{
public int id { get; set; }
public int digitalId { get; set; }
public string title { get; set; }
public int issueNumber { get; set; }
public string variantDescription { get; set; }
public string description { get; set; }
public DateTime modified { get; set; }
public string isbn { get; set; }
public string upc { get; set; }
public string diamondCode { get; set; }
public string ean { get; set; }
public string issn { get; set; }
public string format { get; set; }
public int pageCount { get; set; }
public List<TextObject> textObjects { get; set; }
public string resourceURI { get; set; }
public List<Url> urls { get; set; }
public Series series { get; set; }
public List<Variant> variants { get; set; }
public List<object> collections { get; set; }
public List<object> collectedIssues { get; set; }
public List<Date> dates { get; set; }
public List<Price> prices { get; set; }
public Thumbnail thumbnail { get; set; }
public List<Image> images { get; set; }
public Creators creators { get; set; }
public Characters characters { get; set; }
public Stories stories { get; set; }
public Events events { get; set; }
}
public class Data
{
public int offset { get; set; }
public int limit { get; set; }
public int total { get; set; }
public int count { get; set; }
public List<Result> results { get; set; }
}
public class Rooto
{
public int code { get; set; }
public string status { get; set; }
public string copyright { get; set; }
public string attributionText { get; set; }
public string attributionHTML { get; set; }
public string etag { get; set; }
public Data data { get; set; }
}
}
mainpage
private async void Button_Clicked(object sender, EventArgs e)
{
var texto = caja.Text;
var request = new HttpRequestMessage();
request.RequestUri = new Uri("https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=###&hash=###");
request.Method = HttpMethod.Get;
request.Headers.Add("Accept", "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
string content = await response.Content.ReadAsStringAsync();
Result dataObjects = JsonConvert.DeserializeObject<Result>(content);
JObject myJObject = JObject.Parse(content);
Console.WriteLine(myJObject);
List<Result> parsedFields = new List<Result>();
parsedFields.Add(dataObjects);
ListDemo.ItemsSource = parsedFields;
my xaml and json
https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=ab07bf416406297274b27ca941ba3bee&hash=cf9eb501d7c3775c32b72c61a6a76805
<ContentPage.Content>
<StackLayout>
<Label Text="Control ListView" FontSize="40"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Button Text="Lamado API" Clicked="Button_Clicked"/>
<Entry x:Name="caja" Text=""/>
<ListView x:Name="ListDemo">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Source="{Binding resourceURI}"
WidthRequest="50"
HeightRequest="50"/>
<StackLayout Orientation="Vertical">
<Label Text="{Binding title}"
FontSize="15" TextColor="Blue"/>
<Label Text="{Binding isbn}"
FontSize="12" TextColor="Fuchsia"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
tnaka
You try binding it to an observablecollection.
private ObservableCollection<Result> _parsedFields = new ObservableCollection<Result>();
public ObservableCollection<Result> ParsedFields {
get{ return _parsedFields;}
set{
_parsedFields = value ;
OnPropertyChanged("ParsedFields");
}
}
make sure to implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
then in your button function:
var dataObjects = JsonConvert.DeserializeObject<ObservableCollection<Result>>(content);
ParsedFields = dataObjects;
ListDemo.ItemsSource = ParsedFields;
The root level is supposed to be Root not Result class .
Modify your code as below
Root dataObjects = JsonConvert.DeserializeObject<Root>(text);
ListDemo.ItemsSource = dataObjects.data.results;

Do not load images with FFImageLoading

I am consuming an API in my application and I need to load images, I am doing it with FFImageLoading.
The images are in a json
I follow the steps of adding
FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true); in MyActivity and AppDelegate
My class
public partial class Article
{
[JsonProperty("source")]
public Source Source { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("urlToImage")]
public Uri UrlToImage { get; set; }
[JsonProperty("publishedAt")]
public DateTimeOffset PublishedAt { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
View
<ffimageloading:CachedImage HorizontalOptions="Center"
VerticalOptions="Center"
WidthRequest="300"
HeightRequest="300"
DownsampleToViewSize="true"
Source = "{Binding UrlToImage}">
</ffimageloading:CachedImage>
Result, i using a collectionvieww

Xamarin - How to display en Image from an Object property

In xamarin I have a class where one of the property is an "IMAGE type".
I got this image from one Cloud API I developed myself.
I want now to display this image through a ListView and ImageCell. I'm wondering if there is is a way to bind my "Image" from my object directly thanks to the "ImageSource".
The class is declared the following(indeed the image is created from Byte[]:
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public decimal UnitPrice { get; set; }
public string Description { get; set; }
public string Brand { get; set; }
public bool HasSize { get; set; }
//public virtual List<SizedMeal> AvailableSizes { get; set; }
public bool CanBeSalt { get; set; }
public bool CanBeHotNotCold { get; set; }
public bool CanHaveMeat { get; set; }
public bool CanHaveSauce { get; set; }
public Image Image { get; set; }
}
Where IMAGE is comming from using Xamarin.Forms
and the object is constructed the following way:
Image image = new Image();
Stream stream = new MemoryStream(item.Image);
image.Source = ImageSource.FromStream(() => { return stream; });
ImageSource imageSource = image.Source;
resto.Menu.ItemList.Add(new Item
{
Name = item.Name,
Brand = item.Brand,
Image = image,
UnitPrice = item.UnitPrice,
Description = item.Description,
HasSize = item.HasSize,
ItemId = item.ItemId,
});
Thanks,

How to add custom text to Picker's ItemDisplayBinding in Xamarin Forms

I want to add A custom text to my Picker. I have a picker the ItemsSource and ItemDisplayBinding binds from my database How can I add a custom text to my ItemDisplayBinding I want to mix Retailer Code with PresStreet and format to "Retailer Code - Street" My table is below for reference
Picker Title="Select Retailer Code" x:Name="codePicker" SelectedIndexChanged="codePicker_SelectedIndexChanged" ItemsSource="{Binding RetailerCode}" ItemDisplayBinding="{Binding RetailerCode}" StyleClass="fieldForm" IsEnabled="False"
My code below is how I get the data from my database and add the data to my picker
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getCode = conn.QueryAsync<RetailerGroupTable>("SELECT * FROM tblRetailerGroup WHERE ContactID=?", item.ContactID);
var resultCount = getCode.Result.Count;
if (resultCount > 0)
{
var result = getCode.Result;
codePicker.ItemsSource = result;
codePicker.IsEnabled = true;
}
else
{
lstName.IsVisible = false;
codePicker.IsEnabled = false;
}
My retailer group table:
[Table("tblRetailerGroup")]
public class RetailerGroupTable
{
[PrimaryKey, MaxLength(100)]
public string RetailerCode { get; set; }
public int ContactID { get; set; }
[MaxLength(300)]
public string PresStreet { get; set; }
[MaxLength(90)]
public string PresBarangay { get; set; }
[MaxLength(90)]
public string PresDistrict { get; set; }
[MaxLength(90)]
public string PresTown { get; set; }
[MaxLength(90)]
public string PresProvince { get; set; }
[MaxLength(90)]
public string PresCountry { get; set; }
[MaxLength(30)]
public string Telephone1 { get; set; }
[MaxLength(30)]
public string Telephone2 { get; set; }
[MaxLength(20)]
public string Mobile { get; set; }
[MaxLength(50)]
public string Email { get; set; }
[MaxLength(200)]
public string GPSCoordinates { get; set; }
[MaxLength(100)]
public string Coordinator { get; set; }
public DateTime LastSync { get; set; }
public DateTime ServerUpdate { get; set; }
public DateTime MobileUpdate { get; set; }
}
add a read only property to your class RetailerGroupTable
public string DisplayText {
get {
return $"{RetailerCode} - {PresStreet}";
}
}
and then bind to it
<Picker ItemDisplayBinding="{Binding DisplayText}" ... />

Xamarin - reading JSON file and reading the values

everyone ! I'm new in Xamarin. I've this json file...
{
"debug":true,
"sequence":[
"p1"
],
"pages":[
{
"pageId":"p1",
"type":"seq",
"elements":[
{
"type":"smallVideo",
"width":300,
"height":300,
"top":0,
"left":0,
"file":"xxx.mp4"
}
]
}
],
"index":[
{
"width":300,
"height":300,
"top":0,
"left":0,
"goTo":"p1"
}
]
}
And this is my simple code...
using Newtonsoft.Json;
JObject elements = JObject.Parse(File.ReadAllText("elements.json"));
Console.WriteLine(elements);
Ok, I can see on my output screen the whole JSON file. Fine...
But I'd like to read any value just like javascript, examples...
elements.debug (true)
elements.pages[0].pageId
So, I need to retrieve values based on the key/path like it's usual in Javascript. Any clue ?
ty !
C# is a little bit different from js, here you need to declare objects.
In your case you need to create new class called ElementsObj and your object would be this class instance:
public class ElementsObj
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
In future use http://json2csharp.com/ to generate classes from JSON file.
Later you can deserialize your JSON to this object.
I'd suggest Newtonsoft lib to do this:
ElementsObj tmp = JsonConvert.DeserializeObject<ElementsObj>(jsonString);
1) Option create an object that reflects your JSON structure:
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
public class MyObject
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
MyObject parsed = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("elements.json"));
var debug = parsed.debug;
2) Option using dynamic
dynamic results = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("elements.json"));
var debug = dynamic.debug;

Resources