xamarin entry not work - xamarin

I Have An Entry In One Page in my xamarin.forms application that doesn't work properly on my tablet.when I Click on it keyboard appears and I can type in but nothing but placeholder display. this application is work on other android Devices but my tablet not display input data.
tablet : galaxy tab s - android 5.0
phone : galaxy s6 - android 6.0
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyProject.MyPage"
Title="SomeTitle"
Padding="10, 40, 10, 10">
<Entry Placeholder="Hi"/>
</ContentPage>

In some samsung devices this happens for that you need to write custom renderer and try set text color or backgroundcolor then it should work.
OR
try XLabs Extended Entry

Try this
Usage :
ExtendedEntry entry = new ExtendedEntry
{
Text = "Dummy Text",
TextColor = Color.Black,
PlaceholderTextColor = Color.Black,
};
PCL Code
using Xamarin.Forms;
namespace VHS.MobileApp.eVita.CustomViews
{
public class ExtendedEntry : Entry
{
/// <summary>
/// The font property
/// </summary>
public static readonly BindableProperty FontProperty =
BindableProperty.Create("Font", typeof(Font), typeof(ExtendedEntry), new Font());
/// <summary>
/// The XAlign property
/// </summary>
public static readonly BindableProperty XAlignProperty =
BindableProperty.Create("XAlign", typeof(TextAlignment), typeof(ExtendedEntry),
TextAlignment.Start);
/// <summary>
/// The HasBorder property
/// </summary>
public static readonly BindableProperty HasBorderProperty =
BindableProperty.Create("HasBorder", typeof(bool), typeof(ExtendedEntry), true);
/// <summary>
/// The PlaceholderTextColor property
/// </summary>
public static readonly BindableProperty PlaceholderTextColorProperty =
BindableProperty.Create("PlaceholderTextColor", typeof(Color), typeof(ExtendedEntry), Color.Default);
/// <summary>
/// The MaxLength property
/// </summary>
public static readonly BindableProperty MaxLengthProperty =
BindableProperty.Create("MaxLength", typeof(int), typeof(ExtendedEntry), int.MaxValue);
/// <summary>
/// Gets or sets the MaxLength
/// </summary>
public int MaxLength
{
get { return (int)this.GetValue(MaxLengthProperty); }
set { this.SetValue(MaxLengthProperty, value); }
}
/// <summary>
/// Gets or sets the Font
/// </summary>
public Font Font
{
get { return (Font)GetValue(FontProperty); }
set { SetValue(FontProperty, value); }
}
/// <summary>
/// Gets or sets the X alignment of the text
/// </summary>
public TextAlignment XAlign
{
get { return (TextAlignment)GetValue(XAlignProperty); }
set { SetValue(XAlignProperty, value); }
}
/// <summary>
/// Gets or sets if the border should be shown or not
/// </summary>
public bool HasBorder
{
get { return (bool)GetValue(HasBorderProperty); }
set { SetValue(HasBorderProperty, value); }
}
/// <summary>
/// Sets color for placeholder text
/// </summary>
public Color PlaceholderTextColor
{
get { return (Color)GetValue(PlaceholderTextColorProperty); }
set { SetValue(PlaceholderTextColorProperty, value); }
}
public static readonly BindableProperty BorderRadiusProperty =
BindableProperty.Create<ExtendedEntry, float>(p => p.BorderRadius, default(float));
public float BorderRadius
{
get { return (float)GetValue(BorderRadiusProperty); }
set { SetValue(BorderRadiusProperty, value); }
}
}
}
Droid Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using VHS.MobileApp.eVita.CustomViews;
using Android.Graphics;
using Android.Text.Method;
using Android.Util;
using Color = Xamarin.Forms.Color;
using VHS.MobileApp.eVita.Droid.CustomRenderer;
using System.ComponentModel;
using Android.Text;
[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))]
namespace VHS.MobileApp.eVita.Droid.CustomRenderer
{
public class ExtendedEntryRenderer : EntryRenderer
{
protected ExtendedEntryRenderer(IntPtr javaReference, JniHandleOwnership transfer)
{
}
public ExtendedEntryRenderer()
: base()
{
}
private const int MinDistance = 10;
/// <summary>
/// Called when [element changed].
/// </summary>
/// <param name="e">The e.</param>
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
var view = (ExtendedEntry)Element;
if (Control != null && e.NewElement != null && e.NewElement.IsPassword)
{
Control.SetTypeface(Typeface.Default, TypefaceStyle.Normal);
Control.TransformationMethod = new PasswordTransformationMethod();
this.Control.SetBackgroundColor(Android.Graphics.Color.White);
}
#region SETTING CUSTOM FONT
if (view.FontFamily != null && view.FontFamily != string.Empty)
{
Typeface typeface = Typeface.CreateFromAsset(Forms.Context.Assets, view.FontFamily);
Control.Typeface = typeface;
}
#endregion
// SetFont(view);
SetTextAlignmentWithVerticalFill(view);
SetPlaceholderTextColor(view);
SetMaxLength(view);
}
/// <summary>
/// Handles the touch.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Android.Views.View.TouchEventArgs"/> instance containing the event data.</param>
/*void HandleTouch(object sender, TouchEventArgs e)
{
var element = (ExtendedEntry)this.Element;
switch (e.Event.Action)
{
case MotionEventActions.Down:
this.downX = e.Event.GetX();
this.downY = e.Event.GetY();
return;
case MotionEventActions.Up:
case MotionEventActions.Cancel:
case MotionEventActions.Move:
this.upX = e.Event.GetX();
this.upY = e.Event.GetY();
float deltaX = this.downX - this.upX;
float deltaY = this.downY - this.upY;
// swipe horizontal?
if (Math.Abs(deltaX) > Math.Abs(deltaY))
{
if (Math.Abs(deltaX) > MinDistance)
{
if (deltaX < 0)
{
element.OnRightSwipe(this, EventArgs.Empty);
return;
}
if (deltaX > 0)
{
element.OnLeftSwipe(this, EventArgs.Empty);
return;
}
}
else
{
Log.Info("ExtendedEntry", "Horizontal Swipe was only " + Math.Abs(deltaX) + " long, need at least " + MinDistance);
return; // We don't consume the event
}
}
// swipe vertical?
// else
// {
// if(Math.abs(deltaY) > MIN_DISTANCE){
// // top or down
// if(deltaY < 0) { this.onDownSwipe(); return true; }
// if(deltaY > 0) { this.onUpSwipe(); return true; }
// }
// else {
// Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
// return false; // We don't consume the event
// }
// }
return;
}
}*/
/// <summary>
/// Handles the <see cref="E:ElementPropertyChanged" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var view = (ExtendedEntry)Element;
this.Control.SetBackgroundColor(Android.Graphics.Color.White);
//if (e.PropertyName == ExtendedEntry.FontProperty.PropertyName)
//{
// SetFont(view);
//}
//else
if (e.PropertyName == ExtendedEntry.XAlignProperty.PropertyName)
{
SetTextAlignmentWithVerticalFill(view);
}
else if (e.PropertyName == ExtendedEntry.HasBorderProperty.PropertyName)
{
//return;
}
else if (e.PropertyName == ExtendedEntry.PlaceholderTextColorProperty.PropertyName)
{
SetPlaceholderTextColor(view);
}
else
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
{
this.Control.SetBackgroundColor(view.BackgroundColor.ToAndroid());
}
}
}
/// <summary>
/// Sets the text alignment.
/// </summary>
/// <param name="view">The view.</param>
private void SetTextAlignmentWithVerticalFill(ExtendedEntry entry)
{
switch (entry.XAlign)
{
case Xamarin.Forms.TextAlignment.Center:
Control.Gravity = GravityFlags.Center;
break;
case Xamarin.Forms.TextAlignment.End:
Control.Gravity = GravityFlags.End | GravityFlags.CenterVertical;
break;
case Xamarin.Forms.TextAlignment.Start:
Control.Gravity = GravityFlags.Start | GravityFlags.CenterVertical;
break;
}
}
/// <summary>
/// Sets the color of the placeholder text.
/// </summary>
/// <param name="view">The view.</param>
private void SetPlaceholderTextColor(ExtendedEntry view)
{
if (view.PlaceholderTextColor != Color.Default)
{
Control.SetHintTextColor(view.PlaceholderTextColor.ToAndroid());
}
}
/// <summary>
/// Sets the MaxLength characteres.
/// </summary>
/// <param name="view">The view.</param>
private void SetMaxLength(ExtendedEntry view)
{
Control.SetFilters(new IInputFilter[] { new InputFilterLengthFilter(view.MaxLength) });
}
}
}

