ListField displays no ListSTore data Ext GWT - gwt-rpc

I have an RPC method that returns a raw data from DB.
I am trying to fill the lisfield with this data using ListStore.
Everything is ok, but when ListField is rendered it have rows, but no displaying data. So I can select a row and navigate from first row to las, but nothing to view.
So whats the problem? Should I add a store to LisStore after store is loaded with data, how can I do that?
rpc = RpcInit.initRpc();
RpcProxy<List<WebasystProductData>> proxy = new RpcProxy<List<WebasystProductData>>() {
#Override
public void load(Object loadConfig,
AsyncCallback<List<WebasystProductData>> callback) {
rpc.getWebasystProductData(callback);
}
};
BeanModelReader reader = new BeanModelReader();
ListLoader<ListLoadResult<BeanModel>> loader = new BaseListLoader<ListLoadResult<BeanModel>>(proxy, reader);
store = new ListStore<BeanModel>(loader);
ListField<BeanModel> feedList = new ListField<BeanModel>();
feedList.setStore(store);
feedList.setDisplayField("productIdWA");
loader.load();

Related

How to get TreeProvider.SelectNodes to return all data in preview mode like CMSRepeater does

if I provide the data query as properties of the CMSRepeater, the repeater shows all items (published or not) in preview mode and only published items on the live site.
However, if I try to pass a datasource to the repeater, I can't get it to do the same thing.
Is there some property or method I'm missing?
Works
<cms:CMSRepeater ID="rep2" runat="server" EnableViewState="true"
Path="./%" OrderBy="NodeOrder ASC"
MaxRelativeLevel="1"
ClassNames="MyClassName"
SelectedColumns="Col1, col2, etc">
</cms:CMSRepeater>
Does Not Work
private DataSet LoadRepeaterItemsWithoutCache()
{
var columns = #"col1,col2";
var path ="./%";
TreeProvider tree = new TreeProvider();
return tree.SelectNodes("MyClassName")
.OnCurrentSite()
.Path(path)
.OrderBy("NodeOrder")
.NestingLevel(1)
//.Published(true/false)
//.CheckPermissions(true/false)
.CombineWithDefaultCulture(false)
.Columns(columns);
}
var tnds = LoadRepeaterItemsWithoutCache();
rep2.DataBindByDefault = false;
rep2.HideControlForZeroRows = true;
if (!DataHelper.DataSourceIsEmpty(tnds))
{
rep2.DataSource = tnds;
rep2.DataBind();
}
Looks like you need to modify your query a bit. Your function is expecting a DataSet as a return value and you're returning an ObjectQuery. If you want or need to return a DataSet then add .Result to the end of your .SelectNodes() method.
.Columns(columns).Result;
The other option is to return an ObjectQuery and simply assign that to the repeater and let the natural lifecycle process things.
public override void OnContentLoaded()
{
//rep2.DataBindByDefault = false;
rep2.HideControlForZeroRows = true;
TreeProvider tree = new TreeProvider();
rep2.DataSource = tree.SelectNodes("MyClassName")
.OnCurrentSite()
.Path(path)
.OrderBy("NodeOrder")
.NestingLevel(1)
//.Published(true/false)
//.CheckPermissions(true/false)
.CombineWithDefaultCulture(false)
.Columns(columns);
}
I think you can try this way:
private DataSet LoadRepeaterItemsWithoutCache()
{
var columns = #"col1,col2";
var path ="./%";
TreeProvider tree = new TreeProvider();
var datasource = tree.SelectNodes("MyClassName")
.OnCurrentSite()
.Path(path)
.OrderBy("NodeOrder")
.NestingLevel(1)
//.Published(true/false)
//.CheckPermissions(true/false)
.CombineWithDefaultCulture(false)
.Columns(columns);
//If is in LiveSite mode, then return only published
if (PortalContext.ViewMode == ViewModeEnum.LiveSite)
datasource = datasource.Published();
return datasource;
}
Before return the datasource, check if the site is in LiveSite mode. If true return only the Published nodes, otherwise return Published and Unpublished nodes.
I've not tested it, but hope it works.

Save Image file on persist method

