How to print Generated Barcode ZXING in xamarin forms - c#

I managed to generate a Barcode using ZXING library, now I want to print the generated barcode as it is from the ZXingBarcodeImageView with the same size ,how can I do that
private async Task<Item> getItem()
{
HttpResponseMessage _response = await _client.GetAsync(url + txt_Barcode.Text);
if (_response.IsSuccessStatusCode)
{
string itemDetailes = await _response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Item>(itemDetailes);
}
return new Item();
}
private async void Btn_GetInfo(object sender, EventArgs e)
{
var selected_item = await getItem();
// Item_barcode.Text = selected_item.Value;
Item_Description.Text = selected_item.Description;
Item_name.Text = selected_item.Name;
Item_price.Text = selected_item.Price.ToString();
item_barcode.BarcodeValue = selected_item.Value;
}
xaml code
<!--<Image HeightRequest="300" WidthRequest="300" Margin="1" x:Name="img_barcode"></Image>-->
<zxing:ZXingBarcodeImageView x:Name="item_barcode" HeightRequest="20" WidthRequest="100" BarcodeFormat="CODE_39" BarcodeValue="Place Barcode" >
<zxing:ZXingBarcodeImageView.BarcodeOptions>
<zxingcomon:EncodingOptions Height="80" Width="1000"></zxingcomon:EncodingOptions>
</zxing:ZXingBarcodeImageView.BarcodeOptions>
</zxing:ZXingBarcodeImageView>
<StackLayout Orientation="Horizontal" Spacing="20" >
<Label TextColor="Black" x:Name="Item_Description"></Label>
<Label TextColor="Black" x:Name="Item_price"></Label>
</StackLayout>
<StackLayout x:Name="SLPrint" BackgroundColor="GhostWhite" VerticalOptions="FillAndExpand">
<Button Text="print" BackgroundColor="Black" TextColor="White"></Button>
</StackLayout>
</StackLayout>
</StackLayout>

The best and easiest option to do this is show the barcode inside webview.
here is a library which u can use Link
you can copy the script in asset folder. create a html file import the script
Now from xamarin side Evalute javascript in webview where you would send the barcode data to webview
here is how you can do it.
Link
note : you dont need to do any custom rendering
with this you can remove the zxing and can make your app size small

Related

How to select an image from gallery in xamarin forms?

I'm trying to pick an image from gallery and i've done everything that is in this doc, but i'm getting an error with the "image" object in my .cs implementation.
My .cs code:
public partial class MyProfilePage : ContentPage
{
public MyProfilePage()
{
InitializeComponent();
BindingContext = new MyProfileViewModel();
}
async void ImageButton_Clicked(object sender, EventArgs e)
{
//(sender as Button).IsEnabled = true;
Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
if (stream != null)
{
image = ImageSource.FromStream(() => stream);
}
(sender as Button).IsEnabled = true;
}
}
Welcome to SO!
but i'm getting an error with the "image" object in my .cs implementation.
You can check the Xaml file that whether contain the x:Name="image".
Such as follows:
<ContentPage Title="Photo Picker"
Icon="monkeyicon.png">
<StackLayout Margin="20,35,20,20" >
<Label Text="Photo Picker"
FontAttributes="Bold"
HorizontalOptions="Center" />
<Button Text="Pick Photo"
Clicked="OnPickPhotoButtonClicked" />
<Image x:Name="image" />
</StackLayout>
</ContentPage>
If not works , you can refer to following steps:
First, you need to share the detail error logs here, and explain this occurs in iOS or
Android.
Second, you also can refer to this official sample Xamarin.Forms - Dependency Service to check where problem is.

My piece of HTML won't display in my WebView in C#/XAML

