Remove decimal values in supercsv - supercsv

I have following CellProcessor method
private static CellProcessor[] getProcessors() {
final CellProcessor[] processors = new CellProcessor[] {
new NotNull(), // senderId
new NotNull(), // orderId
new NotNull(), // execQuantity
new NotNull(), // execPrice <~~~~~~~~~~~~
new NotNull(new FmtDate("yyyy-MM-dd")), // deliveryDate
};
return processors;
}
As execPrice is Double, output csv file contains decimal values. It has to be double type in bean. I need to change it when writing csv file.
How do I remove decimal values (or convert to integer) in supercsv? I think I have to use FmtNumber in CellProcessor but I don't know how.

private static CellProcessor[] getProcessors() {
DecimalFormat df = new DecimalFormat();
df.applyPattern("#");
final CellProcessor[] processors = new CellProcessor[] {
new NotNull(), // senderId
new NotNull(), // orderId
new NotNull(), // execQuantity
new NotNull(new ParseDouble(new FmtNumber(df))), // execPrice <~~~~~~
new NotNull(new FmtDate("yyyy-MM-dd")), // deliveryDate
};
return processors;
}
Above code worked in case someone with same situation like me might wanna know.

Related

Where is TextFormFieldBuilder?

The code below, which can be found in the last example here (https://kb.itextpdf.com/home/it7kb/examples/creating-form-fields) uses a class called TextFormFieldBuilder. This class doesn't seem to exist in the API though (at least not for c#). I just downloaded the latest nuget package, and the link has "it7kb" so I assume this documentation is for itext 7.
What am I missing? What do I need to do to make the example work?
namespace iText.Samples.Sandbox.Events
{
public class GenericFields
{
public static readonly String DEST = "results/sandbox/events/generic_fields.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new GenericFields().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Paragraph p = new Paragraph();
p.Add("The Effective Date is ");
Text day = new Text(" ");
day.SetNextRenderer(new FieldTextRenderer(day, "day"));
p.Add(day);
p.Add(" day of ");
Text month = new Text(" ");
month.SetNextRenderer(new FieldTextRenderer(month, "month"));
p.Add(month);
p.Add(", ");
Text year = new Text(" ");
year.SetNextRenderer(new FieldTextRenderer(year, "year"));
p.Add(year);
p.Add(" that this will begin.");
doc.Add(p);
doc.Close();
}
private class FieldTextRenderer : TextRenderer
{
protected String fieldName;
public FieldTextRenderer(Text textElement, String fieldName) : base(textElement)
{
this.fieldName = fieldName;
}
// If renderer overflows on the next area, iText uses getNextRender() method to create a renderer for the overflow part.
// If getNextRenderer isn't overriden, the default method will be used and thus a default rather than custom
// renderer will be created
public override IRenderer GetNextRenderer()
{
return new FieldTextRenderer((Text) modelElement, fieldName);
}
public override void Draw(DrawContext drawContext)
{
PdfTextFormField field = new TextFormFieldBuilder(drawContext.GetDocument(), fieldName)
.SetWidgetRectangle(GetOccupiedAreaBBox()).CreateText();
PdfAcroForm.GetAcroForm(drawContext.GetDocument(), true)
.AddField(field);
}
}
}
}
EDIT: I tried the following as it seems to be equivalent logic, but when I run it I get a null reference object on the following line. Specifically, the null reference error happens on the .AddField(field) method call on the last line of the Draw method, but on inspection there is nothing that is null on that line so the error must be coming within that method so I can't tell what the issue is.
PdfTextFormField field = PdfTextFormField.CreateText(drawContext.GetDocument(), GetOccupiedAreaBBox());

Elasticsearch / NEST 6 - storing enums as string

Is it possible to store enums as string in NEST6?
I've tried this but it does not seem to work. Any suggestions?
var pool = new SingleNodeConnectionPool(new Uri(context.ConnectionString));
connectionSettings = new ConnectionSettings(pool, connection, SourceSerializer());
private static ConnectionSettings.SourceSerializerFactory SourceSerializer()
{
return (builtin, settings) => new JsonNetSerializer(builtin, settings,
() => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new StringEnumConverter()
}
});
}
Use the StringEnumAttribute attribute on the property. This signals to the internal serializer to serialize the enum as a string. In using this, you don't need to use the NEST.JsonNetSerializer package
If you'd like to set it for all enums, you can do so with
private static void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(
pool,
(builtin, settings) => new JsonNetSerializer(builtin, settings,
contractJsonConverters: new JsonConverter[] { new StringEnumConverter() }));
var client = new ElasticClient(connectionSettings);
client.Index(new Product { Foo = Foo.Bar }, i => i.Index("examples"));
}
public class Product
{
public Foo Foo { get;set; }
}
public enum Foo
{
Bar
}
which yields a request like
POST http://localhost:9200/examples/product
{
"foo": "Bar"
}
I think the way that you're attempting to set converters should also work and is a bug that it doesn't. I'll open an issue to address.

