ReactiveUI 4.1 CreateDerivedCollection(...) filter does not seem to work - reactiveui

I am using ReactiveUI 4.1. I use a ReactiveCollection of selectable items (having IsSelected flag) as a source for another derived reactive collection that uses filter to view only items that have IsSelected == true. If the source collection is pre-populated with some un/selected items before creating the derived collection, the view filter seems to work, but when later on items in the source collection go from selected to unselected state these items do not "disappear" within the derived collection. I do set ChangeTrackingEnabled flag to true on all of the collection, but it does not seem to help. Attaching my code snippet:
private readonly ReactiveCollection<string> _sourceItems = new ReactiveCollection<string>();
private readonly ReactiveCollection<SelectableDataItem<string>> _selectableItemsView = null;
private readonly ReactiveCollection<SelectableDataItem<string>> _selectedItemsView = null;
private readonly ReactiveCollection<string> _selectedDataView = null;
///....
this._sourceItems.ChangeTrackingEnabled = true;
this._selectableItemsView =
this.SourceItems.CreateDerivedCollection<string, SelectableDataItem<string>>(i => new SelectableDataItem<string>(i) { IsSelected = true, });
this._selectableItemsView.ChangeTrackingEnabled = true;
this._selectedItemsView =
this._selectableItemsView.CreateDerivedCollection<SelectableDataItem<string>, SelectableDataItem<string>>(
i => i,
f => f.IsSelected,
(i1, i2) => 0
);
this._selectedItemsView.ChangeTrackingEnabled = true;
this._selectedDataView =
this._selectableItemsView.CreateDerivedCollection<SelectableDataItem<string>, string>(i => i.Data, f => f.IsSelected, (i1, i2) => 0);
this._selectedDataView.ChangeTrackingEnabled = true;

Hmmm, looks like a bug - can you do one of the following:
Create a sample app that hits this bug, then create an issue
(Even better) Create a pull request against ReactiveUI with a test that fails

Related

Converting an IObservable to SourceCache with Dynamic Data

I'm new to ReactiveUI and I'm trying to add bits of it to my Xamarin Forms application. We have a service method that returns an IObservable.
IObservable<List<DiningArea>> diningAreaObservable = _tableService.GetAllDiningAreas();
This works and previously we've subscribed to this and mapped the results into an ObservableCollection. I'd like to replace this and start using Dynamic Data. So I've setup some global's with the XAML collection view's binding source being DiningAreas.
private SourceCache<DiningArea, int> _diningAreas = new SourceCache<DiningArea, int>(x => x.Id);
private ReadOnlyObservableCollection<DiningArea> _diningAreaCollection;
public ReadOnlyObservableCollection<DiningArea> DiningAreas => _diningAreaCollection;
Now in my ViewModel I call the service, get back an observable but how do I add the observable to the SourceCache. I can see how to convert it to an IChangeSet but I want it to be apart of _diningAreas.
IObservable<List<DiningArea>> diningAreaObservable = _tableService.GetAllDiningAreas();
IObservable<IChangeSet<DiningArea, int>> diningAreaChangeSet = diningAreaObservable.ToObservableChangeSet(t => t.Id);
_diningAreas.AddOrUpdate(new DiningArea { Id = 0, Name = "All", Position = 0 });
var diningAreaDisposable = _diningAreas.Connect()
.Sort(SortExpressionComparer<DiningArea>.Ascending(z => z.Position))
.Bind(out _diningAreaCollection)
.Subscribe();
Am I understanding this correctly or am I doing something backwards?

how to update observable collection group

I have implemented group observable collection like below.
Grouped Property
private ObservableCollection<Grouping<String, Request>> _groupedList = null;
public ObservableCollection<Grouping<String, Request>> GroupedList {
get {
return _groupedList;
}
set {
_groupedList = value;
RaisePropertyChanged(() => GroupedList);
}
}
Creating List
var list = new List<Request>();
var grouped = from Model in list
group Model by Model.Done into Group
select new Grouping<string, Request>(Group.Key, Group);
GroupedList = new ObservableCollection<Grouping<string, TModel>>(grouped);
Now i need to update one item in the list without reloading full list for performance.
i did tried like this , mylist.FirstOrDefault(i => i.Id== mymodel.Id); Not worked for me.
I need to pick that particular item and edit and update into the list again using linq or something but i stuck here for group observable collection no efficient details to do this., anybody having idea about this help please.
And finally i get updated single item, but i need to do that without
GroupedList = new ObservableCollection<Grouping<string, TModel>>(grouped);
Because everytime it create new list and bind into my view.Thats again big performance though.
Thanks in advance.
What I understand from your question is that you want to push an updated group without overwriting the entire ObservableCollection.
To do that:
var targetGroup = GroupedList.FirstOrDefault(i => i.Id == mymodel.Id);
var targetIndex = GroupedList.IndexOf(targetGroup);
var modifiedGroup = ... //Do whatever you want to do
GroupedList[targetIndex] = modifiedGroup;
This will trigger a 'replace' operation of the target grouping.