I have been trying to save image file that's been copied from screenshot and pasted into the PXImage control. Now, when I save the record I am trying to save the image as well and save the name of the file in database record along with other DAC fields.
Below is the js code that sets the screenshot image into the PXImage control.
document.onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
if (items.length > 0) {
var imgControl = document.querySelectorAll('.note-m img');
//get the last screenshot
var item = items[items.length - 1];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function (event) {
var result = event.target.result;
imgControl[0].src = result;
px_alls["ds"].executeCallback("saveScreenshotImage","test");
};
reader.readAsDataURL(blob);
}
}
}
This is how it looks when I press (Ctrl+V) on the screenshot.
Now, I want to save this image and generate a file name that I can save on DAC field called 'ScreenShotImage' along with the record.
I thought of creating an action and calling that via js but I couldn't succeed on passing image as a command argument.
Action method in graph:
public PXAction<Ticket> saveScreenshotImage;
[PXButton]
public virtual IEnumerable SaveScreenshotImage(PXAdapter adapter)
{
throw new PXException("test...");
}
Calling via JS
px_alls["ds"].executeCallback("saveScreenshotImage");
Is there any way, I can get that particular file on Persist method?
public override void Persist()
{
base.Persist();
}
Thank you.

azure table storage pagination for request 10 items each time

Basically I am trying to get pagination working when requesting entities of azure table storage. i.e. Press next button gets the next 10 entities & Press previous button gets the previous 10 entities. A relatively close example Gaurav Mantri's Answer. But my question is how do I get the nextPartitionKey and nextRowKey from a HTML button attribute and store in to a array/list in order to keep track of current page so I can get the next/previous items?Code example would be very appreciated.
Thanks!
This is something I have right now which gets a range of data based on pageNumber request
private async Task<List<UserInfo>> queryPage(CloudTable peopleTable, string item, int pageNumber)
{
// Construct the query operation for all customer entities
TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, item));
// Print the fields for each customer.
TableContinuationToken token = null;
//TodoItem data = new TodoItem();
List<UserInfo> data = new List<UserInfo>();
do
{
TableQuerySegment<CustomerEntity> resultSegment = await peopleTable.ExecuteQuerySegmentedAsync(query, token);
token = resultSegment.ContinuationToken;
foreach (CustomerEntity entity in resultSegment.Results)
{
data.Add(new UserInfo
{
// add data
});
}
} while (token != null);
//get a subset of all entity
List<UserInfo> sublist = data.GetRange(0, pageNumber);
return sublist;
}
Managed to solved the problem under Gaurav's help.
Here is the code, not perfect but works.
private async Task<List<UserInfo>> queryPage(CloudTable peopleTable, string item, string NextPartitionKey , string NextRowKey, int itemNumber)
{
// Construct the query operation for all customer entities
TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, item)).Take(itemNumber);
// Print the fields for each customer.
List<UserInfo> data = new List<UserInfo>();
Tabletoken.NextPartitionKey = NextPartitionKey;
Tabletoken.NextRowKey = NextRowKey;
TableQuerySegment<CustomerEntity> resultSegment = await peopleTable.ExecuteQuerySegmentedAsync(query, Tabletoken);
Tabletoken = resultSegment.ContinuationToken;
foreach (CustomerEntity entity in resultSegment.Results)
{
data.Add(new UserInfo
{
//add data
});
}
return data;
}
private TableContinuationToken Tabletoken = new TableContinuationToken();
and declare it use a tuple.
Tuple<List<UserInfo>, string, string > tuple =
new Tuple<List<UserInfo>, string, string>(data, Tabletoken.NextPartitionKey, Tabletoken.NextRowKey);

Image downloaded from Azure Storage not being displayed

