Get current Android activity in MAUI android (net6-android) library - android-activity

I have a library for Xamarin.Forms (Android) allowing to use NFC, with this code :
public class MediaAccessReader : Java.Lang.Object, NfcAdapter.IReaderCallback
{
public const string TypeName = "Nfc";
private static NfcAdapter NfcAdapter { get; } = NfcAdapter.GetDefaultAdapter(Android.App.Application.Context);
public string Name { get; set; }
public void Initialize(MediaAddedEventHandler mediaAdded, MediaRemovedEventHandler mediaRemoved)
{
Name = "Nfc";
#if XAMARINANDROID
var activity = Forms.Context as Activity;
NfcAdapter?.EnableReaderMode(activity, this, NfcReaderFlags.NfcA | NfcReaderFlags.NfcB | NfcReaderFlags.NfcF | NfcReaderFlags.NfcV | NfcReaderFlags.SkipNdefCheck, Bundle.Empty);
#else
var activity = ?????????????????;
NfcAdapter?.EnableReaderMode(activity , this, NfcReaderFlags.NfcA | NfcReaderFlags.NfcB | NfcReaderFlags.NfcF | NfcReaderFlags.NfcV | NfcReaderFlags.SkipNdefCheck, Bundle.Empty);
#endif
MediaAdded += mediaAdded;
MediaRemoved += mediaRemoved;
}
}
How could I replace the var activity = Forms.Context as Activity line to get the current activity and be able to call NfcAdapter?.EnableReaderMode without Xamarin Forms ?
Otherwise, is there another solution ?

It's include inside Xamarin.Essentials
Xamarin.Essentials.Platform.CurrentActivity
Essentials has been ported to .Net Maui
Platform.CurrentActivity

I ended up using this solution : https://gist.github.com/BrunoVT1992/8c858e4fed85d5dd96098c012a6e0708
using System.Collections.Generic;
using System.Linq;
using Android.Runtime;
using Android.Util;
using Java.Lang;
using Java.Util;
namespace Droid
{
public static class CurrentActivityUtil
{
/// <summary>
/// Gets the current activity of the application (must run on the UI thread for older Android versions).
/// </summary>
/// <returns>The current activity.</returns>
/// <param name="app">App.</param>
public static Activity GetCurrentActivity()
{
Activity activity = null;
List<Object> objects = null;
var activityThreadClass = Class.ForName("android.app.ActivityThread");
var activityThread = activityThreadClass.GetMethod("currentActivityThread").Invoke(null);
var activityFields = activityThreadClass.GetDeclaredField("mActivities");
activityFields.Accessible = true;
var obj = activityFields.Get(activityThread);
if (obj is JavaDictionary)
{
var activities = (JavaDictionary)obj;
objects = new List<Object>(activities.Values.Cast<Object>().ToList());
}
else if (obj is ArrayMap)
{
var activities = (ArrayMap)obj;
objects = new List<Object>(activities.Values().Cast<Object>().ToList());
}
else if (obj is IMap)
{
var activities = (IMap)activityFields.Get(activityThread);
objects = new List<Object>(activities.Values().Cast<Object>().ToList());
}
if (objects != null && objects.Any())
{
foreach (var activityRecord in objects)
{
var activityRecordClass = activityRecord.Class;
var pausedField = activityRecordClass.GetDeclaredField("paused");
pausedField.Accessible = true;
if (!pausedField.GetBoolean(activityRecord))
{
var activityField = activityRecordClass.GetDeclaredField("activity");
activityField.Accessible = true;
activity = (Activity)activityField.Get(activityRecord);
break;
}
}
}
return activity;
}
}
}

Related

Showing ScriptableObjects in multi selection dropdown menu in Unity