Related

Xamarin Forms: How to handle a subcribe event from view to viewmodel (ListView - Search Bar)

All,
I'm building a custom SearchableListView that binds the SearchText property.
public class SearchableListView : SfListView
{
#region Field
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
public static readonly BindableProperty SearchTextProperty =
BindableProperty.Create(nameof(SearchText), typeof(string), typeof(SearchableListView), null, BindingMode.Default, null, OnSearchTextChanged);
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
private string searchText;
#endregion
#region Property
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
public string SearchText
{
get
{
return (string)this.GetValue(SearchTextProperty);
}
set
{
this.SetValue(SearchTextProperty, value);
}
}
#endregion
#region Method
/// <summary>
/// Filtering the list view items based on the search text.
/// </summary>
/// <param name="obj">The list view item</param>
/// <returns>Returns the filtered item</returns>
public virtual bool FilterData(object obj)
{
if (this.SearchText == null)
{
return false;
}
return true;
}
/// <summary>
/// Invoked when the search text is changed.
/// </summary>
/// <param name="bindable">The SfListView</param>
/// <param name="oldValue">The old value</param>
/// <param name="newValue">The new value</param>
private static void OnSearchTextChanged(BindableObject bindable, object oldValue, object newValue)
{
var listView = bindable as SearchableListView;
if (newValue != null && listView.DataSource != null)
{
listView.searchText = (string)newValue;
listView.DataSource.Filter = listView.FilterData;
listView.DataSource.RefreshFilter();
}
listView.RefreshView();
}
#endregion
}
This view is binding to a Generic List Items, so the object on FilterData can be any type.
IDK how to subscribe an event to the FilterData which executes the method on the view model where I can cast my object to my known type.
This is my ViewModel.
public abstract class ListPageViewModel<T> : BaseViewModel where T : class, IEntity
{
private T _selectedItem;
private string searchText;
private ObservableCollection<T> _items;
public ListPageViewModel()
{
this.NewCommand = new Command(NewItem);
this.ItemSelectedCommand = new Command(ItemSelected);
}
public ObservableCollection<T> Items
{
get => _items;
set
{
this.SetProperty(ref this._items, value);
}
}
public T SelectedItem
{
get => _selectedItem;
set
{
this.SetProperty(ref this._selectedItem, value);
}
}
public string SearchText
{
get => searchText;
set
{
this.SetProperty(ref this.searchText, value);
}
}
public ICommand NewCommand { get; set; }
public ICommand ItemSelectedCommand { get; set; }
public async virtual void LoadItemsAsync()
{
Items = new ObservableCollection<T>(await localDataService.GetAllAsync<T>());
}
public async virtual void NewItem(object obj)
{
}
public async virtual void ItemSelected(object obj)
{
var eventArgs = obj as Syncfusion.ListView.XForms.ItemTappedEventArgs;
navigationService.NavigateTo(EditViewModel, "editEntity", eventArgs.ItemData, false);
await MtTaskExtensions.CompletedTask;
}
}
Since it's a virtual method, can't you just override the method in the ViewModel like this?
public class MyListPageViewModel : ListPageViewModel<MyClass>
{
public override bool FilterData(object obj)
{
if(obj is MyClass myObj)
{
// Do something
}
return base
.FilterData(obj);
}
}