An issue with editable JFX TableView

I have a little issue with an editable TableView. I want to display data from the database and also be able to edit then which saves it back to the DB.
Now, I can edit it. I have an if statement which checks whether the value is blank (empty or white space) and it works properly, the item in DB doesn't get updated if the value is blank.
My issue is that the blank value still gets displayed. If I click to edit it again, it displays the proper value. Here is a picture of the issue.
Here is the method which creats the table in my view class.
private TableView<Teacher> createTable(){
TableView table = new TableView();
table.setEditable(true);
table.setPrefWidth(500);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
table.getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = table.getColumns().size();
double columnSize = Math.floor(table.getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
surnameColumn.setPrefWidth(columnSize);
nickColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("surname"));
nickColumn.setCellValueFactory(new PropertyValueFactory<>("nick"));
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
table.setItems(observableList);
return table;
}
Here is the part of the controller class to handle the edits.
private void onEditAction(){
view.getNameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getSurnameColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getSurnameColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
view.getNickColumn().setCellFactory(TextFieldTableCell.forTableColumn());
view.getNickColumn().setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Teacher, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if(!(CheckString.isBlank(newValue))) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = view.getTeacherTableView().getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
}
}
}
);
}
I also tried adding, it didn't help though.
else
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getOldValue());
Well, I managed to solve it, here is how if anyone is curious
public class TeacherTableView extends TableView {
private TableColumn<Teacher, String> nameColumn, surnameColumn, nickColumn;
TeacherTableView() {
createTable();
onEditAction();
}
private void createTable(){
setEditable(true);
setPrefWidth(500);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
nameColumn = new TableColumn<>("Jméno");
surnameColumn = new TableColumn<>("Příjmení");
nickColumn = new TableColumn<>("Nick");
getColumns().addAll(nameColumn, surnameColumn, nickColumn);
int columnCount = getColumns().size();
double columnSize = Math.floor(getPrefWidth() / columnCount);
nameColumn.setPrefWidth(columnSize);
nameColumn.setCellValueFactory(cdf -> cdf.getValue().nameProperty());
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setEditable(true);
surnameColumn.setPrefWidth(columnSize);
surnameColumn.setCellValueFactory(cdf -> cdf.getValue().surnameProperty());
surnameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
surnameColumn.setEditable(true);
nickColumn.setPrefWidth(columnSize);
nickColumn.setCellValueFactory(cdf -> cdf.getValue().nickProperty());
nickColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nickColumn.setEditable(true);
List<Teacher> list = new TeacherDao().getAllTeachers();
ObservableList<Teacher> observableList = FXCollections.observableArrayList(list);
setItems(observableList);
}
private void onEditAction(){
nameColumn.setOnEditCommit(this::updateCol);
surnameColumn.setOnEditCommit(this::updateCol);
nickColumn.setOnEditCommit(this::updateCol);
}
private void updateCol(TableColumn.CellEditEvent<Teacher, String> col) {
String newValue = col.getNewValue();
if (CheckString.isNotBlank(newValue)) {
(col.getTableView().getItems().get(
col.getTablePosition().getRow())
).setName(col.getNewValue());
Teacher teacher = (Teacher) getSelectionModel().getSelectedItem();
int id = teacher.getUser_id();
new TeacherDao().updateTeacherNick(id, newValue);
} else {
col.getTableView().refresh();
}
}
}

File upload example for grapevine