How should I create PropertyAttribute and PropertyDrawer to show ScriptableObjects in dropdown menu in Inspector for multi selecting ?
I've published a repository on Github which solve this problem. It is for multi selecting in dropdown menu in Inspector.
In Github links you have access to example folder and unitypackage in release page but if you don't want to go to the links or any problem happens to the links, you can follow this instruction:
ScriptableObjectMultiSelectDropdown:
ScriptableObjectMultiSelectDropdown is an attribute for the Unity Inspector.
It is used for showing ScriptableObjects which are created in your project, in dropdown menu and select multiple of them in Inspector.
Code:
ScriptableObjectReference.cs:
// Copyright (c) ATHellboy (Alireza Tarahomi) Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using UnityEngine;
namespace ScriptableObjectMultiSelectDropdown
{
/// <summary>
/// Because you can't make a PropertyDrawer for arrays or generic lists themselves,
/// I had to create parent class as an abstract layer.
/// </summary>
[Serializable]
public class ScriptableObjectReference
{
public ScriptableObject[] values;
}
}
ScriptableObjectMultiSelectDropdownAttribute.cs:
// Copyright (c) ATHellboy (Alireza Tarahomi) Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using UnityEngine;
namespace ScriptableObjectMultiSelectDropdown
{
/// <summary>
/// Indicates how selectable scriptableObjects should be collated in drop-down menu.
/// </summary>
public enum ScriptableObjectGrouping
{
/// <summary>
/// No grouping, just show type names in a list; for instance, "MainFolder > NestedFolder > SpecialScriptableObject".
/// </summary>
None,
/// <summary>
/// Group classes by namespace and show foldout menus for nested namespaces; for
/// instance, "MainFolder >> NestedFolder >> SpecialScriptableObject".
/// </summary>
ByFolder,
/// <summary>
/// Group scriptableObjects by folder; for instance, "MainFolder > NestedFolder >> SpecialScriptableObject".
/// </summary>
ByFolderFlat
}
/// <example>
/// <para>Usage Examples</para>
/// <code language="csharp"><![CDATA[
/// using UnityEngine;
/// using ScriptableObjectDropdown;
///
/// [CreateAssetMenu(menuName = "Create Block")]
/// public class Block : ScriptableObject
/// {
/// // Some fields
/// }
///
/// public class BlockManager : MonoBehaviour
/// {
/// [ScriptableObjectMultiSelectDropdown(typeof(Block))]
/// public ScriptableObjectReference firstTargetBlocks;
///
/// // or
///
/// [ScriptableObjectMultiSelectDropdown(typeof(Block), grouping = ScriptableObjectGrouping.ByFolder)]
/// public ScriptableObjectReference secondTargetBlocks;
/// }
///
/// // or
///
/// [CreateAssetMenu(menuName = "Create Block Manager Settings")]
/// public class BlockManagerSetting : ScriptableObject
/// {
/// [ScriptableObjectMultiSelectDropdown(typeof(Block))]
/// public ScriptableObjectReference firstTargetBlocks;
///
/// // or
///
/// [ScriptableObjectMultiSelectDropdown(typeof(Block), grouping = ScriptableObjectGrouping.ByFolderFlat)]
/// public ScriptableObjectReference secondTargetBlocks;
/// }
/// ]]></code>
/// </example>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class ScriptableObjectMultiSelectDropdownAttribute : PropertyAttribute
{
public ScriptableObjectGrouping grouping = ScriptableObjectGrouping.None;
private Type _baseType;
public Type BaseType
{
get { return _baseType; }
private set { _baseType = value; }
}
public ScriptableObjectMultiSelectDropdownAttribute(Type baseType)
{
_baseType = baseType;
}
}
}
Put this one in Editor folder:
ScriptableObjectMultiSelectionDropdownDrawer.cs:
// Copyright (c) ATHellboy (Alireza Tarahomi) Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System.Linq;
namespace ScriptableObjectMultiSelectDropdown.Editor
{
// TODO: Mixed value (-) for selecting multi objects
[CustomPropertyDrawer(typeof(ScriptableObjectReference))]
[CustomPropertyDrawer(typeof(ScriptableObjectMultiSelectDropdownAttribute))]
public class ScriptableObjectMultiSelectionDropdownDrawer : PropertyDrawer
{
private static ScriptableObjectMultiSelectDropdownAttribute _attribute;
private static List<ScriptableObject> _scriptableObjects = new List<ScriptableObject>();
private static List<ScriptableObject> _selectedScriptableObjects = new List<ScriptableObject>();
private static readonly int _controlHint = typeof(ScriptableObjectMultiSelectDropdownAttribute).GetHashCode();
private static GUIContent _popupContent = new GUIContent();
private static int _selectionControlID;
private static readonly GenericMenu.MenuFunction2 _onSelectedScriptableObject = OnSelectedScriptableObject;
private static bool isChanged;
static ScriptableObjectMultiSelectionDropdownDrawer()
{
EditorApplication.projectChanged += ClearCache;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
ScriptableObjectMultiSelectDropdownAttribute castedAttribute = attribute as ScriptableObjectMultiSelectDropdownAttribute;
if (_scriptableObjects.Count == 0)
{
GetScriptableObjects(castedAttribute);
}
Draw(position, label, property, castedAttribute);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorStyles.popup.CalcHeight(GUIContent.none, 0);
}
/// <summary>
/// How you can get type of field which it uses PropertyAttribute
/// </summary>
private static Type GetPropertyType(SerializedProperty property)
{
Type parentType = property.serializedObject.targetObject.GetType();
FieldInfo fieldInfo = parentType.GetField(property.propertyPath);
if (fieldInfo != null)
{
return fieldInfo.FieldType;
}
return null;
}
private static bool ValidateProperty(SerializedProperty property)
{
Type propertyType = GetPropertyType(property);
if (propertyType == null)
{
return false;
}
if (propertyType != typeof(ScriptableObjectReference))
{
return false;
}
return true;
}
/// <summary>
/// When new ScriptableObject added to the project
/// </summary>
private static void ClearCache()
{
_scriptableObjects.Clear();
}
/// <summary>
/// Gets ScriptableObjects just when it is a first time or new ScriptableObject added to the project
/// </summary>
private static void GetScriptableObjects(ScriptableObjectMultiSelectDropdownAttribute attribute)
{
string[] guids = AssetDatabase.FindAssets(String.Format("t:{0}", attribute.BaseType));
for (int i = 0; i < guids.Length; i++)
{
_scriptableObjects.Add(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[i]), attribute.BaseType) as ScriptableObject);
}
}
/// <summary>
/// Checks if the ScriptableObject is selected or not by checking if the list contains it.
/// </summary>
private static bool ResolveSelectedScriptableObject(ScriptableObject scriptableObject)
{
if (_selectedScriptableObjects == null)
{
return false;
}
return _selectedScriptableObjects.Contains(scriptableObject);
}
private static void Draw(Rect position, GUIContent label,
SerializedProperty property, ScriptableObjectMultiSelectDropdownAttribute attribute)
{
if (label != null && label != GUIContent.none)
position = EditorGUI.PrefixLabel(position, label);
if (ValidateProperty(property))
{
if (_scriptableObjects.Count != 0)
{
UpdateScriptableObjectSelectionControl(position, label, property.FindPropertyRelative("values"), attribute);
}
else
{
EditorGUI.LabelField(position, "There is no this type asset in the project");
}
}
else
{
EditorGUI.LabelField(position, "Use it with ScriptableObjectReference");
}
}
/// <summary>
/// Iterats through the property for finding selected ScriptableObjects
/// </summary>
private static ScriptableObject[] Read(SerializedProperty property)
{
List<ScriptableObject> selectedScriptableObjects = new List<ScriptableObject>();
SerializedProperty iterator = property.Copy();
SerializedProperty end = iterator.GetEndProperty();
while (!SerializedProperty.EqualContents(iterator, end) && iterator.Next(true))
{
if (iterator.propertyType == SerializedPropertyType.ObjectReference)
{
selectedScriptableObjects.Add(iterator.objectReferenceValue as ScriptableObject);
}
}
return selectedScriptableObjects.ToArray();
}
/// <summary>
/// Iterats through the property for storing selected ScriptableObjects
/// </summary>
private static void Write(SerializedProperty property, ScriptableObject[] scriptableObjects)
{
// Faster way
// var w = new System.Diagnostics.Stopwatch();
// w.Start();
int i = 0;
SerializedProperty iterator = property.Copy();
iterator.arraySize = scriptableObjects.Length;
SerializedProperty end = iterator.GetEndProperty();
while (!SerializedProperty.EqualContents(iterator, end) && iterator.Next(true))
{
if (iterator.propertyType == SerializedPropertyType.ObjectReference)
{
iterator.objectReferenceValue = scriptableObjects[i];
i++;
}
}
// w.Stop();
// long milliseconds = w.ElapsedMilliseconds;
// Debug.Log(w.Elapsed.TotalMilliseconds + " ms");
// Another way
// property.arraySize = scriptableObjects.Length;
// for (int i = 0; i < property.arraySize; i++)
// {
// property.GetArrayElementAtIndex(i).objectReferenceValue = scriptableObjects[i];
// }
}
private static void UpdateScriptableObjectSelectionControl(Rect position, GUIContent label,
SerializedProperty property, ScriptableObjectMultiSelectDropdownAttribute attribute)
{
ScriptableObject[] output = DrawScriptableObjectSelectionControl(position, label, Read(property), property, attribute);
if (isChanged)
{
isChanged = false;
Write(property, output);
}
}
private static ScriptableObject[] DrawScriptableObjectSelectionControl(Rect position, GUIContent label,
ScriptableObject[] scriptableObjects, SerializedProperty property, ScriptableObjectMultiSelectDropdownAttribute attribute)
{
bool triggerDropDown = false;
int controlID = GUIUtility.GetControlID(_controlHint, FocusType.Keyboard, position);
switch (Event.current.GetTypeForControl(controlID))
{
case EventType.ExecuteCommand:
if (Event.current.commandName == "ScriptableObjectReferenceUpdated")
{
if (_selectionControlID == controlID)
{
if (scriptableObjects != _selectedScriptableObjects.ToArray())
{
scriptableObjects = _selectedScriptableObjects.ToArray();
isChanged = true;
}
_selectionControlID = 0;
_selectedScriptableObjects = null;
}
}
break;
case EventType.MouseDown:
if (GUI.enabled && position.Contains(Event.current.mousePosition))
{
GUIUtility.keyboardControl = controlID;
triggerDropDown = true;
Event.current.Use();
}
break;
case EventType.KeyDown:
if (GUI.enabled && GUIUtility.keyboardControl == controlID)
{
if (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Space)
{
triggerDropDown = true;
Event.current.Use();
}
}
break;
case EventType.Repaint:
if (scriptableObjects.Length == 0)
{
_popupContent.text = "Nothing";
}
else if (scriptableObjects.Length == _scriptableObjects.Count)
{
_popupContent.text = "Everything";
}
else if (scriptableObjects.Length >= 2)
{
_popupContent.text = "Mixed ...";
}
else
{
_popupContent.text = scriptableObjects[0].name;
}
EditorStyles.popup.Draw(position, _popupContent, controlID);
break;
}
if (triggerDropDown)
{
_selectionControlID = controlID;
_selectedScriptableObjects = scriptableObjects.ToList();
DisplayDropDown(position, scriptableObjects, attribute.grouping);
}
return scriptableObjects;
}
private static void DisplayDropDown(Rect position, ScriptableObject[] selectedScriptableObject, ScriptableObjectGrouping grouping)
{
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Nothing"), selectedScriptableObject.Length == 0, _onSelectedScriptableObject, null);
menu.AddItem(new GUIContent("Everything"),
(_scriptableObjects.Count != 0 && selectedScriptableObject.Length == _scriptableObjects.Count),
_onSelectedScriptableObject, _scriptableObjects.ToArray());
for (int i = 0; i < _scriptableObjects.Count; ++i)
{
var scriptableObject = _scriptableObjects[i];
string menuLabel = MakeDropDownGroup(scriptableObject, grouping);
if (string.IsNullOrEmpty(menuLabel))
continue;
var content = new GUIContent(menuLabel);
menu.AddItem(content, ResolveSelectedScriptableObject(scriptableObject), _onSelectedScriptableObject, scriptableObject);
}
menu.DropDown(position);
}
private static void OnSelectedScriptableObject(object userData)
{
if (userData == null)
{
_selectedScriptableObjects.Clear();
}
else if (userData.GetType().IsArray)
{
_selectedScriptableObjects = (userData as ScriptableObject[]).ToList();
}
else
{
ScriptableObject scriptableObject = userData as ScriptableObject;
if (!ResolveSelectedScriptableObject(scriptableObject))
{
_selectedScriptableObjects.Add(scriptableObject);
}
else
{
_selectedScriptableObjects.Remove(scriptableObject);
}
}
var scriptableObjectReferenceUpdatedEvent = EditorGUIUtility.CommandEvent("ScriptableObjectReferenceUpdated");
EditorWindow.focusedWindow.SendEvent(scriptableObjectReferenceUpdatedEvent);
}
private static string FindScriptableObjectFolderPath(ScriptableObject scriptableObject)
{
string path = AssetDatabase.GetAssetPath(scriptableObject);
path = path.Replace("Assets/", "");
path = path.Replace(".asset", "");
return path;
}
private static string MakeDropDownGroup(ScriptableObject scriptableObject, ScriptableObjectGrouping grouping)
{
string path = FindScriptableObjectFolderPath(scriptableObject);
switch (grouping)
{
default:
case ScriptableObjectGrouping.None:
path = path.Replace("/", " > ");
return path;
case ScriptableObjectGrouping.ByFolder:
return path;
case ScriptableObjectGrouping.ByFolderFlat:
int last = path.LastIndexOf('/');
string part1 = path.Substring(0, last);
string part2 = path.Substring(last);
path = part1.Replace("/", " > ") + part2;
return path;
}
}
}
}
Usage Example:
Create ScriptableObject class which you want to create specified objects by that.
using UnityEngine;
[CreateAssetMenu(menuName = "Create Block")]
public class Block : ScriptableObject
{
// Some fields
}
Create ScriptableObjects in the project.
Use ScriptableObjectMultiSelectDropdown attribute by setting type of specified ScriptableObject derived class and optional grouping (Default grouping is None) like this in MonoBeahviour or ScriptableObject derived classes.
MonoBehavior:
using ScriptableObjectMultiSelectDropdown;
using UnityEngine;
public class BlockManager : MonoBehaviour
{
// Without grouping (default is None)
[ScriptableObjectMultiSelectDropdown(typeof(Block))]
public ScriptableObjectReference firstTargetBlocks;
// By grouping
[ScriptableObjectMultiSelectDropdown(typeof(Block), grouping = ScriptableObjectGrouping.ByFolder)]
public ScriptableObjectReference secondTargetBlocks;
}
ScriptableObject:
using UnityEngine;
using ScriptableObjectMultiSelectDropdown;
[CreateAssetMenu(menuName = "Create Block Manager Settings")]
public class BlockManagerSettings : ScriptableObject
{
// Without grouping (default is None)
[ScriptableObjectMultiSelectDropdown(typeof(Block))]
public ScriptableObjectReference firstTargetBlocks;
// By grouping
[ScriptableObjectMultiSelectDropdown(typeof(Block), grouping = ScriptableObjectGrouping.ByFolderFlat)]
public ScriptableObjectReference secondTargetBlocks;
}

