I have a problem with the model classes of my advancedDataGrid. Here are my model classes:
package module.testPlanModule
{
import flash.events.Event;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import mx.collections.IHierarchicalData;
import mx.utils.UIDUtil;
[Bindable]
[RemoteClass(alias="business.project.version.testPlan.TestSuite")]
public class TestSuite implements IExternalizable, IHierarchicalData
{
private var _uuid:String;
private var _ID:String;
private var _testCasesList:Array;
public function TestSuite()
{
_uuid = UIDUtil.createUID();
_ID = "TESTSUITE-"+Math.random();
_testCasesList = [];
}
public function get testCasesList():Array
{
return _testCasesList;
}
public function set testCasesList(value:Array):void
{
_testCasesList = value;
}
public function get ID():String
{
return _ID;
}
public function set ID(value:String):void
{
_ID = value;
}
public function get uuid():String
{
return _uuid;
}
public function set uuid(value:String):void
{
_uuid = value;
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function dispatchEvent(event:Event):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function hasEventListener(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function willTrigger(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function canHaveChildren(node:Object):Boolean
{
if(node is TestSuite){
return true;
}
else if(node is TestCase){
return true;
}
else
return false;
}
public function hasChildren(node:Object):Boolean
{
if(node is TestSuite){
return !(node.testCasesList.length == 0);
}
else if(node is TestCase){
return !(node.allocatedTests.length == 0);
}
else
return false;
}
public function getChildren(node:Object):Object
{
if(node is TestSuite){
return node.testCasesList;
}
else if(node is TestCase){
return node.allocatedTests;
}
else
return null;
}
public function getData(node:Object):Object
{
return node;
}
public function getRoot():Object
{
// TODO Auto Generated method stub
return null;
}
public function writeExternal(output:IDataOutput):void
{
output.writeUTF(_uuid);
output.writeUTF(_ID);
output.writeObject(_testCasesList);
}
public function readExternal(input:IDataInput):void
{
_uuid = input.readUTF();
_ID = input.readUTF();
_testCasesList = input.readObject();
}
}
}
package module.testPlanModule
{
import flash.events.Event;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import mx.collections.IHierarchicalData;
import mx.utils.UIDUtil;
[Bindable]
[RemoteClass(alias="business.project.version.testPlan.TestCase")]
public class TestCase implements IExternalizable, IHierarchicalData
{
private var _uuid:String;
private var _ID:String;
private var _allocatedTests:Array;
public function TestCase()
{
_uuid = UIDUtil.createUID();
_ID = "TESTCASE-"+Math.random();
_allocatedTests = [];
}
public function get ID():String
{
return _ID;
}
public function set ID(value:String):void
{
_ID = value;
}
public function get allocatedTests():Array
{
return _allocatedTests;
}
public function set allocatedTests(value:Array):void
{
_allocatedTests = value;
}
public function get uuid():String
{
return _uuid;
}
public function set uuid(value:String):void
{
_uuid = value;
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function dispatchEvent(event:Event):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function hasEventListener(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function willTrigger(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function canHaveChildren(node:Object):Boolean
{
if(node is TestSuite){
return true;
}
else if(node is TestCase){
return true;
}
else
return false;
}
public function hasChildren(node:Object):Boolean
{
if(node is TestSuite){
return !(node.testCasesList.length == 0);
}
else if(node is TestCase){
return !(node.allocatedTests.length == 0);
}
else
return false;
}
public function getChildren(node:Object):Object
{
if(node is TestSuite){
return node.testCasesList;
}
else if(node is TestCase){
return node.allocatedTests;
}
else
return null;
}
public function getData(node:Object):Object
{
return node;
}
public function getRoot():Object
{
// TODO Auto Generated method stub
return null;
}
public function writeExternal(output:IDataOutput):void
{
output.writeUTF(_uuid);
output.writeUTF(_ID);
output.writeObject(_allocatedTests);
}
public function readExternal(input:IDataInput):void
{
_uuid = input.readUTF();
_ID = input.readUTF();
_allocatedTests = input.readObject();
}
}
}
package module.testPlanModule
{
import flash.events.Event;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import mx.collections.IHierarchicalData;
import mx.utils.UIDUtil;
[Bindable]
[RemoteClass(alias="business.project.version.test.TestBase")]
public class TestBase implements IExternalizable, IHierarchicalData
{
private var _uuid:String;
private var _ID:String;
private var _state:String;
private var _result:String;
private var _allocatedUser:String;
private var _linkedRequirements:Array;
public function TestBase()
{
_uuid = UIDUtil.createUID();
_ID = "TEST-"+Math.random();
_state = "not passed";
_result = "na";
_allocatedUser = "";
_linkedRequirements = [];
}
public function get ID():String
{
return _ID;
}
public function set ID(value:String):void
{
_ID = value;
}
public function get state():String
{
return _state;
}
public function set state(value:String):void
{
_state = value;
}
public function get result():String
{
return _result;
}
public function set result(value:String):void
{
_result = value;
}
public function get allocatedUser():String
{
return _allocatedUser;
}
public function set allocatedUser(value:String):void
{
_allocatedUser = value;
}
public function get linkedRequirements():Array
{
return _linkedRequirements;
}
public function set linkedRequirements(value:Array):void
{
_linkedRequirements = value;
}
public function get uuid():String
{
return _uuid;
}
public function set uuid(value:String):void
{
_uuid = value;
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function dispatchEvent(event:Event):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function hasEventListener(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
{
// TODO Auto Generated method stub
}
public function willTrigger(type:String):Boolean
{
// TODO Auto Generated method stub
return false;
}
public function canHaveChildren(node:Object):Boolean
{
if(node is TestSuite){
return true;
}
else if(node is TestCase){
return true;
}
else
return false;
}
public function hasChildren(node:Object):Boolean
{
if(node is TestSuite){
return !(node.testCasesList.length == 0);
}
else if(node is TestCase){
return !(node.allocatedTests.length == 0);
}
else
return false;
}
public function getChildren(node:Object):Object
{
if(node is TestSuite){
return node.testCasesList;
}
else if(node is TestCase){
return node.allocatedTests;
}
else
return null;
}
public function getData(node:Object):Object
{
return node;
}
public function getRoot():Object
{
// TODO Auto Generated method stub
return null;
}
public function writeExternal(output:IDataOutput):void
{
output.writeUTF(_uuid);
output.writeUTF(_ID);
output.writeUTF(_state);
output.writeUTF(_result);
output.writeUTF(_allocatedUser);
output.writeObject(_linkedRequirements);
}
public function readExternal(input:IDataInput):void
{
_uuid = input.readUTF();
_ID = input.readUTF();
_state = input.readUTF();
_result = input.readUTF();
_allocatedUser = input.readUTF();
_linkedRequirements = input.readObject();
}
}
}
And here is my AdvancedDatagrid:
<mx:AdvancedDataGrid id="testPlanADG" displayItemsExpanded="true"
width="95%" height="95%"
contentBackgroundAlpha="0.0" chromeColor="0xdbeaff"
openDuration="500"
verticalScrollPolicy="on"
horizontalScrollPolicy="auto"
variableRowHeight="true">
<mx:columns>
<mx:AdvancedDataGridColumn id="IdCol" dataField="ID" headerText="ID"
/>
<mx:AdvancedDataGridColumn dataField="state" headerText="State"/>
<mx:AdvancedDataGridColumn dataField="result" headerText="Result"/>
<mx:AdvancedDataGridColumn dataField="allocatedUser" headerText="User affected"/>
</mx:columns>
</mx:AdvancedDataGrid>
The problem is that just the TestSuite's ID are displayed and nothing else.
To populate the ADG I did this:
_model = new ArrayCollection();
// here I populate the model
var testSuite1:TestSuite = new TestSuite();
testSuite1.ID = "testSuite1";
var testCase1:TestCase = new TestCase();
testCase1.ID = "testCase1";
var testBase1:TestBase = new TestBase();
testBase1.ID = "testBase1";
var testBase2:TestBase = new TestBase();
testBase2.ID = "testBase2";
testCase1.allocatedTests = [testBase1,testBase2];
// ...
_testPlanHierarchy = new HierarchicalData();
_testPlanHierarchy.source = _model;
testPlanADG.dataProvider = _testPlanHierarchy;
I can see the ID of my two test suites displayed like leaf nodes and nothing else. I really don't understand.
You can choose to show or hide the root node, and you need to tell the ADG what field to look at for children, since you don't have a field called children. That field needs to be of type ListCollectionViewnor one of its subclasses, such as ArrayCollection. Perhaps just adding a field called children that wraps the fields you already have of type Array will fix your issue.
Related
I am trying to recreate the Byline component activity in AEM WKND (https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-wknd-tutorial-develop/project-archetype/custom-component.html?lang=en#byline-styles). However when I tried to implement the html file, byline component is hidden in the page whenever I call data-sly-use api. Is there any workaround or solution for this one?
Below is my impl code:
#Model(adaptables = {SlingHttpServletRequest.class},
adapters = {Byline.class},
resourceType = {BylineImpl.RESOURCE_TYPE},
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class BylineImpl implements Byline {
protected static final String RESOURCE_TYPE = "wknd/components/byline";
#Self
private SlingHttpServletRequest request;
#OSGiService
private ModelFactory modelFactory;
#ValueMapValue
private String name;
#ValueMapValue
private List<String> occupations;
private Image image;
#Override
public String getName() {
return name;
}
#PostConstruct
private void init(){
image = modelFactory.getModelFromWrappedRequest(request, request.getResource(), Image.class);
}
#Override
public List<String> getOccupations() {
if (occupations != null) {
Collections.sort(occupations);
return new ArrayList<String>(occupations);
} else {
return Collections.emptyList();
}
}
#Override
public boolean isEmpty() {
final Image componentImage = getImage();
if (StringUtils.isBlank(name)) {
// Name is missing, but required
return true;
} else if (occupations == null || occupations.isEmpty()) {
// At least one occupation is required
return true;
} else if (componentImage == null || StringUtils.isBlank(componentImage.getSrc())) {
// A valid image is required
return true;
} else {
// Everything is populated, so this component is not considered empty
return false;
}
}
private Image getImage() {
return image;
}
}
Below is my byline.html code:
div data-sly-use.byline="com.adobe.aem.guides.wknd.core.models.impl.BylineImpl"
data-sly-use.placeholderTemplate="core/wcm/components/commons/v1/templates.html"
data-sly-test.hasContent="${!byline.empty}" class="cmp-byline">
<div class="cmp-byline__image" data-sly-resource="${ '.' # resourceType = 'core/wcm/components/image/v2/image' }">
</div>
<h2 class="cmp-byline__name">${byline.name}</h2>
<p class="cmp-byline__occupations">${byline.occupations # join=', '}</p>
</div>
<sly data-sly-call="${placeholderTemplate.placeholder # isEmpty=!hasContent}"></sly>
Below are shown my classes of sysOperation framework, my problem is when i open the dialog and i press OK , nothing happens, what's wrong with this code?
My service class:
class ProdutionFLowsService extends SysOperationServiceBase
{
ProductionFlowId idOfCopy;
int copyToDo;
ProdTable prodTable;
public void process(ProdutionFLowsContract _contract)
{
this.getPromptParameters(_contract);
select firstonly ProdId
from prodTable
order by ProdId
where prodTable.ProductionFlowId == this.idOfCopy;
this.insertInProdTable();
}
public void insertInProdTable()
{
ProdTable _prodTable;
while(copyToDo > 0)
{
buf2Buf(prodTable,_prodTable);
_prodTable.RecId = 0;
_prodTable.ProdId = _prodTable.Type().initProdId(true);
_prodTable.GAP035ProductionFlowId = _prodTable.ProductionFlowId;
_prodTable.insert();
copyToDo--;
}
}
public void getPromptParameters(ProdutionFLowsContract _contract)
{
copyToDo = _contract.parmCopyToDo();
idOfCopy = _contract.parmidOfCopy();
}
}
My controller class:
class ProdutionFLowsController extends SysOperationServiceController
{
public void new()
{
super();
super(classStr(ProdutionFLowsService), methodStr(ProdutionFLowsService, process), SysOperationExecutionMode::Synchronous);
this.parmDialogCaption("TODO");
}
public static void main(Args _args)
{
ProdutionFLowsController controller = new ProdutionFLowsController();
controller.parmArgs(_args);
controller.startOperation();
}
}
My Contract Class:
[DataContractAttribute]
class ProdutionFLowsContract implements SysOperationInitializable,SysOperationValidatable
{
ProductionFlowId idOfCopy;
int copyToDo;
public void initialize()
{
idOfCopy = "";
copyToDo = 0;
}
[DataMemberAttribute("idOfCopy"),SysOperationLabelAttribute(literalStr("TODO(Id)")),SysOperationDisplayOrderAttribute("1")]
public ProductionFlowId parmidOfCopy(ProductionFlowId _idOfCopy = idOfCopy)
{
idOfCopy = _idOfCopy;
return idOfCopy;
}
[DataMemberAttribute("copyToDo"),SysOperationLabelAttribute(literalStr("copyToDo(Copy)")),SysOperationDisplayOrderAttribute("2")]
public int parmCopyToDo(int _copyToDo = copyToDo)
{
copyToDo = _copyToDo;
return copyToDo;
}
public boolean validate()
{
return false;
}
}
Your contract validation always fails because it always returns false and doesn't show any error in the infolog:
public boolean validate()
{
return false;
}
Try to replace return false with return true or to remove SysOperationValidatable and validate method altogether.
I'm having trouble with the coding to properly listen for Firebase add or update events. My attempt below has the data loading into the Syncfusion Datagrid, but there is a weird glitch where when I click the mouse on the Datagrid and pull-down, the first record in my 4 record set gets added to the bottom of the Datagrid, showing a 5th record... if I update an element in the Datagrid, the change is not reflected in Firebase. If I add or change a value in firebase, it does not update in Datagrid. Any help to steer me in the right direction to get this to work would be appreciated. Here's the code:
the VisualStudio 2019
CookPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Chart_sample"
xmlns:gauge="clr-namespace:Syncfusion.SfGauge.XForms;assembly=Syncfusion.SfGauge.XForms"
xmlns:Syncfusion="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
mc:Ignorable="d"
x:Class="Chart_sample.Views.CookPage">
<StackLayout>
<Syncfusion:SfDataGrid x:Name="sfGrid">
</Syncfusion:SfDataGrid>
</StackLayout>
</ContentPage>
CookPage.xaml.cs
using Chart_sample.Services;
using Syncfusion.SfDataGrid.XForms;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Chart_sample.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CookPage : ContentPage
{
FirebaseHelper firebaseHelper = new FirebaseHelper();
public CookPage()
{
InitializeComponent();
// for Syncfusion DataGrid
firebaseHelper.listenForEvents();
sfGrid.ItemsSource = ViewProgramModel._returnedEvents;
sfGrid.ColumnSizer = ColumnSizer.Star;
sfGrid.AllowEditing = true;
sfGrid.NavigationMode = NavigationMode.Cell;
sfGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Single;
}
}
}
FirebaseHelper.cs
using Firebase.Database;
using Firebase.Database.Query;
using System;
using System.Linq;
namespace Chart_sample.Services
{
public class FirebaseHelper
{
internal ViewProgramModel ViewProgramModel { get; set; }
FirebaseClient firebase = new FirebaseClient("https://pelletpirate.firebaseio.com/");
private readonly string ChildProgram = "ControllerData/Pellet_Pirate_1/Program";
public static IDisposable returnedEvents;
public async void listenForEvents()
{
ViewProgramModel._returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
ViewProgramModel._returnedEvents.Add(programs.ElementAt(i).Object);
}
returnedEvents = firebase.Child(ChildProgram).OrderByKey().AsObservable<ViewProgramModel>()
.Subscribe(eventReceived =>
{
if (eventReceived.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
{
var found = ViewProgramModel._returnedEvents.FirstOrDefault(i => i._KEY == eventReceived.Key);
if (found == null)
{
// not in observable collection, add it
ViewProgramModel._returnedEvents.Add(eventReceived.Object);
}
else
{
// event was updated
int tempIndex = ViewProgramModel._returnedEvents.IndexOf(found);
ViewProgramModel._returnedEvents[tempIndex] = eventReceived.Object;
}
}
});
}
}
}
ViewProgrammodel.cs
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Chart_sample
{
public class ViewProgramModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _KEy;
private string MOde;
private int TArget;
private string TRigger;
private int TRiggerVAlue;
public string _KEY
{
get { return _KEy; }
set
{
this._KEy = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("_KEY"));
}
}
public string MODE
{
get { return MOde; }
set
{
this.MOde = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MODE"));
}
}
public int TARGET
{
get { return TArget; }
set
{
this.TArget = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TARGET"));
}
}
public string TRIGGER
{
get { return TRigger; }
set
{
this.TRigger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGER"));
}
}
public int TRIGGERVALUE
{
get { return TRiggerVAlue; }
set
{
this.TRiggerVAlue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGERVALUE"));
}
}
public static ObservableCollection<ViewProgramModel> _returnedEvents = new ObservableCollection<ViewProgramModel>();
}
}
I edit your demo, I achieve the update, Add, delete function.
Here is running GIF.
I change your ViewProgramModel like following code. Just move the _returnedEvents to the FirebaseHelper.cs
namespace Chart_sample
{
public class ViewProgramModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _KEy;
private string MOde;
private int TArget;
private string TRigger;
private int TRiggerVAlue;
public string _KEY
{
get { return _KEy; }
set
{
this._KEy = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("_KEY"));
}
}
public string MODE
{
get { return MOde; }
set
{
this.MOde = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MODE"));
}
}
public int TARGET
{
get { return TArget; }
set
{
this.TArget = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TARGET"));
}
}
public string TRIGGER
{
get { return TRigger; }
set
{
this.TRigger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGER"));
}
}
public int TRIGGERVALUE
{
get { return TRiggerVAlue; }
set
{
this.TRiggerVAlue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGERVALUE"));
}
}
}
Here is FirebaseHelper.cs, Note: I achieve the update function just for the TARGET Column, I suggest your to add a Primary-key(Auto-increase) for every record in your database to achieve your search function.
public class FirebaseHelper
{
public ObservableCollection<ViewProgramModel> _returnedEvents { get; set; }
public FirebaseHelper()
{
_returnedEvents = new ObservableCollection<ViewProgramModel>();
}
// internal ViewProgramModel MyViewProgramModel { get; set; }
FirebaseClient firebase = new FirebaseClient("https://xxxxxxxxxx.firebaseio.com/");
private readonly string ChildProgram = "ControllerData/xxxxxx_Pirate_1/Program";
public static IDisposable returnedEvents;
public async Task AddViewProgramModel()
{
//new ViewProgramModel() { MODE="test", TARGET=122, TRIGGER="122", TRIGGERVALUE=333, }
await firebase
.Child(ChildProgram)
.PostAsync( new ViewProgramModel() { MODE = "test", TARGET = 122, TRIGGER = "122", TRIGGERVALUE = 333, });
GetAllData();
}
public async Task UpdateViewProgramModel(ViewProgramModel viewProgramModel , string oldValue)
{
var toUpdatePerson = (await firebase
.Child(ChildProgram)
.OnceAsync<ViewProgramModel>()).FirstOrDefault(a => a.Object.TARGET == Convert.ToInt32( oldValue));
await firebase
.Child(ChildProgram)
.Child(toUpdatePerson.Key)
.PutAsync(viewProgramModel);
GetAllData();
}
public async Task DeleteViewProgramModel(string mode)
{
var toDeletePerson = (await firebase
.Child(ChildProgram)
.OnceAsync<ViewProgramModel>()).FirstOrDefault(a => a.Object.MODE == mode);
await firebase.Child(ChildProgram).Child(toDeletePerson.Key).DeleteAsync();
GetAllData();
}
public async void GetAllData()
{
_returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
_returnedEvents.Add(programs.ElementAt(i).Object);
}
}
public async void listenForEvents()
{
_returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
_returnedEvents.Add(programs.ElementAt(i).Object);
}
//returnedEvents = firebase.Child(ChildProgram).OrderByKey().AsObservable<ViewProgramModel>()
// .Subscribe(eventReceived =>
// {
// if (eventReceived.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
// {
// var found = _returnedEvents.FirstOrDefault(i => i._KEY == eventReceived.Key);
// if (found == null)
// {
// // not in observable collection, add it
// _returnedEvents.Add(eventReceived.Object);
// }
// else
// {
// // event was updated
// int tempIndex = _returnedEvents.IndexOf(found);
// _returnedEvents[tempIndex] = eventReceived.Object;
// }
// }
//});
}
}
}
Here is CookPage.xaml
<StackLayout>
<Button Text="add" Clicked="Button_Clicked"></Button>
<Button Text="delete" Clicked="Button_Clicked_1"></Button>
<Syncfusion:SfDataGrid x:Name="sfGrid" ItemsSource="{Binding _returnedEvents, Mode=TwoWay} " >
</Syncfusion:SfDataGrid>
</StackLayout>
Here is code about CookPage.cs.
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CookPage : ContentPage
{
FirebaseHelper firebaseHelper = new FirebaseHelper();
public CookPage()
{
InitializeComponent();
// for Syncfusion DataGrid
firebaseHelper.listenForEvents();
//sfGrid.ItemsSource = ViewProgramModel._returnedEvents;
BindingContext= firebaseHelper;
sfGrid.ColumnSizer = ColumnSizer.Star;
sfGrid.AllowEditing = true;
sfGrid.NavigationMode = NavigationMode.Cell;
sfGrid.AllowLoadMore = true;
sfGrid.AutoGenerateColumns = true;
//sfGrid.AutoGenerateColumnsMode= AutoGenerateColumnsMode.
sfGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Single;
sfGrid.AllowPullToRefresh = true;
sfGrid.CurrentCellEndEdit += SfGrid_CurrentCellEndEdit; ;
}
private async void SfGrid_CurrentCellEndEdit(object sender, GridCurrentCellEndEditEventArgs e)
{
//throw new System.NotImplementedException();
var selectObj = sender as SfDataGrid;
RowColumnIndex index = e.RowColumnIndex;
int selectColumnIndex = index.ColumnIndex; //2
int selectRowIndex = index.RowIndex; //3
var ob=firebaseHelper._returnedEvents;
ViewProgramModel selectObject =ob[selectRowIndex-1];
var newVale = e.NewValue.ToString();
var oldeValue = e.OldValue.ToString();
//Here just judge TARGET Column, you should judge all Columns
if (selectColumnIndex == 2)
{
selectObject.TARGET = Convert.ToInt32(newVale);
}
//If you want to achieve the all Grid change function, you should judge the selectRowIndex for every change
//if (selectRowIndex==1)
//{
// selectObject.MODE = newVale;
//}else if (selectRowIndex==2)
//{
// selectObject.TARGET = Convert.ToInt32( newVale);
//}else if (selectRowIndex == 3)
//{
// selectObject.TRIGGER = newVale;
//}else if (selectRowIndex == 4)
//{
// selectObject.TRIGGERVALUE = Convert.ToInt32(newVale);
//}
await firebaseHelper.UpdateViewProgramModel(selectObject, oldeValue);
}
private async void Button_Clicked(object sender, System.EventArgs e)
{
await firebaseHelper.AddViewProgramModel();
}
private async void Button_Clicked_1(object sender, System.EventArgs e)
{
await firebaseHelper.DeleteViewProgramModel("test");
}
}
I took from a GitHub TkCustomMap project TK.CustomMap, and I want to call my custom service, to fill my custom list, and on ItemSelected event, from autocomplete searchBar to MapCenter it with Coordinates from my list model.
I've tried and I stopped at binding and on ItemSelect event.
Here is my MapPage:
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace TK.CustomMap.Sample
{
public partial class SamplePage : ContentPage
{
public SamplePage()
{
//InitializeComponent();
this.CreateView();
this.BindingContext = new SampleViewModel();
}
private async void CreateView()
{
var autoComplete = new PlacesAutoComplete { ApiToUse = PlacesAutoComplete.PlacesApi.CustomList };
autoComplete.SetBinding(PlacesAutoComplete.MapSelectedCommandProperty, "MapCenter");
var newYork = new Position(40.7142700, -74.0059700);
var mapView = new TKCustomMap(MapSpan.FromCenterAndRadius(newYork, Distance.FromKilometers(2)));
mapView.IsShowingUser = true;
mapView.SetBinding(TKCustomMap.CustomPinsProperty, "Pins");
mapView.SetBinding(TKCustomMap.MapClickedCommandProperty, "MapClickedCommand");
mapView.SetBinding(TKCustomMap.MapLongPressCommandProperty, "MapLongPressCommand");
mapView.SetBinding(TKCustomMap.MapCenterProperty, "MapCenter");
mapView.SetBinding(TKCustomMap.PinSelectedCommandProperty, "PinSelectedCommand");
mapView.SetBinding(TKCustomMap.SelectedPinProperty, "SelectedPin");
mapView.SetBinding(TKCustomMap.RoutesProperty, "Routes");
mapView.SetBinding(TKCustomMap.PinDragEndCommandProperty, "DragEndCommand");
mapView.SetBinding(TKCustomMap.CirclesProperty, "Circles");
mapView.SetBinding(TKCustomMap.CalloutClickedCommandProperty, "CalloutClickedCommand");
mapView.SetBinding(TKCustomMap.PolylinesProperty, "Lines");
mapView.SetBinding(TKCustomMap.PolygonsProperty, "Polygons");
mapView.SetBinding(TKCustomMap.MapRegionProperty, "MapRegion");
mapView.SetBinding(TKCustomMap.RouteClickedCommandProperty, "RouteClickedCommand");
mapView.SetBinding(TKCustomMap.RouteCalculationFinishedCommandProperty, "RouteCalculationFinishedCommand");
mapView.SetBinding(TKCustomMap.TilesUrlOptionsProperty, "TilesUrlOptions");
mapView.SetBinding(TKCustomMap.MapFunctionsProperty, "MapFunctions");
mapView.IsRegionChangeAnimated = true;
autoComplete.SetBinding(PlacesAutoComplete.BoundsProperty, "MapRegion");
RelativeLayout _baseLayout = new RelativeLayout();
_baseLayout.Children.Add(
mapView,
Constraint.RelativeToView(autoComplete, (r, v) => v.X),
Constraint.RelativeToView(autoComplete, (r, v) => autoComplete.HeightOfSearchBar),
heightConstraint: Constraint.RelativeToParent((r) => r.Height - autoComplete.HeightOfSearchBar),
widthConstraint: Constraint.RelativeToView(autoComplete, (r, v) => v.Width));
_baseLayout.Children.Add(
autoComplete,
Constraint.Constant(0),
Constraint.Constant(0));
Content = _baseLayout;
}
}
}
Here is my PlacesAutoComplete class:
using System;
using System.Collections.Generic;
using System.Linq;
using TK.CustomMap.Api;
using TK.CustomMap.Api.Google;
using TK.CustomMap.Api.OSM;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using static TK.CustomMap.Sample.SearchBarModel;
namespace TK.CustomMap.Sample
{
public class SearchBarModel : IPlaceResult
{
public string Subtitle { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class PlacesAutoComplete : RelativeLayout
{
public static BindableProperty BoundsProperty = BindableProperty.Create<PlacesAutoComplete, MapSpan>(
p => p.Bounds,
default(MapSpan));
// TODO: SUMMARIES
public enum PlacesApi
{
//Google,
//Osm,
//Native,
//THIS IS MY LIST!
CustomList
}
private readonly bool _useSearchBar;
private bool _textChangeItemSelected;
private SearchBar _searchBar;
private Entry _entry;
private ListView _autoCompleteListView;
private IEnumerable<IPlaceResult> _predictions;
public PlacesApi ApiToUse { get; set; }
public static readonly BindableProperty MapSelectedCommandProperty =
BindableProperty.Create<PlacesAutoComplete, Command<Position>>(
p => p.SetMap, null);
public List<SearchBarModel> myList = new List<SearchBarModel>();
public Command<Position> SetMap
{
get { return (Command<Position>)this.GetValue(MapSelectedCommandProperty); }
set { this.SetValue(MapSelectedCommandProperty, value); }
}
public double HeightOfSearchBar
{
get
{
return this._useSearchBar ? this._searchBar.Height : this._entry.Height;
}
}
private string SearchText
{
get
{
return this._useSearchBar ? this._searchBar.Text : this._entry.Text;
}
set
{
if (this._useSearchBar)
this._searchBar.Text = value;
else
this._entry.Text = value;
}
}
public new MapSpan Bounds
{
get { return (MapSpan)this.GetValue(BoundsProperty); }
set { this.SetValue(BoundsProperty, value); }
}
public PlacesAutoComplete(bool useSearchBar)
{
this._useSearchBar = useSearchBar;
this.Init();
}
public string Placeholder
{
get { return this._useSearchBar ? this._searchBar.Placeholder : this._entry.Placeholder; }
set
{
if (this._useSearchBar)
this._searchBar.Placeholder = value;
else
this._entry.Placeholder = value;
}
}
public PlacesAutoComplete()
{
this._useSearchBar = true;
this.Init();
}
private void Init()
{
OsmNominatim.Instance.CountryCodes.Add("de");
this._autoCompleteListView = new ListView
{
IsVisible = false,
RowHeight = 40,
HeightRequest = 0,
BackgroundColor = Color.White
};
this._autoCompleteListView.ItemTemplate = new DataTemplate(typeof(MapSearchCell));
View searchView;
if (this._useSearchBar)
{
this._searchBar = new SearchBar
{
Placeholder = "Search for address..."
};
this._searchBar.TextChanged += SearchTextChanged;
this._searchBar.SearchButtonPressed += SearchButtonPressed;
searchView = this._searchBar;
}
else
{
this._entry = new Entry
{
Placeholder = "Sarch for address"
};
this._entry.TextChanged += SearchTextChanged;
searchView = this._entry;
}
this.Children.Add(searchView,
Constraint.Constant(0),
Constraint.Constant(0),
widthConstraint: Constraint.RelativeToParent(l => l.Width));
this.Children.Add(
this._autoCompleteListView,
Constraint.Constant(0),
Constraint.RelativeToView(searchView, (r, v) => v.Y + v.Height));
this._autoCompleteListView.ItemSelected += ItemSelected;
this._textChangeItemSelected = false;
}
private void SearchButtonPressed(object sender, EventArgs e)
{
if (this._predictions != null && this._predictions.Any())
this.HandleItemSelected(this._predictions.First());
else
this.Reset();
}
private void SearchTextChanged(object sender, TextChangedEventArgs e)
{
if (this._textChangeItemSelected)
{
this._textChangeItemSelected = false;
return;
}
this.SearchPlaces();
}
private async void SearchPlaces()
{
try
{
if (string.IsNullOrEmpty(this.SearchText))
{
this._autoCompleteListView.ItemsSource = null;
this._autoCompleteListView.IsVisible = false;
this._autoCompleteListView.HeightRequest = 0;
return;
}
IEnumerable<IPlaceResult> result = null;
if (this.ApiToUse == PlacesApi.CustomList)
{
myList.Add(new SearchBarModel
{
Name = "Test1",
Description = "On item select, show me on map!",
Longitude = 20.4680701,
Latitude = 44.8152658
});
myList.Add(new SearchBarModel
{
Name = "Test2",
Description = "On item select, show me on map!",
Longitude = 20.4233035,
Latitude = 44.805651,
});
myList.Add(new SearchBarModel
{
Name = "Test3",
Description = "On item select, show me on map!",
Longitude = 20.456054,
Latitude = 44.8839925
});
myList.Add(new SearchBarModel
{
Name = "Test4",
Description = "On item select, show me on map!",
Longitude = 20.4328035,
Latitude = 44.8071928,
});
result = myList.OfType<IPlaceResult>().ToList<IPlaceResult>();
}
else
{
result = await OsmNominatim.Instance.GetPredictions(this.SearchText);
}
if (result != null && result.Any())
{
this._predictions = result;
this._autoCompleteListView.HeightRequest = result.Count() * 40;
this._autoCompleteListView.IsVisible = true;
this._autoCompleteListView.ItemsSource = this._predictions;
}
else
{
this._autoCompleteListView.HeightRequest = 0;
this._autoCompleteListView.IsVisible = false;
}
}
catch (Exception x)
{
// TODO
}
}
//From here my code partially works
private void ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null) return;
var prediction = (IPlaceResult)e.SelectedItem;
this.HandleItemSelected(prediction);
}
private void HandleItemSelected(IPlaceResult prediction)
{
if (this.SetMap != null && this.SetMap.CanExecute(this))
{
this.SetMap.Execute(prediction);
}
this._textChangeItemSelected = true;
this.SearchText = prediction.Description;
this._autoCompleteListView.SelectedItem = null;
this.Reset();
}
private void Reset()
{
this._autoCompleteListView.ItemsSource = null;
this._autoCompleteListView.IsVisible = false;
this._autoCompleteListView.HeightRequest = 0;
if (this._useSearchBar)
this._searchBar.Unfocus();
else
this._entry.Unfocus();
}
}
}
I have written code to get async data from Couchbase views:
This is the Implementation Class
AsyncViewResult viewResult =
offerCouchDao.findViewResultAsync(DDN, VIEWNAME).toBlocking().single();
if (viewResult.success()) {
Observable<JsonArray> JAoffer =
offerCouchDao.getAsyncJsonObject(viewResult.rows());
Object response = offerCouchDao.getData(JAoffer);
System.out.println("Data is "+response);
return new OfferResponse(true,"Offer Data",response).toJson();
}
This is OfferCouchDao:
public Observable<AsyncViewResult> findViewResultAsync(String ddn, String viewname) {
ViewQuery allResult = ViewQuery.from(ddn, viewname);
return couchbaseManager.getMobikwikBucket().async().query(allResult);
}
public Observable<JsonArray> getAsyncJsonObject(Observable<AsyncViewRow> viewResult) {
return viewResult.
//extract the document from the row and carve a result object using its content and id
flatMap(new Func1<AsyncViewRow, Observable<JsonObject>>() {
#Override
public Observable<JsonObject> call(AsyncViewRow row) {
return row.document().map(new Func1<JsonDocument, JsonObject>() {
#Override
public JsonObject call(JsonDocument jsonDocument) {
return JsonObject.create()
.put("id", jsonDocument.id())
;
}
})
;
}
}).filter(new Func1<JsonObject, Boolean>() {
#Override
public Boolean call(JsonObject jsonObject) {
String name = jsonObject.getString("name");
return name != null ;
}
})
.collect(new Func0<JsonArray>() { //this creates the array (once)
#Override
public JsonArray call() {
return JsonArray.empty();
}
}, new Action2<JsonArray, JsonObject>() { //this populates the array (each item)
#Override
public void call(JsonArray objects, JsonObject jsonObject) {
objects.add(jsonObject);
}
});
}
public Object getData(Observable<JsonArray> jsonArraay) {
return jsonArraay
.map(new Func1<JsonArray, JsonArray>() {
#Override
public JsonArray call(JsonArray objects) {
return objects;
}
})
.onErrorReturn(new Func1<Throwable, JsonArray>() {
#Override
public JsonArray call(Throwable throwable) {
return null;
}
})
.toBlocking().single();
}
The issue I have is Data returned is null
Here are the logs:
Data is []
Data is null
Also when doing via sync call which is:
else {
JsonArray keys = JsonArray.create();
Iterator<ViewRow> iter = viewResult.rows();
while (iter.hasNext()) {
ViewRow row = iter.next();
JsonObject beer = JsonObject.create();
beer.put("name", row.key());
beer.put("id", row.id());
keys.add(beer);
}
}
I am getting the expected response.
Can Someone help me?