Wednesday, August 5, 2015

C# Convert image to hex and vice versa

    Here I want to show you how to convert image to hex format and vice versa  using C# language

To convert image to hex data we need only one line of code.
public void ConvertImageToHex(string filePath){
    return BitConverter.ToString(File.ReadAllBytes(fName));
} 
To bring back hex string to image we need to do a little bit more
// saves hex string image to the pathToSave
public static void SaveImageFromHex(string hex, string pathToSave)
{
    // Call function to Convert the hex data to byte array
    byte[] newByte = ToByteArray(hexImgData);
    MemoryStream memStream = new MemoryStream(newByte);

    // Save the memorystream to file
    Bitmap.FromStream(memStream).Save(pathToSave);
}

// Function converts hex data into byte array
private static byte[] ToByteArray(String HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];

    for (int i = 0; i < NumberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    }
    return bytes;
}
original posts: http://www.nullskull.com/faq/40/convert-hex-image-data-to-jpeg.aspx http://stackoverflow.com/questions/18717182/convert-jpeg-image-to-hex-format

JavaFX Table view

I'm writing this post just to remember to myself how did I achieved some goals.
So this first is about JavaFX Table view.
// Allow TableView select multiply rows  
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

//Allow TableView to select single cell     
tableView.getSelectionModel().setCellSelectionEnabled(true);

//TableColumn<Batch, String> codeColumn;
codeColumn.setCellValueFactory(new PropertyValueFactory<Batch, String>(
                "code"));

//Make the codeColumn editable
codeColumn.setCellFactory(TextFieldTableCell.<Batch> forTableColumn());

//Register listner on finish editing cell
codeColumn.setOnEditCommit(value -> {
            System.out.println(value.getRowValue().getCode());
        });

// Make column resizable
codeColumn.prefWidthProperty()
                .bind(tableView.widthProperty().divide(3));



nameColumn.setCellValueFactory(new PropertyValueFactory<Batch, String>(
                "name"));

//If you have some double field than you have to
// use DoubleStringConverter from javafx.util.converters  
nameColumn.setCellFactory(TextFieldTableCell
                .<Batch, String> forTableColumn(new DefaultStringConverter()));

nameColumn.setOnEditCommit(value -> {
            System.out.println(value.getNewValue());
            System.out.println(value.getRowValue().getCode());
        });


nameColumn.prefWidthProperty().bind(tableView.widthProperty().divide(3));


btnCol.setMinWidth(150);


//Creating column which holds buttons
btnCol.setCellValueFactory(new Callback<CellDataFeatures<Batch, Batch>, ObservableValue<Batch>>() {
            @Override
            public ObservableValue<Batch> call(
                    CellDataFeatures<Batch, Batch> features) {
                return new ReadOnlyObjectWrapper(features.getValue());
            }
        });

btnCol.prefWidthProperty().bind(tableView.widthProperty().divide(3));

//Fill column with buttons
btnCol.setCellFactory(new Callback<TableColumn<Batch, Batch>, TableCell<Batch, Batch>>() {
            @Override
            public TableCell<Batch, Batch> call(TableColumn<Batch, Batch> btnCol) {
                return new TableCell<Batch, Batch>() {
                    final Button button = new Button();
                    {
                        button.setMinWidth(130);
                        button.setText("save");
                    }

                    @Override
                    public void updateItem(final Batch person, boolean empty) {
                        super.updateItem(person, empty);
                        //Setting user data to Model
                        button.setUserData(person);
                        setGraphic(button);
                        button.setOnAction(new EventHandler<ActionEvent>() {
                            @Override
                            public void handle(ActionEvent event) {
                              
                                Button btnButton = (Button)event.getSource();
                                //Retrieving user data which is Batch
                                Batch batch = (Batch)btnButton.getUserData();
                                System.out.println(batch.getCode());
                                System.out.println(batch.getName());
                            }
                        });
                    }
                };
            }
        });

//Filling table with data 
tableView.setItems(new BatchService().list());

Monday, January 19, 2015

How to use ControlsFX Autocomplete

First, lets create Fxml file which is the view layer

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.StackPane?>

<GridPane prefHeight="164.0" prefWidth="403.0" xmlns="http://javafx.com/javafx/8"
          xmlns:fx="http://javafx.com/fxml/1" fx:controller="tj.daqiq.operations.controller.ReceiptController">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <Label prefHeight="15.0" prefWidth="72.0" text="From" />
      <Label text="To" GridPane.rowIndex="1" />
      <TextField fx:id="txtAuto" prefHeight="18.0" prefWidth="71.0" GridPane.columnIndex="1" />
      <TextField GridPane.columnIndex="1" GridPane.rowIndex="1" />
   </children>
</GridPane>

Here we placed TextField.


Next in the controller we will bind ControlsFX autocomplete

package tj.daqiq.operations.controller;

import java.net.URL;
import java.util.ResourceBundle;

import org.controlsfx.control.textfield.TextFields;

import tj.daqiq.warehouse.services.BatchService;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

public class ReceiptController implements Initializable {

    @FXML
    private TextField txtAuto;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        BatchService service = new BatchService();

        TextFields.bindAutoCompletion(txtAuto, t-> {
            return service.getSuggestions("code", t.getUserText());
        });
    }
}

The following code will get records from database using hibernate

    @SuppressWarnings("unchecked")
    @Override
    public List<String> getSuggestions(String fieldName, String searchString) {
        logger.info("Getting batch list for autocomplete");
        List<String> list = null;
        HibernateUtil.getSessionFactory().openSession().close();
        Session s = HibernateUtil.getSessionFactory().openSession();
        try {
            s.beginTransaction();
            Query query = s.createQuery("select B." + fieldName + " from Batch B where B."+fieldName + " LIKE :search");
            list = query.setParameter("search", "%"+searchString+"%").setMaxResults(10).list();
            s.getTransaction().commit();
        } catch (Exception ex) {
            logger.error("Other exception {}", ex);
        } finally {
            s.close();
        }      
        return list;
    }

Thats all!