Viewmodel not updating model after add or insert to list

I'm fairly new to MVVM and Entity framework and I've hit a problem trying to add new records to my SQL database through MVVM. Below is the first and last part of my viewmodel which loads from my entity framework and this is working fine.
internal class MainWindowViewModel : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
private TEAMSEntities ctx = new TEAMSEntities();
public MainWindowViewModel()
{
FillSales();
}
public void AddASale()
{
Tbl_Sales newsale = new Tbl_Sales();
newsale.SALEID = "2018...";
newsale.SALE = "....";
newsale.SALEDESC = "....";
newsale.START = Convert.ToDateTime("12/04/2018");
newsale.SESSIONS = 2;
newsale.DAYS = 2;
newsale.LOTS = 100;
newsale.FIRSTLOT = 1;
newsale.LASTLOT = 100;
Sales.Add(newsale);
SaveChanges();
}
#region Sale
private void FillSales()
{
var q = (from a in ctx.Tbl_Sales
select a).ToList();
this.Sales = q;
}
private List<Tbl_Sales> _sales;
public List<Tbl_Sales> Sales
{
get
{
return _sales;
}
set
{
_sales = value;
NotifyPropertyChanged();
}
}
private Tbl_Sales _selectedSale;
public Tbl_Sales SelectedSale
{
get
{
return _selectedSale;
}
set
{
_selectedSale = value;
NotifyPropertyChanged();
}
}
#endregion Sale
.
.
.
.
public void SaveChanges()
{
ctx.SaveChanges();
}
private void NotifyPropertyChanged([CallerMemberName] String
propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void Dispose()
{
((IDisposable)ctx).Dispose();
}
}
When I make changes to existing data in the view bound to the viewmodel and call the SaveChanges method in the viewmodel it saves the change back to the SQL database every time. If I call the AddASale method it adds that sale to the list but doesn't refresh the UI control bound to Sales and doesn't pass the newly created sale back to the SQL DB. Through debugging I can see the set being called in the Sales property when the LINQ code runs but it doesn't fire when I add a new sale through the AddASale code which is probably why the UI isn't updating...?
Can anyone offer any guidance as to what I'm doing wrong?
Thanks in advance.
Alex
First, add your new entity in your context and save it like this :
Tbl_Sales newsale = new Tbl_Sales
{
SALEID = "2018...",
SALE = "....",
SALEDESC = "....",
START = Convert.ToDateTime("12/04/2018"),
SESSIONS = 2,
DAYS = 2,
LOTS = 100,
FIRSTLOT = 1,
LASTLOT = 100
};
ctx.Tbl_Sales.Add(newsale);
SaveChanges();
after that, I think you have to refresh your list manually :
FillSales();
Here, a link to MSDN
Hope I helped you