My application reads a RSS feed and display it in a list. This mostly works:
var rssfeed = new RSSfeed(); // make instance to use
string s = await rssfeed.GetHttpStr(feedUrl); // get feed as string
this.items = rssfeed.ParseRSS(s); // parse RSS into a list
(RSSfeed is a model of an item in the feed. s is the http response string. ParseRSS is a method that converts the string, using the model, into an object.)
(To made this brief, I've excluded the code behind the methods. If you want I can post has as well on request.)
The following loop will place each item into the ListView.
foreach (var item in myItems)
{
var htmlSource = new HtmlWebViewSource
{
Html = #"<html><body>" + item.Desc + "</body></html>"
};
this.items.Add(new RSSItem
{
Title = item.Title,
Link = item.Link,
ID = item.Id,
Desc = htmlSource.Html
});
}
Here is my XAML, inside my DataTemplate:
<ViewCell>
<Frame OutlineColor="Gray">
<StackLayout Margin="5" Padding="5">
<Label Text="{Binding Title}" TextColor="SteelBlue" />
<Label Text="{Binding Link}" FontSize="10" TextColor="Green" />
<Label Text="{Binding Desc}" TextColor="Fuchsia" />
<Grid RowSpacing="0" ColumnSpacing="0" Margin="0" Padding="0" BackgroundColor="Transparent">
<WebView Source="{Binding Desc}" />
</Grid>
</StackLayout>
</Frame>
</ViewCell>
(Apparently the WebView wrapped in a Grid doesn't require a Width/HeightRequest - is this true? Is there another way to make it dynamically sized to the contents?)
The ListView shows fine (and most RSS fields) but my WebView is empty. What do I need to display the "Desc" (a simple HTML image tag) in the WebView?
WebView.Source is a Uri not a string. If you want to view custom HTML content, you'll need to use the NavigateToString(html) method. Unfortunately, you can't bind to that either, but there's a workaround found here.

How create Bottom sheets in Xamarin.Forms

How create Bottom sheets in Xamarin.Forms?
https://material.io/guidelines/components/bottom-sheets.html
Use SlideOverKit for this purpose.
It's available on nuget
Here are some examples
The control you are looking for is called Slide up Menu
Xamarin Forms Bottom sheet without a nuget package library.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourAppName.Views.YourPageName">
<ContentPage.Content>
<RelativeLayout BackgroundColor="White">
<StackLayout HorizontalOptions="Fill" VerticalOptions="Fill">
<!-- place your page content here -->
</StackLayout>
<Frame x:Name="BottomSheet" CornerRadius="20" HasShadow="True" BackgroundColor="White" Padding="10,5" BorderColor="LightGray"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=.93,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=1,Constant=0}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=1,Constant=0}">
<Frame.GestureRecognizers>
<PanGestureRecognizer PanUpdated="OnPanelUpdated" />
</Frame.GestureRecognizers>
<StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="Fill">
<BoxView HeightRequest="5" CornerRadius="2" BackgroundColor="Grey" HorizontalOptions="CenterAndExpand" WidthRequest="50" Margin="25,10,0,10"></BoxView>
<!-- Place your bottom sheet layout here -->
</StackLayout>
</Frame>
</RelativeLayout>
</ContentPage.Content>
</ContentPage>
YourPageName.xaml.cs Code behind
protected override void OnAppearing()
{
MoveBottomSheet(true);
}
/// The -negative value determines how many vertical units should the panel occuply on the screen.
private async void MoveBottomSheet(bool close)
{
double finalTranslation = close ? (Device.Idiom == TargetIdiom.Phone ? -134.0 : -144.0) : (Device.Idiom == TargetIdiom.Phone ? -389.0 : -434.0);
await BottomSheet.TranslateTo(BottomSheet.X, finalTranslation, 450, Easing.SinIn);
}
/// This is fired multiple times while the user pans the bottom sheet. This variable captures the first intention of determining whether to open (pan up) or close (pan down)
bool _panelActivated = false;
private void OnPanelUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
break;
case GestureStatus.Running:
if (_panelActivated)
{
return;
}
MoveBottomSheet(e.TotalY > 0);
_panelActivated = true;
break;
case GestureStatus.Completed:
_panelActivated = false;
break;
case GestureStatus.Canceled:
break;
}
}
you can use a nuget made by me this is the github project
https://github.com/josco007/CHDBottomSheet
It also supports scrollviews inside.
You need a relative layout as root view and set your relative layout in this way on the onAppearing method
protected override void OnAppearing()
{
base.OnAppearing();
CHDBottomSheetBs.SetRelativeLayout(_rootRlt);
}
See the github project for more information.

How would I correctly parse data from wordpress mySQL DB to xamarin forms c#?