I am new to Web API and REST services and looking to build a simple REST server which accepts file uploads. I found out grapevine which is simple and easy to understand. I couldn't find any file upload example?
This is an example using System.Web.Http
var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder);
await Request.Content.ReadAsMultipartAsync(streamProvider);
but the grapevine Request property does not have any method to do that. Can someone point me to an example?
If you are trying to upload a file as a binary payload, see this question/answer on GitHub.
If you are trying to upload a file from a form submission, that will be a little bit trickier, as the multi-part payload parsers haven't been added yet, but it is still possible.
The following code sample is complete untested, and I just wrote this off the top of my head, so it might not be the best solution, but it's a starting point:
public static class RequestExtensions
{
public static IDictionary<string, string> ParseFormUrlEncoded(this IHttpRequest request)
{
var data = new Dictionary<string, string>();
foreach (var tuple in request.Payload.Split('='))
{
var parts = tuple.Split('&');
var key = Uri.UnescapeDataString(parts[0]);
var val = Uri.UnescapeDataString(parts[1]);
if (!data.ContainsKey(key)) data.Add(key, val);
}
return data;
}
public static IDictionary<string, FormElement> ParseFormData(this IHttpRequest request)
{
var data = new Dictionary<string, FormElement>();
var boundary = GetBoundary(request.Headers.Get("Content-Type"));
if (boundary == null) return data;
foreach (var part in request.Payload.Split(new[] { boundary }, StringSplitOptions.RemoveEmptyEntries))
{
var element = new FormElement(part);
if (!data.ContainsKey(element.Name)) data.Add(element.Name, element);
}
return data;
}
private static string GetBoundary(string contenttype)
{
if (string.IsNullOrWhiteSpace(contenttype)) return null;
return (from part in contenttype.Split(';', ',')
select part.TrimStart().TrimEnd().Split('=')
into parts
where parts[0].Equals("boundary", StringComparison.CurrentCultureIgnoreCase)
select parts[1]).FirstOrDefault();
}
}
public class FormElement
{
public string Name => _dispositionParams["name"];
public string FileName => _dispositionParams["filename"];
public Dictionary<string, string> Headers { get; private set; }
public string Value { get; }
private Dictionary<string, string> _dispositionParams;
public FormElement(string data)
{
var parts = data.Split(new [] { "\r\n\r\n", "\n\n" }, StringSplitOptions.None);
Value = parts[1];
ParseHeaders(parts[0]);
ParseParams(Headers["Content-Disposition"]);
}
private void ParseHeaders(string data)
{
Headers = data.TrimStart().TrimEnd().Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries).Select(header => header.Split(new[] {':'})).ToDictionary(parts => parts[0].TrimStart().TrimEnd(), parts => parts[1].TrimStart().TrimEnd());
}
private void ParseParams(string data)
{
_dispositionParams = new Dictionary<string, string>();
foreach (var part in data.Split(new[] {';'}))
{
if (part.IndexOf("=") == -1) continue;
var parts = part.Split(new[] {'='});
_dispositionParams.Add(parts[0].TrimStart(' '), parts[1].TrimEnd('"').TrimStart('"'));
}
}
}
If you are looking for something async to use immediately, you can try to implement the answer to this stackoverflow question, which has not been tested by me.

Bind object data to Int xamarin forms

I have a MasterDetailPage that creates several Department objects. I want to grab the current department number so I can use it to sort a list later on in my program. How do I go about doing that? I have tried binding it to a label and then getting the data from that (very hacky, I know) but that's the only thing I could think of.
Department[] departments = {
new Department ("D", 1),
new Department ("De", 7),
new Department ("G", 4),
new Department ("M", 9),
new Department ("Pr", 167),
new Department ("Fr", 187),
new Department ("H", 169),
new Department ("B", 11),
new Department ("S", 399),
new Department ("N", 407),
new Department ("O", 201),
new Department ("U", 023)
};
ListView listView = new ListView {
ItemsSource = departments
};
this.Master = new ContentPage {
Title = "Departments", // Title required!
Content = new StackLayout {
Children = {
header,
listView
}
}
};
DetailPage2 detailPage = new DetailPage2 ();
this.Detail = detailPage; //detail page is where I want to use deptNum for sorting
listView.ItemSelected += (sender, args) => {
// Set the BindingContext of the detail page.
this.Detail.BindingContext = args.SelectedItem;
// Show the detail page.
this.IsPresented = false;
};
// Initialize the ListView selection.
listView.SelectedItem = departments [0];
}
}
}
Then in my detailpage I want to be able to pull the departmentNumber out and use it as an int
using System;
using Xamarin.Forms;
namespace irisxamarin
{
public class Department :BindableObject
{
public Department (string name, int deptNumber)
{
this.Name = name;
this.DeptNum = deptNumber;
}
public string Name { private set; get; }
public int DeptNum { private set; get; }
public override string ToString ()
{
return Name;
}
}
}
And here is some logic in the detailpage. This is where I would like to grab the current deptNum.
namespace irisxamarin
{
public class DetailPage2 : ContentPage
{
public DetailPage2 ()
{
Request request = new Request ();
Button settingsButton = new Button {
Text = "Settings",
TextColor = Color.Gray
};
//......................
//code above and below
ListView itemsList = new ListView {
ItemsSource = request.GetList (deptNum) //USE INT HERE
};
itemsList.ItemSelected += (sender, args) => {
this.BindingContext = args.SelectedItem;
};
itemLabel.SetBinding (Label.TextProperty, "DeptNum");
//DeptNum is the data I want but not in a label, just the int val
var listFrame = new Frame {
Content = itemsList,
OutlineColor = Color.Silver,
};
Each page is just a C# class. You can pass a value to it the way you would do with any class - generally the easiest way is to
pass values in the constructor
or if the page already exists, create public properties and set the value via the setter
If you want to set a value globally for use throughout your app, you can create a static class that is available everywhere and set state values in that class.

Resources