How to get actual value and validate of CustomTextbox Text in ViewModel

I have created custom component for displaying text with either Simple or Password mode, intention to develop this control is the Silverlight does not support custom TextMode (like Password or Text).
This is my requirement
In addition to the access rights it will be possible for organizations to specify restricted access to certain fields in the database. The access restriction to these fields will be Update and Redacted, thus meaning if a specific field has true against Update then a user will be able to update the field as well as viewing it, and if the field has true against Redacted then the user will only be able to see a redacted value in the filed (possibly asterisks - * * * * *). It will be possible to set a field to being Update-able and Redacted, thus meaning a user will see the redacted view but still be able to go and update the field with a new value. Such a requirement is mostly used when holding sensitive information against a contact or information which could be used to discriminate against the contact.
I have created custom control for this requirement and it is working perfectly. i am able to set TextMode dynamically but i couldn't able to get the original value in my ViewModel. (I am able to get original value in View but can't in ViewModel)
If i am access the original value in View using following then it is work.
string s = UserName.Text;
but not getting this value in ViewModel it is giving me like **.
Following is the complete code for PasswordTextBox control.
namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string text = string.Empty;
private string passwordChar = "*";
private int selectionLength = 0;
#endregion
#region Properties
/// <summary>
/// The text associated with the control.
/// </summary>
public new string Text
{
get { return text; }
set
{
text = value;
DisplayMaskedCharacters();
}
}
/// <summary>
/// Indicates the character to display for password input.
/// </summary>
public string PasswordChar
{
get { return passwordChar; }
set { passwordChar = value; }
}
/// <summary>
/// Indicates the input text mode to display for either text or password.
/// </summary>
public Mode TextMode
{
get { return (Mode)GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
public static readonly DependencyProperty TextModeProperty = DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
#endregion
#region Constructors
public PasswordTextBox()
{
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion
#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
if (this.TextMode == Mode.Password)
{
text = base.Text;
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new KeyEventHandler(PasswordTextBox_KeyDown);
this.SelectionChanged += new RoutedEventHandler(PasswordTextBox_SelectionChanged);
DisplayMaskedCharacters();
}
this.Loaded -= PasswordTextBox_Loaded;
}
void PasswordTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
selectionLength = this.SelectionLength;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= text.Length)
text += base.Text.Substring(text.Length);
else
{
int cursorPosition = this.SelectionStart;
selectionLength = (selectionLength > 1) ? selectionLength : 1;
text = text.Remove(cursorPosition, selectionLength);
}
DisplayMaskedCharacters();
selectionLength = 0;
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back && cursorPosition > 0)
{
DeleteAt(cursorPosition);
}
else if (e.Key == System.Windows.Input.Key.Delete)
{
DeleteAt(cursorPosition);
}
else
{
if (selectionLength > 0) text = text.Remove(cursorPosition, selectionLength);
base.Text = text;
this.Select((cursorPosition > text.Length ? text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
selectionLength = 0;
}
#endregion
#region Private Methods
private void DisplayMaskedCharacters()
{
int cursorPosition = this.SelectionStart;
// This changes the Text property of the base TextBox class to display all Asterisks in the control
base.Text = new string(passwordChar.ToCharArray()[0], text.Length);
this.Select((cursorPosition > text.Length ? text.Length : cursorPosition), 0);
}
private void DeleteAt(int position)
{
if (text.Length > position)
{
text = text.Remove(position, 1);
base.Text = base.Text.Remove(position, 1);
}
}
#endregion
}
}
LoginView.xaml
<control:PasswordTextBox x:Name="UserName" TabIndex="1" Grid.Row="1" TextMode="Password" Text="{Binding Path=LoginModelValue.UserName, Mode=TwoWay,ValidatesOnNotifyDataErrors=True, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Width="200" Height="25" Validatevalue:UpdateSourceTriggerHelper.UpdateSourceTrigger="True"/>
LoginViewModel.cs
public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime
{
public LoginModel LoginModelValue
{
get { return _LoginModelValue; }
set
{
_LoginModelValue = value;
OnPropertyChanged("LoginModelValue");
}
}
}
LoginModel.cs
namespace QSys.Model
{
public class LoginModel : INotifyPropertyChanged
{
#region Variables
private string _userName;
private string _password;
#endregion
#region Constructor
public LoginModel()
{
}
#endregion
#region Properties
[CustomValidation(typeof(PasswordTextBox), "IsValidUserName")]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "UserName")]
[StringLength(50)]
//[RegularExpression(#"^[a-zA-Z\\0-9\\.\\,\\'\s]+$", ErrorMessage = "Please enter right format.")]
public string UserName
{
get { return _userName; }
set
{
_userName = value;
OnPropertyChanged("UserName");
ValidateProperty("UserName", value);
}
}
[Required(ErrorMessage = "Password is required")]
[Display(Name = "Password")]
[StringLength(10)]
public string Password
{
get { return _password; }
set
{
_password = value;
OnPropertyChanged("Password");
ValidateProperty("Password", value);
}
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Private Methods
public bool IsValidObject()
{
ICollection<ValidationResult> results = new Collection<ValidationResult>();
return Validator.TryValidateObject(this, new ValidationContext(this, null, null), results, true) && results.Count == 0;
}
public void ValidateProperty(string propertyName, object value)
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName });
}
#endregion
}
}
**I am looking for solution since two days without any luck.
Please help me if you have any solution, your comments or suggestion would be highly appreciated.**
Thanks
Imdadhusen
Wouldn't it be easier to build your own UserControl around the regular TextBox and PasswordBox and just switching their visibility when your dependency property TextMode changes? You could then have a single VM for the UserControl with property Value and bind in TwoWay mode both the TextProperty of the TextBox and the Password property of the PasswordBox to it.
I have resolved using following code.
I am missing Mode=TwoWay in LoginView.xaml:
<control:RestrictedBox Type="Text" Value="{Binding Path=UserName,Mode=TwoWay}">
Thanks,
Imdadhusen

