Subsonic - Return only certain columns/properties for display - subsonic

I have a baseclass that handles returning data from the relevant class/table.
I want to have some way of specifying the columns to display. Maybe have a public columns List that gets assigned with all column we want to display?
This is what I have but its not right.
public void SetupGrid<T>() where T : class, new()
{
var db = new MyApp.MyDB();
IRepository<T> repo = new SubSonicRepository<T>(db);
var s = repo.GetAll();
var x = from c in s select new { c.Columns //that match columns I specify };
}

This seems to do it, however unsure if its best practice:
public virtual void SetupGrid<T>() where T : class, new()
{
MyApp.MyDBdb = new MyApp.MyDB();
IRepository<T> repo = new SubSonicRepository<T>(db);
ITable table = repo.GetTable();
List<string> list = new List<string>();
list.Add("CreatedOn");
list.Add("PageID");
list.Add("CreatedBy");
var s = db.SelectColumns(list.ToArray()).
From(table.Name).
OrderAsc(table.Descriptor.Name).ExecuteReader();
bindingSource1.DataSource = s;
}

Related

Is there a way to iterate through the fields in a row of a PXResultSet?

Is it possible to use a foreach loop in a BLC to iterate through the fields of a PXResultSet to get the FieldNames?
Is this doable? I can't seem to find a good way.
Thanks...
The PXResultset records are selected from a view. You can get the field names from the View.
Here's a full example:
public class SOOrderEntry_Extension : PXGraphExtension<SOOrderEntry>
{
public override void Initialize()
{
// Get field list from data view
var dataView = new PXSelect<SOOrder>(Base);
string fieldNames = string.Join(",", GetFieldNames(dataView.View, Base.Caches));
// You don't need result set to get field names
PXResultset<SOOrder> resultSet = dataView.Select();
throw new PXException(fieldNames);
}
public string[] GetFieldNames(PXView view, PXCacheCollection caches)
{
var list = new List<string>();
var set = new HashSet<string>();
foreach (Type t in view.GetItemTypes())
{
if (list.Count == 0)
{
list.AddRange(caches[t].Fields);
set.AddRange(list);
}
else
{
foreach (string field in caches[t].Fields)
{
string s = String.Format("{0}__{1}", t.Name, field);
if (set.Add(s))
{
list.Add(s);
}
}
}
}
return list.ToArray();
}
}
When run, this example will show the fields names used in the data view in Sales Order screen SO301000 as an exception.
Field names are contained in Cache object. If you really need to get field names from PXResultset you need to iterate the cache types in the result set.
Example for first DacType (0) of result set:
public class SOOrderEntry_Extension : PXGraphExtension<SOOrderEntry>
{
public override void Initialize()
{
var dataView = new PXSelect<SOOrder>(Base);
PXResultset<SOOrder> resultSet = dataView.Select();
foreach (PXResult result in resultSet)
{
Type dacType = result.GetItemType(0);
foreach (var field in Base.Caches[dacType].Fields)
PXTrace.WriteInformation(field);
}
}
}

PXView does not contain a definition for Select In Acumatica

I faced such a problem and how I can not overcome:
PXView does not contain a definition for Select and the best extension method overload EnumerableEx.Select<T>(IEnumerable)
My goal is to pass different views to the method, for example, I did it this way and it works with a specific type and a specific view.
var grid = Transaction.Select<TSITransaction>().ToList();
But the problem is that I don't know which view is coming to me
public void ValidationTabInformation<T, K, U>(string viewName, PXView viewQuery, PXView viewQueryCache, PXView cascadindView, PXView enablingConditions)
where T: TSNTagQueries
where K: TSNWCascade
where U: TSNTransConditions
{
var grid = viewQuery.SingleToArray().Select<T>().ToList();
var cascading = cascadindView.SingleToArray().Select<K>().ToList();
var deleted = viewQueryCache.Cache.Deleted.RowCast<T>().ToList();
var conditions = enablingConditions.SingleToArray().Select<U>().ToList();
var isRequired = string.Empty;
//... doing something
}
protected void DataFieldValidation()
{
//ValidationAsset();
//ValidationEmployee();
//ValidationTransaction();
//ValidationLinkInfo();
ValidationTabInformation<TSNAsset, TSNCascadeAsset, TSNAssetConditions>(Asset.Name, Asset.View, Asset.View,CascadingAsset.View, TagAssetEnablingConditions.View);
}
Exception:
https://i.stack.imgur.com/ad4fO.png
Try something like this
var grid = viewQuery.SelectMultiBound(new object[] {T});

Spark Cassandra Connector Java API append/remove data in a collection fail

I am trying to append values to a column of type set, via the JAVA API.
It seems that the connector disregards the type of CollectionBehavior I am setting,
and always overrides the previous collection.
Even when I use CollectionRemove, the value to be removed is added to the collection.
I am following the example as shown in:
https://datastax-oss.atlassian.net/browse/SPARKC-340?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel
I am using:
spark-core_2.11 2.2.0
spark-cassandra-connector_2.11 2.0.5
Cassandra 2.1.17
Could it be that this feature is no supported on those versions?
Here is the implementation code:
// CASSANDRA TABLE
CREATE TABLE test.profile (
id text PRIMARY KEY,
dates set<bigint>,
)
// ENTITY
public class ProfileRow {
public static final Map<String, String> namesMap;
static {
namesMap = new HashMap<>();
namesMap.put("id", "id");
namesMap.put("dates", "dates");
}
private String id;
private Set<Long> dates;
public ProfileRow() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Set<Long> getDates() {
return dates;
}
public void setDates(Set<Long> dates) {
this.dates = dates;
}
}
public void execute(JavaSparkContext context) {
List<ProfileRow> elements = new LinkedList<>();
ProfileRow profile = new ProfileRow();
profile.setId("fGxTObQIXM");
Set<Long> dates = new HashSet<>();
dates.add(1l);
profile.setDates(dates);
elements.add(profile);
JavaRDD<ProfileRow> rdd = context.parallelize(elements);
RDDAndDStreamCommonJavaFunctions<T>.WriterBuilder wb = javaFunctions(rdd)
.writerBuilder("test", "profile", mapToRow(ProfileRow.class, ProfileRow.namesMap));
CollectionColumnName appendColumn = new CollectionColumnName("dates", Option.empty(), CollectionAppend$.MODULE$);
scala.collection.Seq<ColumnRef> columnRefSeq = JavaApiHelper.toScalaSeq(Arrays.asList(appendColumn));
SomeColumns columnSelector = SomeColumns$.MODULE$.apply(columnRefSeq);
wb.withColumnSelector(columnSelector);
wb.saveToCassandra();
}
Thanks,
Shai
I found the answer. There are 2 things I had to change:
Add the primary key column to the column selector.
WriterBuilder.withColumnSelector() generates a new instance of WriterBuilder, so I had to store the new instance.
:
RDDAndDStreamCommonJavaFunctions<T>.WriterBuilder wb = javaFunctions(rdd)
.writerBuilder("test", "profile", mapToRow(ProfileRow.class, ProfileRow.namesMap));
ColumnName pkColumn = new ColumnName("id", Option.empty())
CollectionColumnName appendColumn = new CollectionColumnName("dates", Option.empty(), CollectionAppend$.MODULE$);
scala.collection.Seq<ColumnRef> columnRefSeq = JavaApiHelper.toScalaSeq(Arrays.asList(pkColumn, appendColumn));
SomeColumns columnSelector = SomeColumns$.MODULE$.apply(columnRefSeq);
wb = wb.withColumnSelector(columnSelector);
wb.saveToCassandra();

Xpages : How to get all members from a group in java (using ODA) and get their common name

I thought I was pretty clever writing this method to load up members of a group. But the values that are returned are not in common name format:
How can I easily grab these values in common name or easily transform them to common name?
private void loadNetworkTeam() {
try {
Session session = Factory.getSession();
Database tmpDB = session.getCurrentDatabase();
Database tmpDB2 = session.getDatabase(tmpDB.getServer(), "names.nsf");
View grpView = tmpDB2.getView("($VIMGroups)");
Vector<Object> nTeam = new Vector<Object>();
nTeam.addElement("NetWorkTeam");
Document grpDoc = grpView.getFirstDocumentByKey("Network Team");
Item itm = grpDoc.getFirstItem("members");
networkTeam.addAll(itm.getValues());
} catch (Exception e) {
XspOpenLogUtil.logError(e);
}
}
Use class Name and its method getCommon() to convert a hierarchical name into a common name.
Example:
Item itm = grpDoc.getFirstItem("members");
List<String> networkTeam = new ArrayList<String>();
for (Object value : itm.getValues()) {
networkTeam.add(session.createName((String) value).getCommon());
}

Orchard cms Html from IContent items

My question is related to this one, but instead of changing a question I thought it Would be better to ask a new one.
I've now got a list of IContent items using the _taxonomyService.GetContentItems(term)
as suggested by #Bertrand Le Roy in the question mentioned above
But how do I turn this into a useful Html string, that I can update on the client via an ajax post?
public class HomeController : Controller
{
private readonly IOrchardServices _services;
private readonly IBlogService _blogService;
private readonly IBlogPostService _blogPostService;
private readonly IFeedManager _feedManager;
private readonly IArchiveConstraint _archiveConstraint;
private readonly ITaxonomyService _taxonomyService;
public HomeController(
IOrchardServices services,
IBlogService blogService,
IBlogPostService blogPostService,
IFeedManager feedManager,
IShapeFactory shapeFactory,
IArchiveConstraint archiveConstraint,
ITaxonomyService taxonomyService) {
_services = services;
_blogService = blogService;
_blogPostService = blogPostService;
_feedManager = feedManager;
_archiveConstraint = archiveConstraint;
T = NullLocalizer.Instance;
Shape = shapeFactory;
_taxonomyService = taxonomyService;
}
dynamic Shape { get; set; }
public Localizer T { get; set; }
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult ListByArchive(string path, IEnumerable<string> category)
{
try
{
// get year and month from path
path = path.ToLower().Substring(path.LastIndexOf(#"/archive/", StringComparison.Ordinal) + 9);
var date = path.Split('/');
var month = int.Parse(date[1]);
var year = int.Parse(date[0]);
// get list of terms ids from strings
var taxonomyPart = _taxonomyService.GetTaxonomyByName("Category");
var terms = category.Select(cat => _taxonomyService.GetTermByName(taxonomyPart.Id, cat)).ToList();
// get list of content items by term avoiding duplicates
var posts = new List<IContent>();
foreach (var term in terms)
{
var items = _taxonomyService.GetContentItems(term);
foreach (var item in items)
{
if (!posts.Select(p => p.Id).Contains(item.Id))
{
posts.Add(item);
}
}
}
// filter by date
var byDate = posts.Where(x =>
{
var publishedUtc = x.ContentItem.As<CommonPart>().CreatedUtc;
return
publishedUtc != null
&& publishedUtc.Value.Month == month
&& publishedUtc.Value.Year == year;
});
....
This gets me my list of IContent, but how do I get a the html for the rendered list ?
I've tried
var range = byDate.Select(x => _services.ContentManager.BuildDisplay(x, "Summary"));
var list = Shape.List();
list.AddRange(range);
dynamic viewModel = Shape.ViewModel().ContentItems(list);
var html = View((object)viewModel);
return Json(new { html = html });
but it returns an empty view,
{"html":{"MasterName":"","Model":[],"TempData":[],"View":null,"ViewBag":{},"ViewData":[],"ViewEngineCollection":[{"HostContainer":{}}],"ViewName":""}}
I have a view called ListByArchive.cshtml, that matches the one it the orchard.blog module.
As an aside, I should be returning a partial view result, instead of a jason result, but when I change the Action result type I get a 404. result from the server.
This is never going to work the way you think it does:
var html = View((object)viewModel);
The easiest way to return HTML representing the content item is to:
Mark your action with ThemedAttribute, ie. [Themed(false)]
Return new ShapeResult(this, viewModel) (full view) or new ShapePartialResult(this, viewModel) (partial view) instead of Json(new { html = html })
Rendering a shape/view to string inside the action is also possible, but way more tricky.
EDIT: I assumed you already have /Views/ViewModel.cshtml file in place. Like Bertrand Le Roy noted below - if it's not there, you need to add one to be able to create a shape using Shape.ViewModel().

Resources