How to get a standalone / unmanaged RealmObject using Realm Xamarin

Is there a way that when I read an object from Realm that it can become a standalone or unmanaged object? In EF, this is called no tracking. The usage for this would be when I want to implement more business logic on my data objects before they are updated on the persistent data storage. I may want to give the RealmObject to a ViewModel, but when the changes come back from the ViewModel, I want to compare the disconnected object to the object in the datastore to determine what was changed, so If there was a way that I could disconnect the object from Realm when I give it to the ViewModel, then I can better manage what properties have changed, using my biz logic to do what I need, then save the changes back to realm.
I understand Realm does a lot of magic and many people will not want to add a layer like this but in my app, I cant really have the UI directly updating the datastore, unless there is a event that is raised that I can subscribe too and then attach my business logic this way.
I only saw one event and it does not appear to perform this action.
Thanks for your assistance.
First, get json NUGET :
PM> Install-Package Newtonsoft.Json
And, try this "hack" :
Deserialize the modified IsManaged property does the tricks.
public d DetachObject<d>(d Model) where d : RealmObject
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<d>(
Newtonsoft.Json.JsonConvert.SerializeObject(Model)
.Replace(",\"IsManaged\":true", ",\"IsManaged\":false")
);
}
.
If you facing slow-down on JsonConvert:
According to source code
, the 'IsManaged' property only has get accessor and return true when private field _realm which is available
So, we has to set the instance of field _realm to null does the tricks
public d DetachObject<d>(d Model) where d : RealmObject
{
typeof(RealmObject).GetField("_realm",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.SetValue(Model, null);
return Model.IsManaged ? null : Model;
}
.
You will get empty RealmObject body after Realm are now implemented same strategy as LazyLoad
Record down live RealmObject and (deactivate) realm instance in object by Reflection. And set back recorded values to RealmObject. With handled all the ILists inside too.
public d DetachObject<d>(d Model) where d : RealmObject
{
return (d)DetachObjectInternal(Model);
}
private object DetachObjectInternal(object Model)
{
//Record down properties and fields on RealmObject
var Properties = Model.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
.Where(x => x.Name != "ObjectSchema" && x.Name != "Realm" && x.Name != "IsValid" && x.Name != "IsManaged" && x.Name != "IsDefault")
.Select(x =>(x.PropertyType.Name == "IList`1")? ("-" + x.Name, x.GetValue(Model)) : (x.Name, x.GetValue(Model))).ToList();
var Fields = Model.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
.Select(x => (x.Name, x.GetValue(Model))).ToList();
//Unbind realm instance from object
typeof(RealmObject).GetField("_realm", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(Model, null);
//Set back the properties and fields into RealmObject
foreach (var field in Fields)
{
Model.GetType().GetField(field.Item1, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public).SetValue(Model, field.Item2);
}
foreach (var property in Properties.OrderByDescending(x=>x.Item1[0]).ToList())
{
if (property.Item1[0] == '-')
{
int count = (int)property.Item2.GetType().GetMethod("get_Count").Invoke(property.Item2, null);
if (count > 0)
{
if (property.Item2.GetType().GenericTypeArguments[0].BaseType.Name == "RealmObject")
{
for (int i = 0; i < count; i++)
{
var seter = property.Item2.GetType().GetMethod("set_Item");
var geter = property.Item2.GetType().GetMethod("get_Item");
property.Item2.GetType().GetField("_realm", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public).SetValue(property.Item2, null);
DetachObjectInternal(geter.Invoke(property.Item2, new object[] { i }));
}
}
}
}
else
{
Model.GetType().GetProperty(property.Item1, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public).SetValue(Model, property.Item2);
}
}
return Model;
}
.
For List of the RealmObject , Using Select():
DBs.All<MyRealmObject>().ToList().Select(t => DBs.DetachObject(t)).ToList();
.
(Java)You dont need this if youre in java:
Maybe some day, this feature will come to .NET Realm
Realm.copyFromRealm();
#xamarin #C# #Realm #RealmObject #detach #managed #IsManaged #copyFromRealm
Until its added to Realm for Xamarin, I added a property to my Model that creates a copy of the object. This seems to work for my use. The TwoWay Binding error messages are now also not an issue. For a more complicated application, I don't want to put business or data logic in the ViewModel. This allows all the Magic of xamarin forms to work and me to implement logic when its finally time to save the changes back to realm.
[Ignored]
public Contact ToStandalone()
{
return new Contact()
{
companyName = this.companyName,
dateAdded = this.dateAdded,
fullName = this.fullName,
gender = this.gender,
website = this.website
};
}
However, If there are any relationships this method does not work for the relationships. Copying the List is not really an option either as the relationship cant exist if the object is not attached to Realm, I read this some where, can't find it to ref now. So I guess we will be waiting for the additions to the framework.
Not currently in the Xamarin interface but we could add it. The Java interface already has copyFromRealm which performs a deep copy. That also has a paired merging copyToRealmOrUpdate.
See Realm github issue for further discussion.
However, as a design issue, is this really meeting your need in an optimal way?
I have used converters in WPF apps to insert logic into the binding - these are available in Xamarin Forms.
Another way in Xamarin forms is to use Behaviours, as introduced in the blog article and covered in the API.
These approaches are more about adding logic between the UI and ViewModel, which you could consider as part of the ViewModel, but before updates are propagated to bound values.
After wasting too much time in 3rd party libraries like AutoMapper, I've created my own extension function which works pretty well. This function simply uses Reflection with the recession. (Currently, Only for List type. You can extend the functionality for Dictionary and other types of the collection very easily or you can completely modify the functionality based on your own requirements.).
I didn't do too much time and complexity analysis. I've tested only for my test case which contains many nested RealmObject, built from a 3500+ line of JSON object, took only 15 milliseconds to clone the object.
Here the complete extension available via Github Gist. If you want to extend the functionality of this extension please update this Github Gist, So, other developers can take advantage of it.
Here the complete extension -
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Realms;
namespace ProjectName.Core.Extensions
{
public static class RealmExtension
{
public static T Clone<T>(this T source) where T: new()
{
//If source is null return null
if (source == null)
return default(T);
var target = new T();
var targetType = typeof(T);
//List of skip namespaces
var skipNamespaces = new List<string>
{
typeof(Realm).Namespace
};
//Get the Namespace name of Generic Collection
var collectionNamespace = typeof(List<string>).Namespace;
//flags to get properties
var flags = BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
//Get target properties list which follows the flags
var targetProperties = targetType.GetProperties(flags);
//if traget properties is null then return default target
if (targetProperties == null)
return target;
//enumerate properties
foreach (var property in targetProperties)
{
//skip property if it's belongs to namespace available in skipNamespaces list
if (skipNamespaces.Contains(property.DeclaringType.Namespace))
continue;
//Get property information and check if we can write value in it
var propertyInfo = targetType.GetProperty(property.Name, flags);
if (propertyInfo == null || !property.CanWrite)
continue;
//Get value from the source
var sourceValue = property.GetValue(source);
//If property derived from the RealmObject then Clone that too
if (property.PropertyType.IsSubclassOf(typeof(RealmObject)) && (sourceValue is RealmObject))
{
var propertyType = property.PropertyType;
var convertedSourceValue = Convert.ChangeType(sourceValue, propertyType);
sourceValue = typeof(RealmExtension).GetMethod("Clone", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(propertyType).Invoke(convertedSourceValue, new[] { convertedSourceValue });
}
//Check if property belongs to the collection namespace and original value is not null
if (property.PropertyType.Namespace == collectionNamespace && sourceValue != null)
{
//get the type of the property (currently only supported List)
var listType = property.PropertyType;
//Create new instance of listType
var newList = (IList)Activator.CreateInstance(listType);
//Convert source value into the list type
var convertedSourceValue = Convert.ChangeType(sourceValue, listType) as IEnumerable;
//Enumerate source list and recursively call Clone method on each object
foreach (var item in convertedSourceValue)
{
var value = typeof(RealmExtension).GetMethod("Clone", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(item.GetType()).Invoke(item, new[] { item });
newList.Add(value);
}
//update source value
sourceValue = newList;
}
//set updated original value into the target
propertyInfo.SetValue(target, sourceValue);
}
return target;
}
}
}

Add an entity from another DataContex in linq

I am trying to merge data between two identical schema databases using Linq-to-sql:
List<Contact> contacts = (from c in oldDb.Contact
select c).ToList();
contacts.ForEach(c => c.CreatedByID = 0);
newDb.Contact.InsertAllOnSubmit(contacts);
newDb.SubmitChanges();
Merely throws an "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported." exception.
Other than doing the following, how else can this be done generically (in reasonable execution time):
List<Contact> contacts = (from c in oldDb.Contact
select c).ToList();
contacts.ForEach(c => { c.CreatedByID = 0; newDb.Contact.InsertAllOnSubmit(contacts); });
newDb.SubmitChanges();
along with:
private t GetNewObject<t>(t oldObj)
{
t newObj = (t)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(typeof(t).Name);
PropertyInfo[] props = typeof(t).GetProperties();
foreach (PropertyInfo _prop in props)
{
_prop.SetValue(newObj, _prop.GetValue(oldObj, null), null);
}
return newObj;
}
The problem is this method is rather slow when there's only 11 objects and 75 properties, I need to do this for a couple hundred thousand objects so any performance gains I can get at this end would greatly reduce overall run time.
Basically, is there any Detach or similar call I could do that will disconnect the existing objects from the old DataContext and connect them to the new DataContext. Without having to create all new objects for each and every one of the returned rows.
I didnt got the
contacts.ForEach(c => { c.CreatedByID = 0; newDb.Contact.InsertAllOnSubmit(contacts); });
shouldnt be something like
contacts.ForEach(c => {
Contact c2 = GetNewObject<Contact>(c);
c2.CreatedByID = 0;
newDb.Contact.InsertOnSubmit(c2);
});
also, here's a way of detaching the object from the old database: http://omaralzabir.com/linq_to_sql__how_to_attach_object_to_a_different_data_context/

What's problem on linq databinding

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
KeyFieldName="CategoryID">
<SettingsEditing Mode="Inline" />
<Columns>
<dx:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True"></EditButton>
<NewButton Visible="True"></NewButton>
<DeleteButton Visible="True"></DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn Caption="CategoryID" FieldName="CategoryID"
VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="CategoryName" FieldName="CategoryName"
VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Description" FieldName="Description"
VisibleIndex="3">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
C# syntax:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { p.CategoryID, p.CategoryName, p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
If you run the code, you get a gridview which is filled by NorthWind Categories table. If you click on command button of grid whose are on left side, you get insert/update field, but you have not access to give input. They are gone to read only mode.
If I replace the above C# syntax with below
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories);
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
then it works fine. Now you can work with command button with out facing any problem.
I want to know what the problem is, why the first syntax does not work. Maybe you say
Anonymous types are class types that consist of one or more public read-only properties. But when you need to join more than one table and need to select several fields not all than what you do. Hope you not say linq is fail to do that or Don't think it is possible. Hope there must be any technique or else something to bind control with Anonymous type. Plz show some syntax .
The problem is that the result set is collection of Anonymous type as you supposed and the grid doesn't know how to treat it. What you have to do is to use RowInserting and RowUpdating events of the grid.
Here is an example of how I use DevExpress grid with NHibernate:
protected void gridAgentGroups_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
var currentAgentGroup = new AgentGroup();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
protected void gridAgentGroups_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
ASPxGridView currentGrid = sender as ASPxGridView;
int currentAgentGroupId = (int)((AgentGroup)currentGrid.GetRow(currentGrid.EditingRowVisibleIndex)).Id;
var currentAgentGroup = AgentGroups.Where(ag => ag.Id == currentAgentGroupId).FirstOrDefault();
if (e.NewValues.Contains("Name"))
{
var newValue = (string)e.NewValues["Name"];
currentAgentGroup.Name = newValue;
}
if (e.NewValues.Contains("PhysicalAddress"))
{
var newValue = (string)e.NewValues["PhysicalAddress"];
currentAgentGroup.PhysicalAddress = newValue;
}
AgentGroupsDataAccess.SaveAgentGroup(currentAgentGroup);
e.Cancel = true;
currentGrid.CancelEdit();
currentGrid.DataBind();
}
I hope this will help.
Just a wild guess - you're binding your data to the grid using field names - yet, your anonymous type doesn't really have any field names.
Does it make any difference if you try this code:
NorthwindDataContext db = new NorthwindDataContext();
var lresult = (db.Categories
.Select(p => new { CategoryID = p.CategoryID,
CategoryName = p.CategoryName,
Description = p.Description}));
ASPxGridView1.DataSource = lresult;
ASPxGridView1.DataBind();
Again - I don't have the means to test this right now, it's just a gut feeling..... try it - does that help at all??
You actually can bind with anonymous type as you see the already filled rows. But: the grid itself cannot know how you build the query and what to add additionally to the visible columns (if there are valid default values).
As you use Developer Express' grid you have the option to provide your own update / edit form and handle everything needed on your own.

Resources