Error in Binding Custom Textbox Property

I have created custom Textbox in Silverlight 4, MVVM and PRISM 4. The custom text box has dynamic behavior link it dynamically set TextMode to either Password or Text.
This is working perfect. ( if i am bind TextMode static)
<control:PasswordTextBox x:Name="customTextBox2" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="Password"/>
This is giving me an error (if i am binding with dynamic)
<control:PasswordTextBox x:Name="customTextBox1" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="{Binding WritingMode}"/>
following is my ViewModel code
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class UserRightsViewModel : NotificationObject, IRegionMemberLifetime
{
private Mode _writingMode = Mode.Text;
public Mode WritingMode
{
get { return _writingMode; }
set
{
_writingMode = value; RaisePropertyChanged("WritingMode");
}
}
[ImportingConstructor]
public UserRightsViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
{
UserSecurity security = new UserSecurity();
FormSecurity formSecurity = security.GetSecurityList("Admin");
formSecurity.WritingMode = Mode.Password;
}
}
following is the enum
namespace QSys.Library.Enums
{
public enum Mode
{
Text,
Password
}
}
following code for Custom PasswordTextBox
namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string _Text = string.Empty;
private string _PasswordChar = "*";
private Mode _TextMode = Mode.Text;
#endregion
#region Properties
/// <summary>
/// The text associated with the control.
/// </summary>
public new string Text
{
get { return _Text; }
set
{
_Text = value;
DisplayMaskedCharacters();
}
}
/// <summary>
/// Indicates the character to display for password input.
/// </summary>
public string PasswordChar
{
get { return _PasswordChar; }
set { _PasswordChar = value; }
}
/// <summary>
/// Indicates the input text mode to display for either text or password.
/// </summary>
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
#endregion
#region Constructors
public PasswordTextBox()
{
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion
#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
//this.TextChanged += ImmediateTextBox_TextChanged;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= _Text.Length) _Text += base.Text.Substring(_Text.Length);
DisplayMaskedCharacters();
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
int selectionLength = this.SelectionLength;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back || e.Key == System.Windows.Input.Key.Delete)
{
if (cursorPosition < _Text.Length)
_Text = _Text.Remove(cursorPosition, (selectionLength > 0 ? selectionLength : 1));
}
base.Text = _Text;
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
#endregion
#region Private Methods
private void DisplayMaskedCharacters()
{
int cursorPosition = this.SelectionStart;
// This changes the Text property of the base TextBox class to display all Asterisks in the control
base.Text = new string(_PasswordChar.ToCharArray()[0], _Text.Length);
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
}
#endregion
#region Public Methods
#endregion
}
}
I am getting following error if i am binding with dynamically.
Set property 'QSys.Library.Controls.PasswordTextBox.TextMode' threw an exception. [Line: 40 Position: 144]
Your answer would be appreciated.
Thanks in advance.
Imdadhusen
Try to change in your PasswordTextBox class
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
to
public static readonly DependencyProperty TextModeProperty =
DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
public Mode TextMode
{
get { return (Mode) GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
You can read more here:
Dependency Properties Overview
DependencyProperty Class
The main paragraph from the second link is:
A DependencyProperty supports the following capabilities in Windows
Presentation Foundation (WPF):
....
The property can be set through data binding. For more information about data binding dependency properties, see How to: Bind the
Properties of Two Controls.
I provide links for WPF, but basically for Silverlight it's the same

Serializing Entity Framework problems

Like several other people, I'm having problems serializing Entity Framework objects, so that I can send the data over AJAX in a JSON format.
I've got the following server-side method, which I'm attempting to call using AJAX through jQuery
[WebMethod]
public static IEnumerable<Message> GetAllMessages(int officerId)
{
SIBSv2Entities db = new SIBSv2Entities();
return (from m in db.MessageRecipients
where m.OfficerId == officerId
select m.Message).AsEnumerable<Message>();
}
Calling this via AJAX results in this error:
A circular reference was detected while serializing an object of type \u0027System.Data.Metadata.Edm.AssociationType
Which is because of the way the Entity Framework creates circular references to keep all the objects related and accessible server side.
I came across the following code from (http://hellowebapps.com/2010-09-26/producing-json-from-entity-framework-4-0-generated-classes/) which claims to get around this problem by capping the maximum depth for references. I've added the code below, because I had to tweak it slightly to get it work (All angled brackets are missing from the code on the website)
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System;
public class EFObjectConverter : JavaScriptConverter
{
private int _currentDepth = 1;
private readonly int _maxDepth = 2;
private readonly List<int> _processedObjects = new List<int>();
private readonly Type[] _builtInTypes = new[]{
typeof(bool),
typeof(byte),
typeof(sbyte),
typeof(char),
typeof(decimal),
typeof(double),
typeof(float),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(short),
typeof(ushort),
typeof(string),
typeof(DateTime),
typeof(Guid)
};
public EFObjectConverter( int maxDepth = 2,
EFObjectConverter parent = null)
{
_maxDepth = maxDepth;
if (parent != null)
{
_currentDepth += parent._currentDepth;
}
}
public override object Deserialize( IDictionary<string,object> dictionary, Type type, JavaScriptSerializer serializer)
{
return null;
}
public override IDictionary<string,object> Serialize(object obj, JavaScriptSerializer serializer)
{
_processedObjects.Add(obj.GetHashCode());
Type type = obj.GetType();
var properties = from p in type.GetProperties()
where p.CanWrite &&
p.CanWrite &&
_builtInTypes.Contains(p.PropertyType)
select p;
var result = properties.ToDictionary(
property => property.Name,
property => (Object)(property.GetValue(obj, null)
== null
? ""
: property.GetValue(obj, null).ToString().Trim())
);
if (_maxDepth >= _currentDepth)
{
var complexProperties = from p in type.GetProperties()
where p.CanWrite &&
p.CanRead &&
!_builtInTypes.Contains(p.PropertyType) &&
!_processedObjects.Contains(p.GetValue(obj, null)
== null
? 0
: p.GetValue(obj, null).GetHashCode())
select p;
foreach (var property in complexProperties)
{
var js = new JavaScriptSerializer();
js.RegisterConverters(new List<JavaScriptConverter> { new EFObjectConverter(_maxDepth - _currentDepth, this) });
result.Add(property.Name, js.Serialize(property.GetValue(obj, null)));
}
}
return result;
}
public override IEnumerable<System.Type> SupportedTypes
{
get
{
return GetType().Assembly.GetTypes();
}
}
}
However even when using that code, in the following way:
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.RegisterConverters(new List<System.Web.Script.Serialization.JavaScriptConverter> { new EFObjectConverter(2) });
return js.Serialize(messages);
I'm still seeing the A circular reference was detected... exception being thrown!
I solved these issues with the following classes:
public class EFJavaScriptSerializer : JavaScriptSerializer
{
public EFJavaScriptSerializer()
{
RegisterConverters(new List<JavaScriptConverter>{new EFJavaScriptConverter()});
}
}
and
public class EFJavaScriptConverter : JavaScriptConverter
{
private int _currentDepth = 1;
private readonly int _maxDepth = 1;
private readonly List<object> _processedObjects = new List<object>();
private readonly Type[] _builtInTypes = new[]
{
typeof(int?),
typeof(double?),
typeof(bool?),
typeof(bool),
typeof(byte),
typeof(sbyte),
typeof(char),
typeof(decimal),
typeof(double),
typeof(float),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(short),
typeof(ushort),
typeof(string),
typeof(DateTime),
typeof(DateTime?),
typeof(Guid)
};
public EFJavaScriptConverter() : this(1, null) { }
public EFJavaScriptConverter(int maxDepth = 1, EFJavaScriptConverter parent = null)
{
_maxDepth = maxDepth;
if (parent != null)
{
_currentDepth += parent._currentDepth;
}
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
_processedObjects.Add(obj.GetHashCode());
var type = obj.GetType();
var properties = from p in type.GetProperties()
where p.CanRead && p.GetIndexParameters().Count() == 0 &&
_builtInTypes.Contains(p.PropertyType)
select p;
var result = properties.ToDictionary(
p => p.Name,
p => (Object)TryGetStringValue(p, obj));
if (_maxDepth >= _currentDepth)
{
var complexProperties = from p in type.GetProperties()
where p.CanRead &&
p.GetIndexParameters().Count() == 0 &&
!_builtInTypes.Contains(p.PropertyType) &&
p.Name != "RelationshipManager" &&
!AllreadyAdded(p, obj)
select p;
foreach (var property in complexProperties)
{
var complexValue = TryGetValue(property, obj);
if(complexValue != null)
{
var js = new EFJavaScriptConverter(_maxDepth - _currentDepth, this);
result.Add(property.Name, js.Serialize(complexValue, new EFJavaScriptSerializer()));
}
}
}
return result;
}
private bool AllreadyAdded(PropertyInfo p, object obj)
{
var val = TryGetValue(p, obj);
return _processedObjects.Contains(val == null ? 0 : val.GetHashCode());
}
private static object TryGetValue(PropertyInfo p, object obj)
{
var parameters = p.GetIndexParameters();
if (parameters.Length == 0)
{
return p.GetValue(obj, null);
}
else
{
//cant serialize these
return null;
}
}
private static object TryGetStringValue(PropertyInfo p, object obj)
{
if (p.GetIndexParameters().Length == 0)
{
var val = p.GetValue(obj, null);
return val;
}
else
{
return string.Empty;
}
}
public override IEnumerable<Type> SupportedTypes
{
get
{
var types = new List<Type>();
//ef types
types.AddRange(Assembly.GetAssembly(typeof(DbContext)).GetTypes());
//model types
types.AddRange(Assembly.GetAssembly(typeof(BaseViewModel)).GetTypes());
return types;
}
}
}
You can now safely make a call like new EFJavaScriptSerializer().Serialize(obj)
Update : since version Telerik v1.3+ you can now override the GridActionAttribute.CreateActionResult method and hence you can easily integrate this Serializer into specific controller methods by applying your custom [GridAction] attribute:
[Grid]
public ActionResult _GetOrders(int id)
{
return new GridModel(Service.GetOrders(id));
}
and
public class GridAttribute : GridActionAttribute, IActionFilter
{
/// <summary>
/// Determines the depth that the serializer will traverse
/// </summary>
public int SerializationDepth { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GridActionAttribute"/> class.
/// </summary>
public GridAttribute()
: base()
{
ActionParameterName = "command";
SerializationDepth = 1;
}
protected override ActionResult CreateActionResult(object model)
{
return new EFJsonResult
{
Data = model,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxSerializationDepth = SerializationDepth
};
}
}
and finally..
public class EFJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public EFJsonResult()
{
MaxJsonLength = 1024000000;
RecursionLimit = 10;
MaxSerializationDepth = 1;
}
public int MaxJsonLength { get; set; }
public int RecursionLimit { get; set; }
public int MaxSerializationDepth { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(JsonRequest_GetNotAllowed);
}
var response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var serializer = new JavaScriptSerializer
{
MaxJsonLength = MaxJsonLength,
RecursionLimit = RecursionLimit
};
serializer.RegisterConverters(new List<JavaScriptConverter> { new EFJsonConverter(MaxSerializationDepth) });
response.Write(serializer.Serialize(Data));
}
}
You can also detach the object from the context and it will remove the navigation properties so that it can be serialized. For my data repository classes that are used with Json i use something like this.
public DataModel.Page GetPage(Guid idPage, bool detach = false)
{
var results = from p in DataContext.Pages
where p.idPage == idPage
select p;
if (results.Count() == 0)
return null;
else
{
var result = results.First();
if (detach)
DataContext.Detach(result);
return result;
}
}
By default the returned object will have all of the complex/navigation properties, but by setting detach = true it will remove those properties and return the base object only. For a list of objects the implementation looks like this
public List<DataModel.Page> GetPageList(Guid idSite, bool detach = false)
{
var results = from p in DataContext.Pages
where p.idSite == idSite
select p;
if (results.Count() > 0)
{
if (detach)
{
List<DataModel.Page> retValue = new List<DataModel.Page>();
foreach (var result in results)
{
DataContext.Detach(result);
retValue.Add(result);
}
return retValue;
}
else
return results.ToList();
}
else
return new List<DataModel.Page>();
}
I have just successfully tested this code.
It may be that in your case your Message object is in a different assembly? The overriden Property SupportedTypes is returning everything ONLY in its own Assembly so when serialize is called the JavaScriptSerializer defaults to the standard JavaScriptConverter.
You should be able to verify this debugging.
Your error occured due to some "Reference" classes generated by EF for some entities with 1:1 relations and that the JavaScriptSerializer failed to serialize.
I've used a workaround by adding a new condition :
!p.Name.EndsWith("Reference")
The code to get the complex properties looks like this :
var complexProperties = from p in type.GetProperties()
where p.CanWrite &&
p.CanRead &&
!p.Name.EndsWith("Reference") &&
!_builtInTypes.Contains(p.PropertyType) &&
!_processedObjects.Contains(p.GetValue(obj, null)
== null
? 0
: p.GetValue(obj, null).GetHashCode())
select p;
Hope this help you.
I had a similar problem with pushing my view via Ajax to UI components.
I also found and tried to use that code sample you provided. Some problems I had with that code:
SupportedTypes wasn't grabbing the types I needed, so the converter wasn't being called
If the maximum depth is hit, the serialization would be truncated
It threw out any other converters I had on the existing serializer by creating its own new JavaScriptSerializer
Here are the fixes I implemented for those issues:
Reusing the same serializer
I simply reused the existing serializer that is passed into Serialize to solve this problem. This broke the depth hack though.
Truncating on already-visited, rather than on depth
Instead of truncating on depth, I created a HashSet<object> of already seen instances (with a custom IEqualityComparer that checked reference equality). I simply didn't recurse if I found an instance I'd already seen. This is the same detection mechanism built into the JavaScriptSerializer itself, so worked quite well.
The only problem with this solution is that the serialization output isn't very deterministic. The order of truncation is strongly dependent on the order that reflections finds the properties. You could solve this (with a perf hit) by sorting before recursing.
SupportedTypes needed the right types
My JavaScriptConverter couldn't live in the same assembly as my model. If you plan to reuse this converter code, you'll probably run into the same problem.
To solve this I had to pre-traverse the object tree, keeping a HashSet<Type> of already seen types (to avoid my own infinite recursion), and pass that to the JavaScriptConverter before registering it.
Looking back on my solution, I would now use code generation templates to create a list of the entity types. This would be much more foolproof (it uses simple iteration), and have much better perf since it would produce a list at compile time. I'd still pass this to the converter so it could be reused between models.
My final solution
I threw out that code and tried again :)
I simply wrote code to project onto new types ("ViewModel" types - in your case, it would be service contract types) before doing my serialization. The intention of my code was made more explicit, it allowed me to serialize just the data I wanted, and it didn't have the potential of slipping in queries on accident (e.g. serializing my whole DB).
My types were fairly simple, and I didn't need most of them for my view. I might look into AutoMapper to do some of this projection in the future.