I am new to Power Builder and I would like to ask how can I represent my objects in a table form. For example, given an ArrayList in java I have implemented the code like this:
table = new JTable();
scrollPane.setViewportView(table);
DefaultTableModel tableModel =
new DefaultTableModel(
new String[] {
"ScheduleNo",
"Start Date",
"End Date",
"No of days",
"Principal Expected",
"Interest Expected",
"EMI amount",
"Factor",
"MeanFactor"}
, 0);
for (Schedule s : pf.getSchedules()){
Integer schNo = s.getScheduleNo();
String startDate = df.format(s.getStartDate());
String endDate = df.format(s.getEndDate());
Integer noofdays = s.getNoOfDays();
String prinExp = String.format("%.2f", s.getPrincipalAmt());
String intExp = String.format("%.2f", s.getInterestAmt());
String emi = String.format("%.2f", s.getAmortizedAmount());
String factor = String.format("%.6f", s.getFactor());
String mean = String.format("%.6f", s.getProductByFactor());
Object[]data = {schNo, startDate, endDate, noofdays, prinExp, intExp,
emi, factor, mean};
tableModel.addRow(data);
}
table.setModel(tableModel);
But I cannot find a way to do it in PowerBuilder without having a connection to a database and pick the data from there which is totally not the case.
The data come from an User Object array[] and have exactly the same form like in the Java example above.
Without really knowing what you are trying to accomplish it appears to me that you could use a 'normal' PowerBuilder datawindow but when you define it you make it's datasource as external. This type of datawindow does not require a connection to a database. You define the 'fields' of the datasource as strings, numeric, etc. when you create it.
In code you can create a datawindow (or datastore for that matter) control, assign the external datasource datawindow object to it, insert a row, then populate the fields with data of the corresponding datatype.
Example usage:
datawindow ldw
long llrow
ldw = CREATE datawindow
ldw.dataobject = 'myExternalDatawindowObject'
llrow = ldw.insertrow(0)
ldw.setitem(llrow,'stringcolumn','my example string')
ldw.setitem(llrow,'numericcolumn',1234)
It's been a while since I used PowerBuilder, but IIRC you should be able to use a DataStore without having a database connection.
Related
My JSON data looks as shown below. Sometimes it's changed the Field Name Position. How to store this data into a Datatable and must be in proper column. Suggest any solution for VB.Net
<string xmlns="http://tecogis.com/">[
{
"REPORT NUMBER":"LG534248650",
"REPORT CITY DATE":"June 22, 2022",
"DESCRIPTION":"LABORATORY GROWN DIAMOND",
"SHAPE AND CUT":"ROUND BRILLIANT",
"CARAT WEIGHT":"1.07 Carat",
"COLOR GRADE":"D",
"CLARITY GRADE":"SI 2",
"CUT GRADE":"VERY GOOD",
"POLISH":"EXCELLENT",
"SYMMETRY":"EXCELLENT",
"Measurements":"6.41 - 6.44 x 4.10 mm",
"Table Size":"57%",
"Crown Height":"15.5% - 35.4°",
"Pavilion Depth":"43.5% - 41.1°",
"Girdle Thickness":"MEDIUM TO SLIGHTLY THICK (FACETED)",
"Culet":"POINTED",
"Total Depth":"63.9%",
"FLUORESCENCE":"NONE",
"COMMENTS":"As Grown - No indication of post-growth treatment\r\nThis Laboratory Grown Diamond was created by High Pressure High Temperature (HPHT) growth process\r\nType II\r\n",
"Inscription(s)":"LABGROWN IGI LG534248650\u003cbr\u003e",
"REPORT_SUF":"LEGAL",
"PDF_FLAG":"Y",
"REPORT1_PDF":"FDR534248650.pdf"
}
]</string>
This is the missing piece you need. Note that it's from my own project so just adjust accordingly for your situation.
Before this, you just need to create a List of your custom type, populate it from your JSON (see Hursey's answer) and reference it instead of BlogList from my code.
This code will then transfer the data from your List into a DataTable which is the DataSource for the DataGridView.
'Declare a DataTable:
Private BlogTable As New DataTable
'Through code, modify a DataGridView instance on your form and clear things:
dgvBlogs.Columns.Clear()
dgvBlogs.DataSource = Nothing
'Set up our columns in the DataTable:
BlogTable.Columns.Add("blogname")
BlogTable.Columns.Add("username")
BlogTable.Columns.Add("password")
dgvBlogs.AutoGenerateColumns = True
dgvBlogs.DataSource = BlogTable
'Put data from JSON into the DataSource:
BlogTable.Rows.Clear()
For Each item As BlogRecord In BlogList
Dim row As DataRow = BlogTable.NewRow()
row("blogname") = item.BlogName
row("username") = item.Username
row("password") = item.Password
BlogTable.Rows.Add(row)
Next
So, conceptually, it's like this:
JSON -> List Of(Your Class) -> DataTable -> DataGridView.DataSource
You turn your JSON into a list of whatever custom item type you want to call it. Then you populate a DataTable from that. And you be sure that your DataGridView.DataSource property is set to your DataTable.
This works for me. The only thing to add is double-check the AutoGenerateColumns because for some reason in my code first I set it to True and then later to False. I'm sure that was just me experimenting and I never cleaned it up.
below is the array of strings , ie , the names of the files and folders is something i will get in the array. now from this array i need to select the newest macro file. ie , among all the strings which ends with xslm in the string array , i will select the one which has the string 20200817_W.xslm .which is the latest file kept.
Edit :
for Min.Rep of the prob ,
here we are talking about a string array like below
{IOH Bot Files , Archive , IOH_AllPlants_BI_2020817_W.xlsm, IOH_AllPlants_BI_2020817_W.xlsm ,... }
from this array i need to choose , IOH_AllPlants_BI_2020817_W.xlsm- because this string has a date component in it and it is the latest in the available list of strings
You don't even need LINQ for this one, because of the regularity of the data:
Array.Sort(arr2)
Dim latestOne = arr(arr.Length-1)
Perhaps we should ensure only xlsm files of the right name are considered:
Dim arr2 = Array.FindAll(arr, Function(x) x.StartsWith("IOH_AllPlants_BI_") AndAlso x.EndsWith("xlsm"))
Array.Sort(arr)
Dim latestOne = arr(arr.Length-1)
We could use LINQ, and (keeping our "only matching names" logic) rather than using an expensive sort, just ask for the Max:
Dim onlyIOHXLSMFiles = arr.Where(Function(x) x.StartsWith("IOH_AllPlants_BI_") AndAlso x.EndsWith("xlsm"))
Dim latestOne = arr.Max()
We don't need to parse this date because it's yyyyMMdd; it sorts just fine as a string. Because it's just a simple string property it is fine to use with just Max which is more efficient than the typical "OrderBy/First" approach.
If the list was not just of a simple type, but instead was eg Person and you were wanting the most recently born Person (rather than just their birthdate, which is what Max would give you) you could:
Dim lastOne = personArr.OrderBy(Function(p) p.Birthdate).Last()
I use OrderBy/Last rather then OrderByDescending/First because it's fewer characters to type for the same effect
All these code samples (with the exception of the last one) make use of an array arr created like:
Dim arr = {"IOH Bot Files" , "Archive" , "IOH_AllPlants_BI_2020817_W.xlsm", "IOH_AllPlants_BI_2020817_W.xlsm" , ... }
See sample logic below which returns what you need. You can change the logic according to your need. You should read the file names to an array and use below logic.
using System;
using System.Linq;
namespace SampleConsoleApp
{
class Program
{
static void Main(string[] args)
{
string[] data = new string[] {
"IOH_AllPlants_BI_20200810_W.xslm"
, "IOH_AllPlants_BI_20200803_W.xslm"
, "IOH_AllPlants_BI_20200727_W.xslm"
, "IOH_AllPlants_BI_20200720_W.xslm",
"IOH_AllPlants_BI_20200817_W.xslm"
, "IOH_AllPlants_BI_20200713_W.xslm"
, "IOH_AllPlants_BI_20200706_W.xslm"};
var result = data.Select(s => s.Split('_')).Select(x => x[3]).OrderByDescending(x => x).First();
//result returns 20200817
}
}
}
I'm trying to get data from an Azure SQL Server. I've Been able to get the data through this method:
let db = dbSchema.GetDataContext()
let serviceType = db.table
serviceType
I then go on to do some type casting where I get the actual data. But as my program has progressed I need a new way of getting the data.
I'm able to get a list of column names with this piece of code:
let columnList = (new SqlCommandProvider<"select * from Information_schema.Columns where table_name = #tableName",connectionString).Execute(tableName)
I'm wondering if there's a similar way to get the data.
I've tried:
let data = (new SqlCommandProvider<"select * from #tableName",connectionstring).Execute(tableName)
But I get this error: "Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of object. This may allow the lookup to be resolved."
I came up with this.
let GetData (tableName : string) =
let cn = new SqlConnection(connectionstring)
cn.Open()
let sQL = "select * from [" + tableName + "]"
let db = new SqlCommand(sQL, cn)
db.ExecuteReader()
From here you can access your data. So assign db.ExecuteReader() to a variable then...
let dataSource = db.ExecuteReader()
let mutable tableData = List.empty
while dataSource.Read() do
let rowLength = dataSource.FieldCount
let rowData = Array.zeroCreate(rowLength)
for i = 0 to dataSource.FieldCount-1 do
rowData.SetValue(dataSource.GetValue(i),i)
tableData <- rowData :: tableData
tableData |> List.toArray
This returns all the values in the table
This is one way (using the SqlClient type provider) to select all data from a table. If your table is too large it will return a lot. So I just select the Top 1000 rows. Replace tablenn with your choice of table name. You can parametrize the columns, but if you need to put the table name itself as a parameter you might need to use a Stored Procedure that takes a Table as a parameter (or use quotations in other type providers).
However, this is a string so it's very easy to build it. Then again, it has to be a literal.
#r #"..\packages\FSharp.Data.SqlClient.1.8.2\lib\net40\FSharp.Data.SqlClient.dll"
open FSharp.Data
open System
[<Literal>]
let connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=C:\Users\userName\Documents\Test.sdf.mdf;Integrated Security=True;Connect Timeout=10"
[<Literal>]
let tblnn = "MyBigTable"
[<Literal>]
let qry = "SELECT TOP 1000 * FROM " + tblnn
let cmd = new SqlCommandProvider<qry, connectionString>(connectionString)
cmd.Execute() |> Seq.toArray
You can also use the stock SqlDataConnection type provider. It also makes it easy to select all data from a table.
I'm trying to create a SpatialObject in C# and pass it to my SQL Server database via a
DataSet, but I can't figure how to pass it to the DataSet :/
When I try to add the element to the params of DS it just get as param
CONVERT(geography, '')
but do not receive anything, is there any way I can pass the object to the DS or should I do it via a stored procedure?
Here is the part of my code I'm using
SqlGeographyItem.BeginGeography(OpenGisGeographyType.Point);
string RadioLatLng = Points.Remove(Points.Length - 1);
string[] tokens = RadioLatLng.Split(',');
decimal.TryParse(HiddenRadio.Value, out Radio);
SqlGeographyItem.BeginFigure(Convert.ToDouble(tokens[1]), Convert.ToDouble(tokens[0]));
SqlGeographyItem.EndFigure();
SqlGeographyItem.EndGeography();
SqlGeographyFig = SqlGeographyItem.ConstructedGeography;
SqlGeographyFig.STBuffer(Convert.ToDouble(Radio));
DS_GeofenceTableAdapters.Geofence1TableAdapter ta_geocercas = new DS_GeofenceTableAdapters.Geofence1TableAdapter();
DS_GeofenceTableAdapters.GeofenceClientTableAdapter tagc = new GeofenceClientTableAdapter();
int IdGeo = Convert.ToInt32(ta_geocercas.InsertQuery(4, this.txt_nombre.Text, Type, Points, Buffer, DateTime.Now, "Active", Radio, Color, route));
I am trying to create a query in Linq to Entities. I want it to return objects that include a DateTime property derived from strings in the table I am querying. The data (in SQL Server) has a string date field (in the database it appears as VARCHAR(8)) called date_occurred. It has a String time field (varchar(6)) called time_occurred.
An example of the contents of date_occurred is "20131007" to represent Oct. 7, 2013. An example of the contents of time_occurred is "145710" to mean 10 seconds after 2:57pm.
I have tried two methods that don't work:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New AuditEntry With {
.EventTime = DateTime.ParseExact(Trim(e.date_occurred) & Trim(e.time_occurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
.ServerName = e.server_name
}
This throws a NotSupportedException with a message stating: "LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression."
Before that, I tried:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New AuditEntry With {
.EventTime = New DateTime(Integer.Parse(e.date_occurred.Substring(0, 4)),
Integer.Parse(e.date_occurred.Substring(4, 2)),
Integer.Parse(e.date_occurred.Substring(6, 2)),
Integer.Parse(e.time_occurred.Substring(0, 2)),
Integer.Parse(e.time_occurred.Substring(2, 2)),
Integer.Parse(e.time_occurred.Substring(4, 2))),
.ServerName = e.server_name
}
This also throws a NotSupportedException. In this case, the message states: "Only parameterless constructors and initializers are supported in LINQ to Entities."
Is what I am trying to do possible using Linq to Entities?
Edit: Comment Alert
For those who read this post later, Moho and Matt Johnson have made especially helpful comments. I have marked these with +1.
Select an anonymous class that contains the fields of interest (called a projection), then create DateTime struct per item after the IQueryable has been enumerated:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New With {
.DateOccurred = e.date_occurred,
.TimeOccurred = e.time_occurred,
.ServerName = e.server_name
}
Dim q2 = From e In ATQuery.ToArray()
Select New AuditEntry With {
.EventTime = DateTime.ParseExact(Trim(e.DateOccurred) & Trim(e.TimeOccurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
.ServerName = e.ServerName
}
Your New DateTime contains only integer, so it looks like 20131008011300 (for 2013/10/08 01:13:00)
/ between date, : between time and a space between date and time are missed