XLabs.Platform not working on UWP

I am using Windows 10 & Visual Studio 2015 for development and targeting Android, iOS, Windows Phone, Windows Universal.
I wanted to use XLabs SecureStorage Service.
I am using XLabs.Platform package 2.3.0-pre02.
at this line i am getting exception (only for UWP)
secureStorage.Store(key, Encoding.UTF8.GetBytes(value));
And Exception Details are :
FileName : System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
HResult : -2146234304
HelpLink : null
InnerException : null
Message : Could not load file or assembly 'System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Source : XLabs.Platform.UWP
SourceTrack : at XLabs.Platform.Services.SecureStorage.d__6.MoveNext()
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.StartTStateMachine
at XLabs.Platform.Services.SecureStorage.Store(String key, Byte[] dataBytes)
at UWPTest.SecureStorageService.Store(String key, String value, Boolean overwrite)
After some trial and error i am able to run SecureStorage service successfully on Xamarin UWP.
SecureStorage.cs(Code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ABC.UWP.Common
{
using System;
using System.IO;
using Windows.Storage;
using System.Threading;
using System.Runtime.InteropServices.WindowsRuntime;
using XLabs.Platform.Services;
using Windows.Security.Cryptography.DataProtection;
/// <summary>
/// Implements <see cref="ISecureStorage"/> for WP using <see cref="IsolatedStorageFile"/> and <see cref="ProtectedData"/>.
/// </summary>
public class SecureStorage : ISecureStorage
{
private static Windows.Storage.ApplicationData AppStorage { get { return ApplicationData.Current; } }
private static Windows.Security.Cryptography.DataProtection.DataProtectionProvider _dataProtectionProvider = new DataProtectionProvider();
private readonly byte[] _optionalEntropy;
/// <summary>
/// Initializes a new instance of <see cref="SecureStorage"/>.
/// </summary>
/// <param name="optionalEntropy">Optional password for additional entropy to make encyption more complex.</param>
public SecureStorage(byte[] optionalEntropy)
{
this._optionalEntropy = optionalEntropy;
}
/// <summary>
/// Initializes a new instance of <see cref="SecureStorage"/>.
/// </summary>
public SecureStorage() : this(null)
{
}
#region ISecureStorage Members
/// <summary>
/// Stores the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="dataBytes">The data bytes.</param>
public async void Store(string key, byte[] dataBytes)
{
//var mutex = new Mutex(false, key);
using (var mutex = new Mutex(false, key))
{
try
{
mutex.WaitOne();
var buffer = dataBytes.AsBuffer();
if (_optionalEntropy != null)
{
buffer = await _dataProtectionProvider.ProtectAsync(buffer);
}
var file = await AppStorage.LocalFolder.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBufferAsync(file, buffer);
}
catch (Exception ex)
{
throw new Exception(string.Format("No entry found for key {0}.", key), ex);
}
}
//finally
//{
// mutex.ReleaseMutex();
//}
}
/// <summary>
/// Retrieves the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>System.Byte[].</returns>
/// <exception cref="System.Exception"></exception>
public byte[] Retrieve(string key)
{
var mutex = new Mutex(false, key);
try
{
mutex.WaitOne();
return Task.Run(async () =>
{
var file = await AppStorage.LocalFolder.GetFileAsync(key);
var buffer = await FileIO.ReadBufferAsync(file);
if (_optionalEntropy != null)
{
buffer = _dataProtectionProvider.UnprotectAsync(buffer).GetResults();
}
return buffer.ToArray();
}).Result;
}
catch (Exception ex)
{
throw new Exception(string.Format("No entry found for key {0}.", key), ex);
}
finally
{
mutex.ReleaseMutex();
}
}
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="key">The key.</param>
public void Delete(string key)
{
var mutex = new Mutex(false, key);
try
{
mutex.WaitOne();
Task.Run(async () =>
{
var file = await AppStorage.LocalFolder.GetFileAsync(key);
await file.DeleteAsync();
});
}
finally
{
mutex.ReleaseMutex();
}
}
/// <summary>
/// Checks if the storage contains a key.
/// </summary>
/// <param name="key">The key to search.</param>
/// <returns>True if the storage has the key, otherwise false. </returns>
public bool Contains(string key)
{
try
{
return Task.Run(async() => await AppStorage.LocalFolder.GetFileAsync(key)).Result.IsAvailable;
}
catch
{
return false;
}
}
#endregion
}
}

Show / Hide checkbox in Xamarin Forms

I am trying to figure out a way to make checkbox appear on button click on a page.
It's invisible by default, because I've set checkBox.Visibility = Android.Views.ViewStates.Invisible; in my custom renderer.
I have a button in the page content and a checkbox in the template which resides in pages resources.
From my ViewModel I am able to invoke PropertyChanged in CheckBox control where I can see the old and new value correctly set.
But I need a way to set it on the ViewRenderer. I'm guessing that it needs to handle some kind of event similar to CheckedChanged.
ViewModel
CheckBox c = new CheckBox { IsCheckBoxVisible=true,IsVisible=true };
CheckBox control
public class CheckBox : View
{
/// <summary>
/// The checked state property.
/// </summary>
public static readonly BindableProperty CheckedProperty =
BindableProperty.Create<CheckBox, bool>(
p => p.Checked, false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged);
**public static readonly BindableProperty IsCheckBoxVisibleProperty =
BindableProperty.Create<CheckBox, bool>(
p => p.IsCheckBoxVisible, false, BindingMode.OneWay, propertyChanged: OnVisibilityPropertyChanged);**
/// <summary>
/// The checked text property.
/// </summary>
public static readonly BindableProperty CheckedTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.CheckedText, string.Empty, BindingMode.TwoWay);
/// <summary>
/// The unchecked text property.
/// </summary>
public static readonly BindableProperty UncheckedTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.UncheckedText, string.Empty);
/// <summary>
/// The default text property.
/// </summary>
public static readonly BindableProperty DefaultTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.Text, string.Empty);
/// <summary>
/// Identifies the TextColor bindable property.
/// </summary>
///
/// <remarks/>
public static readonly BindableProperty TextColorProperty =
BindableProperty.Create<CheckBox, Color>(
p => p.TextColor, Color.Default);
/// <summary>
/// The font size property
/// </summary>
public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create<CheckBox, double>(
p => p.FontSize, -1);
/// <summary>
/// The font name property.
/// </summary>
public static readonly BindableProperty FontNameProperty =
BindableProperty.Create<CheckBox, string>(
p => p.FontName, string.Empty);
/// <summary>
/// The checked changed event.
/// </summary>
public event EventHandler<EventArgs<bool>> CheckedChanged;
**public event EventHandler<EventArgs<bool>> VisibilityChanged;**
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
public bool Checked
{
get
{
return this.GetValue<bool>(CheckedProperty);
}
set
{
if (this.Checked != value)
{
this.SetValue(CheckedProperty, value);
this.CheckedChanged.Invoke(this, value);
}
}
}
**public bool IsCheckBoxVisible
{
get
{
return this.GetValue<bool>(IsCheckBoxVisibleProperty);
}
set
{
if (this.IsCheckBoxVisible != value)
{
this.SetValue(IsCheckBoxVisibleProperty, value);
this.VisibilityChanged.Invoke(this, value);
//OnPropertyChanged("IsCheckBoxVisible");
}
}
}**
/// <summary>
/// Gets or sets a value indicating the checked text.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string CheckedText
{
get
{
return this.GetValue<string>(CheckedTextProperty);
}
set
{
this.SetValue(CheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string UncheckedText
{
get
{
return this.GetValue<string>(UncheckedTextProperty);
}
set
{
this.SetValue(UncheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets the text.
/// </summary>
public string DefaultText
{
get
{
return this.GetValue<string>(DefaultTextProperty);
}
set
{
this.SetValue(DefaultTextProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>The color of the text.</value>
public Color TextColor
{
get
{
return this.GetValue<Color>(TextColorProperty);
}
set
{
this.SetValue(TextColorProperty, value);
}
}
/// <summary>
/// Gets or sets the size of the font.
/// </summary>
/// <value>The size of the font.</value>
public double FontSize
{
get
{
return (double)GetValue(FontSizeProperty);
}
set
{
SetValue(FontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the name of the font.
/// </summary>
/// <value>The name of the font.</value>
public string FontName
{
get
{
return (string)GetValue(FontNameProperty);
}
set
{
SetValue(FontNameProperty, value);
}
}
/// <summary>
/// Gets the text.
/// </summary>
/// <value>The text.</value>
public string Text
{
get
{
return this.Checked
? (string.IsNullOrEmpty(this.CheckedText) ? this.DefaultText : this.CheckedText)
: (string.IsNullOrEmpty(this.UncheckedText) ? this.DefaultText : this.UncheckedText);
}
}
/// <summary>
/// Called when [checked property changed].
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <param name="oldvalue">if set to <c>true</c> [oldvalue].</param>
/// <param name="newvalue">if set to <c>true</c> [newvalue].</param>
private static void OnCheckedPropertyChanged(BindableObject bindable, bool oldvalue, bool newvalue)
{
var checkBox = (CheckBox)bindable;
checkBox.Checked = newvalue;
}
**private static void OnVisibilityPropertyChanged(BindableObject bindable, bool oldvalue, bool newvalue)
{
var checkBox = (CheckBox)bindable;
checkBox.IsCheckBoxVisible = newvalue;
}**
}
CheckBoxRenderer
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (this.Control == null)
{
var checkBox = new Android.Widget.CheckBox(this.Context);
checkBox.Visibility = Android.Views.ViewStates.Invisible;
checkBox.CheckedChange += CheckBoxCheckedChange;
defaultTextColor = checkBox.TextColors;
this.SetNativeControl(checkBox);
}
Control.Text = e.NewElement.Text;
Control.Checked = e.NewElement.Checked;
UpdateTextColor();
if (e.NewElement.FontSize > 0)
{
Control.TextSize = (float)e.NewElement.FontSize;
}
if (!string.IsNullOrEmpty(e.NewElement.FontName))
{
Control.Typeface = TrySetFont(e.NewElement.FontName);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
switch (e.PropertyName)
{
case "Checked":
Control.Text = Element.Text;
Control.Checked = Element.Checked;
break;
case "TextColor":
UpdateTextColor();
break;
case "FontName":
if (!string.IsNullOrEmpty(Element.FontName))
{
Control.Typeface = TrySetFont(Element.FontName);
}
break;
case "FontSize":
if (Element.FontSize > 0)
{
Control.TextSize = (float)Element.FontSize;
}
break;
case "CheckedText":
case "UncheckedText":
Control.Text = Element.Text;
break;
** case "IsCheckBoxVisible":
if(Element.IsCheckBoxVisible==true)
{
Control.Visibility = Android.Views.ViewStates.Visible;
}
else
{
Control.Visibility = Android.Views.ViewStates.Invisible;
}
break;**
default:
System.Diagnostics.Debug.WriteLine("Property change for {0} has not been implemented.", e.PropertyName);
break;
}
}
So this should actually be really simple. right now you have IsCheckBoxVisibleProperty, and you can get rid of it all together. The Xamarin.Forms.View already has an IsVisible property, and each platform specific renderer (VisualElementRenderer) knows how to handle visibility.
Therefore you can do this without issue.
var checkbox = new Checkbox();
checkbox .SetBinding (Checkbox.IsVisibleProperty, "IsCheckboxVisible");
Or in your XAML
<controls:Checkbox IsVisible="{Binding IsCheckboxVisible}" />
Of course this assumes you have a ViewModel similar to.
public class MyViewModel : BaseViewModel
{
private bool _isCheckboxVisible;
public bool IsCheckboxVisible
{
get { return _isCheckboxVisible; }
set { SetField(ref _isCheckboxVisible, value); }
}
}

Substutute for FacebookSubscriptionVerify in facebook C# SDk 6.4

In latest version of Facebook C# SDk 6.4. Can we use FacebookSubscriptionVerify Action Method Attribute ? As this is not available in the FacebookClient Class
I was using the older version of Facebok C# SDK in my MVC3 project. Now, After switching to Facebook C# SDK 6.4 this class is not available.
Do we have any substitute for this?
I took a little more time this morning and confirmed that the attribute that you referenced was removed in version 6 (along with tons of other items). Since this project is open source, here is the code for the FacebookSubscriptionVerify ActionFilter that you used to use. For any references to functions within here that I did not include, this version on CodePlex has all of the code available for you to look at: http://facebooksdk.codeplex.com/SourceControl/changeset/view/08cb51f372b5#Source/Facebook.Web/FacebookSubscriptionsHttpHandler.cs
The new version (version 6.X) and the last few branches of version 5 can be found on the GitHub site - https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/tree/master/Source
With the availability of the source code, you should be able to, in tandem with how you were using this function, create your own ActionFilterAttribute that can replicate the functionality that you had previously.
// --------------------------------
// <copyright file="FacebookSubscriptionVerifyAttribute.cs" company="Thuzi LLC (www.thuzi.com)">
// Microsoft Public License (Ms-PL)
// </copyright>
// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
// <license>Released under the terms of the Microsoft Public License (Ms-PL)</license>
// <website>http://facebooksdk.codeplex.com</website>
// ---------------------------------
namespace Facebook.Web.Mvc
{
using System.Web.Mvc;
public class FacebookSubscriptionVerifyAttribute : ActionFilterAttribute
{
public string VerificationToken { get; set; }
public FacebookSubscriptionVerifyAttribute(string verificationToken)
{
VerificationToken = verificationToken;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.ContentType = "text/plain";
var request = filterContext.HttpContext.Request;
var modelState = filterContext.Controller.ViewData.ModelState;
string errorMessage;
if (request.HttpMethod == "GET")
{
if (string.IsNullOrEmpty(VerificationToken))
{
errorMessage = "Verification Token is empty.";
}
else
{
if (FacebookSubscriptionVerifier.VerifyGetSubscription(request, VerificationToken, out errorMessage))
{
return;
}
}
}
else
{
errorMessage = "Invalid http method.";
}
modelState.AddModelError("facebook-subscription", errorMessage);
filterContext.HttpContext.Response.StatusCode = 401;
}
}
}
And the code for the FacebookSubscriptionVerifier Class
namespace Facebook.Web
{
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
/// <summary>
/// Facebook helper methods for web.
/// </summary>
internal static class FacebookSubscriptionVerifier
{
internal const string HTTP_X_HUB_SIGNATURE_KEY = "HTTP_X_HUB_SIGNATURE";
internal static byte[] ComputeHmacSha1Hash(byte[] data, byte[] key)
{
Contract.Requires(data != null);
Contract.Requires(key != null);
Contract.Ensures(Contract.Result<byte[]>() != null);
using (var crypto = new System.Security.Cryptography.HMACSHA1(key))
{
return crypto.ComputeHash(data);
}
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE.
/// </summary>
/// <param name="secret">
/// The secret.
/// </param>
/// <param name="httpXHubSignature">
/// The http x hub signature.
/// </param>
/// <param name="jsonString">
/// The json string.
/// </param>
/// <returns>
/// Returns true if validation is successful.
/// </returns>
internal static bool VerifyHttpXHubSignature(string secret, string httpXHubSignature, string jsonString)
{
Contract.Requires(!string.IsNullOrEmpty(secret));
if (!string.IsNullOrEmpty(httpXHubSignature) && httpXHubSignature.StartsWith("sha1=") && httpXHubSignature.Length > 5 && !string.IsNullOrEmpty(jsonString))
{
// todo: test inner parts
var expectedSignature = httpXHubSignature.Substring(5);
var sha1 = ComputeHmacSha1Hash(Encoding.UTF8.GetBytes(jsonString), Encoding.UTF8.GetBytes(secret));
var hashString = new StringBuilder();
foreach (var b in sha1)
{
hashString.Append(b.ToString("x2"));
}
if (expectedSignature == hashString.ToString())
{
return true;
}
}
return false;
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE for http GET method.
/// </summary>
/// <param name="request">
/// The http request.
/// </param>
/// <param name="verifyToken">
/// The verify token.
/// </param>
/// <param name="errorMessage">
/// The error message.
/// </param>
/// <returns>
/// Returns true if successful otherwise false.
/// </returns>
internal static bool VerifyGetSubscription(HttpRequestBase request, string verifyToken, out string errorMessage)
{
Contract.Requires(request != null);
Contract.Requires(request.HttpMethod == "GET");
Contract.Requires(request.Params != null);
Contract.Requires(!string.IsNullOrEmpty(verifyToken));
errorMessage = null;
if (request.Params["hub.mode"] == "subscribe")
{
if (request.Params["hub.verify_token"] == verifyToken)
{
if (string.IsNullOrEmpty(request.Params["hub.challenge"]))
{
errorMessage = Properties.Resources.InvalidHubChallenge;
}
else
{
return true;
}
}
else
{
errorMessage = Properties.Resources.InvalidVerifyToken;
}
}
else
{
errorMessage = Properties.Resources.InvalidHubMode;
}
return false;
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE for http POST method.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
/// <param name="secret">
/// The secret.
/// </param>
/// <param name="jsonString">
/// The json string.
/// </param>
/// <param name="errorMessage">
/// The error message.
/// </param>
/// <returns>
/// Returns true if successful otherwise false.
/// </returns>
internal static bool VerifyPostSubscription(HttpRequestBase request, string secret, string jsonString, out string errorMessage)
{
Contract.Requires(request != null);
Contract.Requires(request.HttpMethod == "POST");
Contract.Requires(request.Params != null);
Contract.Requires(!string.IsNullOrEmpty(secret));
errorMessage = null;
// signatures looks somewhat like "sha1=4594ae916543cece9de48e3289a5ab568f514b6a"
var signature = request.Params["HTTP_X_HUB_SIGNATURE"];
if (!string.IsNullOrEmpty(signature) && signature.StartsWith("sha1="))
{
var expectedSha1 = signature.Substring(5);
if (string.IsNullOrEmpty(expectedSha1))
{
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
else
{
if (string.IsNullOrEmpty(jsonString))
{
errorMessage = Properties.Resources.InvalidJsonString;
return false;
}
var sha1 = ComputeHmacSha1Hash(Encoding.UTF8.GetBytes(jsonString), Encoding.UTF8.GetBytes(secret));
var hashString = new StringBuilder();
foreach (var b in sha1)
{
hashString.Append(b.ToString("x2"));
}
if (expectedSha1 == hashString.ToString())
{
// todo: test
return true;
}
// todo: test
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
}
else
{
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
return false;
}
}
}

How to create a console window from a console window on Windows?

I have a console program that needs read the window messages, but since can not be subclassed a window that belongs to another process, how to create a new console window?
I have tried to use AllocConsole but it shows the error: "Access is denied"
From the MSDN documentation for AllocConsole:
A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console.
So you need to call FreeConsole before calling AllocConsole.
I have developed this code for use in my projects. I hope here is all you need and more :)
/// <summary>
/// Smart Console powered by Gregor Primar s.p.
/// </summary>
public class ConsoleWindow
{
#region EXTERNALL DLL CALLS
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeConsole();
[DllImport("user32.dll")]
static extern IntPtr RemoveMenu(IntPtr hMenu, uint nPosition, uint wFlags);
[DllImport("user32.dll")]
static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
[DllImport("user32.dll")]
static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
internal const UInt32 SC_CLOSE = 0xF060;
internal const UInt32 MF_GRAYED = 0x00000001;
internal const UInt32 MF_ENABLED = 0x00000000;
internal const uint MF_BYCOMMAND = 0x00000000;
#endregion
#region PROPERTIES
/// <summary>
/// Gets if console window is displayed
/// </summary>
public bool Displayed { get; internal set; }
/// <summary>
/// Gets or Sets console background color
/// </summary>
public ConsoleColor BackgroundColor
{
get
{
return Console.BackgroundColor;
}
set
{
Console.BackgroundColor = value;
}
}
/// <summary>
/// Gets or Sets console foreground color
/// </summary>
public ConsoleColor ForegroundColor
{
get
{
return Console.ForegroundColor;
}
set
{
Console.ForegroundColor = value;
}
}
/// <summary>
/// Gets or Sets
/// </summary>
public ConsoleColor ForegroundErrorColor { get; set; }
#endregion
#region WRITE AND READ METHODES
/// <summary>
/// Clears console window
/// </summary>
public void Clear()
{
Console.Clear();
}
/// <summary>
/// Writes to console with ForegroundColor
/// </summary>
/// <param name="value"></param>
public void Write(string value)
{
Write(value, false);
}
/// <summary>
/// Writes to console with ForegroundColor or ForegroundErrorColor
/// </summary>
/// <param name="value"></param>
/// <param name="isError"></param>
public void Write(string value, bool isError)
{
Write_internal(value, isError, false);
}
/// <summary>
/// Writes blank line to console with ForegroundColor
/// </summary>
public void WriteLine()
{
this.WriteLine("");
}
/// <summary>
/// Writes to console with ForegroundColor
/// </summary>
/// <param name="value"></param>
public void WriteLine(string value)
{
WriteLine(value, false);
}
/// <summary>
/// Writes line to console with ForegroundColor or ForegroundErrorColor
/// </summary>
/// <param name="value"></param>
/// <param name="isError"></param>
public void WriteLine(string value, bool isError)
{
Write_internal(value, isError, true);
}
void Write_internal(string value, bool isError, bool fullLine)
{
ConsoleColor defaultColor = this.ForegroundColor;
if (isError)
{
this.ForegroundColor = this.ForegroundErrorColor;
}
if (fullLine)
{
Console.WriteLine(value);
}
else
{
Console.Write(value);
}
this.ForegroundColor = defaultColor;
}
void ReadLine_internal(Type type, bool allowNull, ref object returnValue, StringDictionary options)
{
if ((options != null) && (type != typeof(string)))
{
throw new Exception("ReadLine_internal allows options only when type is string!");
}
string currentValue = null;
string errorMessage = null;
do
{
currentValue = Console.ReadLine();
if (allowNull && currentValue == "")
{
returnValue = null;
break;
}
//probaj za točno določen tip...
bool typeResolved = false;
if (type == typeof(string))
{
typeResolved = true;
if (currentValue != "")
{
if (options != null)
{
foreach (DictionaryEntry option in options)
{
if (option.Key.ToString() == currentValue)
{
returnValue = currentValue;
return;
}
}
errorMessage = "Enter one of possible options!";
}
else
{
returnValue = currentValue;
return;
}
}
else
{
errorMessage = "String value is required!";
}
}
if (type == typeof(int?))
{
typeResolved = true;
int iVal = 0;
if (int.TryParse(currentValue, out iVal))
{
returnValue = iVal;
return;
}
errorMessage = "Int value is required!";
}
if (type == typeof(decimal?))
{
typeResolved = true;
decimal dVal = 0;
if (decimal.TryParse(currentValue, out dVal))
{
returnValue = dVal;
return;
}
errorMessage = "Decimal value is required!";
}
if (type == typeof(DateTime?))
{
typeResolved = true;
DateTime dtVal = new DateTime();
if (DateTime.TryParse(currentValue, out dtVal))
{
returnValue = dtVal;
return;
}
errorMessage = "DateTime value is required!";
}
if (typeResolved == false)
{
throw new Exception("Type='" + type.ToString() + "' not supported in ReadLine_internal void!");
}
this.WriteLine(errorMessage, true);
} while (1 == 1);
}
/// <summary>
/// Reads line from user input and returns string
/// </summary>
/// <returns></returns>
public string ReadLine()
{
return this.ReadLine(true);
}
/// <summary>
/// Reads line from user input and returns string
/// </summary>
/// <returns></returns>
public string ReadLine(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(string), allowNull, ref returnValue, null);
if (returnValue != null)
{
return returnValue.ToString();
}
else
{
return null;
}
}
/// <summary>
/// Reads line from user input and returns nullable integer
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public int? ReadLineAsInt(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(int?), allowNull, ref returnValue, null);
return (int?)returnValue;
}
/// <summary>
/// Reads line from user input and returns nullable decimal
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public decimal? ReadLineAsDecimal(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(decimal?), allowNull, ref returnValue, null);
return (decimal?)returnValue;
}
/// <summary>
/// Reads line from user input and returns nullable datetime
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public DateTime? ReadLineDateTime(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(DateTime?), allowNull, ref returnValue, null);
return (DateTime?)returnValue;
}
/// <summary>
/// Reads line from user input and returns string from options list
/// </summary>
/// <param name="options"></param>
/// <param name="allowNull"></param>
/// <returns></returns>
public string ReadLineAsOption(StringDictionary options, bool allowNull)
{
if (options != null)
{
if (options.Count == 0)
{
throw new Exception("Options list can not be empty! You can pass only null or unempty options list!");
}
else
{
this.WriteLine("Enter one of following options:");
foreach (DictionaryEntry de in options)
{
string description = null;
if (de.Value != null)
{
description = de.Value.ToString();
}
string userLine = "[" + de.Key.ToString() + "]";
if (description != null)
{
userLine += " " + description;
}
this.WriteLine(userLine);
}
}
}
object returnValue = null;
ReadLine_internal(typeof(string), allowNull, ref returnValue, options);
if (returnValue != null)
{
return returnValue.ToString();
}
else
{
return null;
}
}
#endregion
const string consoleTitle = "Smart Console powered by Gregor Primar s.p.";
/// <summary>
/// Default constructor
/// </summary>
public ConsoleWindow()
{
}
/// <summary>
/// Set focus to console window
/// </summary>
public void SetFocus()
{
if (this.Displayed)
{
SetConsoleFocus();
}
else
{
throw new Exception("Unable to SetFocus because console is not displayed!");
}
}
/// <summary>
/// Opens console window
/// </summary>
public void Open()
{
if (this.Displayed == false)
{
AllocConsole();
Console.Title = consoleTitle;
//onemogoči zapiranje konzole...
ChangeConsoleMenu(false);
this.Displayed = true;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
//nastavi default barve...
this.BackgroundColor = ConsoleColor.DarkBlue;
this.ForegroundColor = ConsoleColor.White;
this.ForegroundErrorColor = ConsoleColor.Red;
this.Clear();
this.SetFocus();
}
else
{
throw new Exception("Console window is allready opened!");
}
}
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
}
/// <summary>
/// Closes console window
/// </summary>
public void Close()
{
if (this.Displayed)
{
Console.CancelKeyPress -= Console_CancelKeyPress;
ChangeConsoleMenu(true);
FreeConsole();
this.Displayed = false;
}
else
{
throw new Exception("Can not close console window because its not displayed!");
}
}
void ChangeConsoleMenu(bool enabled)
{
IntPtr hConsole = FindConsoleHandle();
IntPtr hMenu = FindMenuHandle(hConsole);
uint value = MF_ENABLED;
if (enabled == false)
{
value = MF_GRAYED;
}
EnableMenuItem(hMenu, SC_CLOSE, value);
}
void SetConsoleFocus()
{
IntPtr hConsole = FindConsoleHandle();
while (true)
{
if (SetForegroundWindow(hConsole))
{
break;
}
Thread.Sleep(50);
}
}
/// <summary>
/// Finds handle to console window
/// </summary>
/// <returns></returns>
IntPtr FindConsoleHandle()
{
string originalTitle = Console.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Console.Title = uniqueTitle;
Thread.Sleep(50);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero)
{
Console.Title = originalTitle;
throw new Exception("Unable to find console window!");
}
Console.Title = originalTitle;
return handle;
}
/// <summary>
/// Finds handle to main menu
/// </summary>
/// <param name="windowHandle"></param>
/// <returns></returns>
IntPtr FindMenuHandle(IntPtr windowHandle)
{
IntPtr hSystemMenu = GetSystemMenu(windowHandle, false);
return hSystemMenu;
}
}
And sample code how to use this class:
ConsoleWindow cw = new ConsoleWindow();
cw.Open();
cw.WriteLine("Some text displayed on smart console", true);

Resources