I'm new to Xamarin. I'm trying display a list of downloaded images. I am downloading images from an APP API on Azure, where I stored the file on Azure Storage.
My server code is the following:
public HttpResponseMessage Get(string PK, string RK)
{
//Creating CloudBlockBlolb...
byte[] bytes = new byte[blockBlob.Properties.Length]
for(int i = 0; i < blockBlob.Properties.Length; i++){
bytes[i] = 0x20;
}
blockBlob.DownloadToByteArray(bytes, 0);
HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new ByteArrayContent(bytes);
resp.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpg");
return resp;
}
My Xamarin code is the following:
public MainPage ()
{
//...
List<PicturePost> list = new List<PicturePost>{
new PicturePost("title", "subtitle", "link/api/Pictures?PK=xxx&RK=yyy")
};
InitializeComponent ();
listView.ItemTemplate = new DataTemplate (typeof(CustomImageCell));
listView.HasUnevenRows = true;
listView.ItemsSource = list;
//...
}
And here is the relevant code for CustomImageCell:
var image = new Image ();
image.SetBinding (Image.SourceProperty, "image");
//...
horizontalLayout.Children.Add (image);
I know that my API call works, because when I test it on the browser, it returns the image. I also know that if I use any random links such as http://www.natureasia.com/common/img/splash/thailand.jpg the image is downloaded and displayed properly. It is only when I use the API link that it doesn't seem to be working. Can someone tell me what I am doing wrong?
so in my public MainPage(), I added the following:
listView.BeginRefresh ();
listView.EndRefresh ();
I realized at some point that the images would take some time to download. I assume that when the listView was created, the images were not finished downloading, so I added the code above... Pretty sure this is not the best way to do this (probably an await would be better, but I don't know where).

Event firing continuously

I wrote a method which changes backcolor of the rows before painting gridview in devexpress. It works fine but I realized that my code begins slowing down. Then I've found that the event firing continuously. It never stops. How can I handle this? Is there any way to stop firing event manually after gridview painted or should I try to solve this problem with an another event or another method???
Here is my event:
private void gvStep_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
try
{
DataRowView drw = (DataRowView)gvStep.GetRow(e.RowHandle);
byte actionTypeID = (byte)drw.Row["ActionType"];
//string colorCode = (new DivaDs()).GetBackColor(actionTypeID);
string colorCode = divaDs.GetBackColor(actionTypeID);
Color backColor = ColorTranslator.FromHtml(colorCode);
e.Appearance.BackColor = backColor;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}
public string GetBackColor(byte actionTypeID)
{
string color = string.Empty;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[DivaSqlSiteConnString].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(#"Select BackColor from ActionTypes where ID = #actionTypeID"))
{
SqlParameter param = new SqlParameter("#actionTypeID", actionTypeID);
cmd.Parameters.Add(param);
cmd.Connection = conn;
conn.Open();
color = cmd.ExecuteScalar().ToString();
conn.Close();
}
}
return color;
}
My best guess is that some part of your code is just really slow.
The event only fires for each visible cell in the grid. If you attempt to debug the event, focus will shift to the debugger, and when you return to the application the cells need to be redrawn, causing the event to fire again, thus giving the impression that the event fires continuously. It does not, however.
Here are some pointers to improve performance:
You are constructing a new DivaDs every time the event fires
Instead, consider reusing the same instance of the class as a member variable
What happens in the constructor?
Take a closer look at the GetBackColor method or ColorTranslator.FromHtml and see if any modifications can be made to improve performance.
Update
It appears you are querying the database for each cell in the grid. This is a really bad idea.
A simple solution would be to preload all ActionTypes and their background colors (or at least the subset of ActionTypes that is displayed in the grid) before setting the grid's data source.
// member variable
private Dictionary<byte, Color> actionTypeColorDict;
void BuildActionTypeColorDictionary()
{
string connectionString = ConfigurationManager
.ConnectionStrings[DivaSqlSiteConnString].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
// load all action type IDs and corresponding background color:
cmd.CommandText = #"SELECT ActionTypeID, BackColor FROM ActionTypes";
DataTable actionTypeTable = new DataTable();
adapter.Fill(actionTypeTable);
// build a dictionary consisting of action type IDs
// and their corresponding colors
actionTypeColorDict = actionTypeTable.AsEnumerable().ToDictionary(
r => r.Field<byte>("ActionTypeID"),
r => ColorTranslator.FromHtml(r.Field<string>("ColorCode")));
}
}
Call the BuildActionTypeColorDictionary method before setting the data source of the grid. In the RowStyle or CustomDrawCell events, use the new dictionary member to determine the background color. See the following modified version of your RowStyle code:
private void gvStep_RowStyle(object sender,DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
try
{
DataRow row = gvStep.GetDataRow(e.RowHandle);
if (row == null)
return;
byte actionTypeID = row.Field<byte>("ActionImage");
// look up color in the dictionary:
e.Appearance.BackColor = actionTypeColorDict[actionTypeID];
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}
How do you know it's firing continuously? Are you debbuging?
This code runs whenever the grid is redrawn, meaning whenever the form gets focus.
This event runs for each cell - so it will run quite a few times.
If you put a break-point in this event you'll never get out of it. It will break, you will debug, when it's done it will return focus to the form - causing the form to be redrawn using this event and the break-point is reached again.
And just a side note - Whenever I use that event I have to put e.Handled = true; in the code so that the cell isn't "drawn" by anyone but me :)
Finally, I found it. RowStyle event only fires same time with gridview's row count
private void gvStep_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
try
{
DataRowView drw = (DataRowView)gridView1.GetRow(e.RowHandle);
if (drw == null)
return;
byte actionTypeID = (byte)drw.Row["ActionImage"];
string colorCode = divaDs.GetBackColor(actionTypeID);
Color backColor = ColorTranslator.FromHtml(colorCode);
e.Appearance.BackColor = backColor;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
}

Resources