I am using the Jetpack Wordpress Plugin, which allows allows a mobile app to connect to the websites MySQL database, the data request completes successfully however it pulls all the html code with the content, all I require are the paragraphs in the content field, this is how it displays:
As you can see the image and Title appear fine, only the content pulls all the wordpress html with required text paragragh in between.
XAML File with code behind:
<ListView x:Name="postListView" HasUnevenRows="true" SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10" Orientation="Vertical" BackgroundColor="#4c4c4c" Spacing="5">
<Image x:Name="listViewImage"
Aspect="AspectFill"
Source="{Binding featured_image_url}"
HorizontalOptions="Fill"
HeightRequest="200" />
<StackLayout VerticalOptions="StartAndExpand">
<Label
Text="{Binding title}"
FontSize="15"
FontAttributes="Bold"
TextColor="#fac80d"
HorizontalTextAlignment="Center"
LineBreakMode="WordWrap"/>
<Label x:Name="ContentLabel"
Text="{Binding content}"
FontSize="12"
TextColor="White"
HorizontalTextAlignment="Center"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
Code Behind set to pull 10 blog posts:
public partial class NewsPage : ContentPage
{
private const string Url = "www.website.com";
WordPressClient client;
public NewsPage()
{
InitializeComponent();
client = new WordPressClient();
}
protected override async void OnAppearing()
{
base.OnAppearing();
var postlist = await client.GetPostList(Url, PostType.post, PostStatus.publish, 10, 0);
postListView.ItemsSource = postlist.posts_list;
}
}
Model:
[JsonProperty("title")]
public string title {get; set;}
[JsonProperty("content")]
public string content {get; set;}
[JsonProperty("featured_image")]
public string featured_image_url {get; set;}
I found a solution to this issue, for anyone who experiences this in their project - when pulling data from a WordPress website, it will get a HTML string of data along with the theme you're using custom code, this is why HTML Agility pack was not recognizing the data as HTML, because it was full of square brackets [].
To remove the unwanted code I used REGEX, to use REGEX :
using System.Text.RegularExpressions;
In your code you need to take your HTML content and clean it up with the following snippet:
var plainContent = Regex.Replace(wallItem.content, #"^?\[.*", "");
var cleanedContent = plainContent;
//The Webview Source HTML
HtmlWBS.Html = cleanedContent;
Use the HTMLAgilityPack to parse the HTML and extract the content that you want.
var doc = new HtmlDocument ();
doc.LoadHtml (content);
// use the HTML DOM to extract the data you need
var div = doc.GetElementbyId ("...");
This blog post discusses this approach in more detail.

How to make the loading screen to disappear when my data is loaded in Xamarin Forms?

I want to build a loading screen when no data is displayed. But it's not working, it keeps loading forever. How to make the loading screen to disappear when my data is loaded?
This is my C# code
if (Clublistview.ItemsSource == null)
{
try
{
base.OnAppearing();
await setClubs(Clublistview);
overlay.IsVisible = false;
Clublistview.IsVisible = true;
}
catch (Exception ex)
{
//MessagingCenter
await DisplayAlert("Error",
"There seems to be an error, please check your internet connection.",
"OK");
}
}
else
{
overlay.IsVisible = true;
Clublistview.IsVisible = false;
}
This is the XAML code
<ListView x:Name="Clublistview" HasUnevenRows="true" ItemSelected="OnItemSelected" ItemsSource="{Binding Id}" IsVisible="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="55">
<StackLayout BackgroundColor="White"
Orientation="Vertical">
<StackLayout Orientation="Horizontal" Padding="2,2,2,2">
<Image Source="{Binding Logo}" IsVisible="true" WidthRequest="50" HeightRequest="50"/>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Name}" FontSize="20" x:Name="BtnClub"
TextColor="Black" />
<Label HorizontalOptions="Start" Text="Select for more info" FontSize="10"/>
<!--<Button BackgroundColor="White" TextColor="Black" HorizontalOptions="Start" x:Name="btnInfo"
Text="Select for more info" FontSize="10" Clicked="OnInfoClicked" CommandParameter="{Binding Id}"/>-->
</StackLayout>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ContentView x:Name="overlay" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" AbsoluteLayout.LayoutFlags="All" IsVisible="false">
<ActivityIndicator IsRunning="True" IsVisible="True" Color="Black" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
</ContentView>
It looks like this code is placed on the OnAppearing method of your ContentPage. If that's the case, it's only going to be called 1 time as the page is shown. Assuming that Clublistview.ItemsSource is not null, then this code gets executed:
overlay.IsVisible = true;
Clublistview.IsVisible = false;
This means that your overlay is visible and the ActivityIndicator will be spinning. If this is not in OnAppearing then I am not sure when you are calling the method it is in.
You might want to do something like this instead:
public override async void OnAppearing()
{
base.OnAppearing();
// Show your overlay
overlay.IsVisible = true;
Clublistview.IsVisible = false;
// Load the items into the ItemsSource
await setClubs(Clublistview);
// Hide the overlay
overlay.IsVisible = false;
Clublistview.IsVisible = true;
}
You can achieve this type of behavior in a cleaner way with the MVVM pattern. With MVVM you can use a property binding to control when the overlay is shown. We have some guides on MVVM and Xamarin.Forms that can help get you started here. Here is a blog post that shows an example too.
This is what worked for me:
protected override void OnAppearing()
{
base.OnAppearing();
this.layoutLoadingSpinner.IsVisible = true;
this.layoutContent.IsVisible = false;
// Load slow-loading model on a separate thread
MySlowLoadingModel model = null;
await Task.Run(() =>
{
model = new MySlowLoadingModel();
});
this.BindingContext = model;
this.layoutLoadingSpinner.IsVisible = false;
this.layoutContent.IsVisible = true;
}
(Another option that avoids async/await is to call MainThread.BeginInvokeOnMainThread() inside the Task.Run)
An unfortunate side-effect is that any code run on the second thread becomes very difficult to debug. It seems the Xamarin debugger doesn't work right with multiple threads.

Categories

Resources