Monthly Archives: August 2015

Quick start on using Hibernate with Postgres 9.4 in IntelliJ

Preliminaries:
1. Install IntelliJ Ultimate. You can get a 30 day trial license.
2. Install PostgresSQL 9.4 or whatever is the latest version today.

What do do:
1. Create a new Maven Project in HIbernate. User the simplest maven archetype to get a good folder structure. I chose the maven-archetype-webapp archetype.
2. Right click on the newly created project and enable Hibernate support through the “Add Framework Support” menu.
3. Add Postgres 9.4 dependencies via Maven.
4. Launch PgAdmin and connect to your PostgreSQL database.
5. Create a users table in PostgresSQL using the following script:

create table Users (
   id SERIAL,
   firstName VARCHAR(100) default NULL,
   lastName  VARCHAR(100) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

6. Under the resources folder, add a new hibernate.cfg.xml file with the following content:

 <session-factory>

    <property name="dialect">org.hibernate.dialect.PostgreSQL82Dialect</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/database</property>
    <property name="connection.username">username</property>
    <property name="connection.password">password</property>

    <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">false</property>
  </session-factory>

7. In the same folder, add a users.hbm.xml file with the following content:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="tut.User" table="Users">
        <meta attribute="class-description">
            This class contains the employee detail.
        </meta>
        <id name="id" type="int" column="id">
            <generator class="increment"/>
        </id>
        <property name="firstName" column="firstname" type="string"/>
        <property name="lastName" column="lastname" type="string"/>
        <property name="age" column="age" type="int"/>
    </class>
</hibernate-mapping>

8. Create a new folder under src/main/java/myco/utils and create a new file HibernateUtils class to host your Session Factory as follows:

public class HibernateUtils {
    private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }
}

9. Create a new folder under src/main/java/myco/models and a new User class as follows:

public class User {
    private String _firstName;
    private String _lastName;
    private int _age;
    private boolean _isEmployed;
    private int _id;

    public String getFirstName(){
        return _firstName;
    }
    public void setFirstName(String name){
        _firstName = name;
    }

    public int getAge(){
        return _age;
    }
    public void setAge(int age){
        _age = age;
    }

    public boolean getIsEmployed(){
        return _isEmployed;
    }
    public void setIsEmployed(boolean isEmployed){
        _isEmployed = isEmployed;
    }
   
    public int getId() {
        return _id;
    }

    public void setId(int _id) {
        this._id = _id;
    }

    public String getLastName() {
        return _lastName;
    }

    public void setLastName(String _lastName) {
        this._lastName = _lastName;
    }

    @Override public String toString(){
        return String.format("%s Ss", _firstName, _age);
    }

}

10. Create a UserResource file under src/main/java/myco/resources as follows:


public class UserResource { 
    public User[] getAll(){

        Session session = HibernateUtils.getSession();
        session.beginTransaction();

        Query query=  session.createQuery("from User where  id > :id");
        query.setParameter("id", 0);

        Object[] users = query.list().toArray();

        User[] toReturn = new User[users.length];
        for (int i = 0; i < users.length; i++){
            toReturn[i] = (User)users[i];
        }

        session.close();
        return toReturn;
    }
 
    public User[] createUsers(User[] users){

        Session session = HibernateUtils.getSession();
        session.beginTransaction();

        for (User user : users){
            System.out.println("Adding user to session " + user.toString());
            session.save(user);
        }

        session.getTransaction().commit();
        session.close();

      return users;
    }
}

11. Create a UserResourceTest class under src/text/java/myco inheriting from TestCase as follows:

public class UserResourceTest extends TestCase {

    @org.junit.Test
    public void testGetAll() throws Exception {

        UserResource userResource = new UserResource();
        User[] users = userResource.getAll();

        Assert.assertTrue(users.length > 0);

    }

    @org.junit.Test
    public void testCreateUsers() throws Exception {

        User user = new User();
        user.setAge(100);
        user.setFirstName("James");
        user.setLastName("Bond");

        UserResource userResource = new UserResource();
        userResource.createUsers(new User[]{ user});

        Assert.assertTrue(user.getId() > 0);
    }
}

12. Go to View | Tools Windows | Maven Project to launch the Maven tools window.
13. Expand the project within the Maven tools window, right click on the clean life cycle and run it.
14. Unless I missed a step, you should see BUILD SUCCESS in your output window.
15. Right click on UserResourceTest and select Run UserResourceTest. Test should all run with green lights.

Happy Coding.

Searchable ComboBox for Windows Universal Apps

Continuing in search for a searchable ComboBox, I decided to build upon the Searchable ListView created in a previous post.

I know, I know that we should favor composition over inheritance but in this case, I will like this searchable ComboBox to carry over all of the behavior from the current ComboBox implementation without requiring to implement the adapter pattern.

This time, I decided to create a custom XAML control so that I can include the custom style in the resources collection of this custom control.  This searchable ComboBox called a ComboPicker, for lack of a better name is represented using the followng XAML:


<local:ListPicker
x:Class="WinUniversalCustomControls.ComboPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WinUniversalCustomControls">
<local:ListPicker.Resources>
<Style TargetType="local:ComboPicker">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="TabNavigation" Value="Once"/>
<Setter Property="IsSwipeEnabled" Value="True"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto"/>
<Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>
<Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
<Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
<Setter Property="ItemContainerTransitions">
<Setter.Value>
<TransitionCollection>
<AddDeleteThemeTransition/>
<ReorderThemeTransition/>
</TransitionCollection>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<ItemsStackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListView">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="ComboBoxButton"
Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ListPickerShowButtonVisibility}"
Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ShowListPickerCommand}"
VerticalAlignment="Top" Padding="0">
<TextBox
BorderThickness="0"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
Foreground="{ThemeResource ApplicationForegroundThemeBrush}"
PlaceholderText=" choose an item "
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem, Mode=TwoWay}"
Padding="0"
Margin="0"
HorizontalAlignment="Stretch"></TextBox>
</Button>
<Grid Grid.Row="1" Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ListPickerVisibility}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBox
Grid.Row="0"
PlaceholderText="search box"
x:Name="FilterTextBox"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=FilterText,
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<ScrollViewer
Grid.Row="1"
x:Name="ScrollViewer" AutomationProperties.AccessibilityView="Raw" BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsHorizontalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsHorizontalScrollChainingEnabled}" IsVerticalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsVerticalScrollChainingEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" TabNavigation="{TemplateBinding TabNavigation}" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">
<ItemsPresenter FooterTransitions="{TemplateBinding FooterTransitions}" FooterTemplate="{TemplateBinding FooterTemplate}" Footer="{TemplateBinding Footer}" HeaderTemplate="{TemplateBinding HeaderTemplate}" Header="{TemplateBinding Header}" HeaderTransitions="{TemplateBinding HeaderTransitions}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</ScrollViewer>
</Grid>
</Grid>

</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</local:ListPicker.Resources>


</local:ListPicker>

The code behind powering this searchable combo box is as follows:


public sealed partial class ComboPicker
{
public ComboPicker()
{
this.InitializeComponent();
ListPickerVisibility = Visibility.Collapsed;
ShowListPickerCommand = new RelayCommand((() =>
{
ListPickerVisibility = Visibility.Visible;
ListPickerShowButtonVisibility = Visibility.Collapsed;
}));
SelectionChanged += OnSelectionChanged;
}

public static readonly DependencyProperty ListPickerShowButtonVisibilityProperty = DependencyProperty.Register(
"ListPickerShowButtonVisibility",
typeof(Visibility),
typeof(ComboPicker),
new PropertyMetadata(Windows.UI.Xaml.Visibility.Visible, (o, args) =>
{
((ComboPicker)o).OnListPickerShowButtonVisibilityChanged((Visibility)args.NewValue);
}));

private void OnListPickerShowButtonVisibilityChanged(Visibility newValue)
{
}

public Visibility ListPickerShowButtonVisibility
{
get { return (Visibility)GetValue(ListPickerShowButtonVisibilityProperty); }
set { SetValue(ListPickerShowButtonVisibilityProperty, value); }
}

public static readonly DependencyProperty ListPickerVisibilityProperty = DependencyProperty.Register(
"ListPickerVisibility",
typeof(Visibility),
typeof(ComboPicker),
new PropertyMetadata(Windows.UI.Xaml.Visibility.Collapsed, (o, args) =>
{
((ComboPicker)o).OnListPickerVisibilityChanged((Visibility)args.NewValue);
}));

public Visibility ListPickerVisibility
{
get { return (Visibility)GetValue(ListPickerVisibilityProperty); }
set { SetValue(ListPickerVisibilityProperty, value); }
}

public static readonly DependencyProperty ShowListPickerCommandProperty = DependencyProperty.Register(
"ShowListPickerCommand",
typeof(ICommand),
typeof(ComboPicker),
new PropertyMetadata(null, null));

public ICommand ShowListPickerCommand
{
get { return (ICommand)GetValue(ShowListPickerCommandProperty); }
set { SetValue(ShowListPickerCommandProperty, value); }
}
private void OnListPickerVisibilityChanged(Visibility visibility)
{

}

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListPickerVisibility = Visibility.Collapsed;
ListPickerShowButtonVisibility = Visibility.Visible;
}
}

All I am doing is using a button and displaying the ListPicker when a user clicks on it to select an item.  When the user has selected an item, the button’s content, which is a textbox is updated accordingly.

Searchable ListView for Windows Universal Apps

Needed a quick implementation of a searchable ListView for Windows Universal apps, specifically Windows Phone 8.1 and came up with the following:


public class ListPicker : ListView
 {
 private IList _items = null;
 private PropertyInfo _filteringProperty = null;
 readonly BasicObservableCollection<object> _filteredList = new BasicObservableCollection<object>();
 
 public static readonly DependencyProperty FilterTextProperty = DependencyProperty.Register(
 "FilterText",
 typeof(String),
 typeof(ListPicker),
 new PropertyMetadata(null, (o, args) =>
 {
 ((ListPicker)o).OnFilterTextChanged((string)args.NewValue);
 }));

private void OnFilterTextChanged(string filter)
 {
 if (_items == null)
 {
 _items = (IList)ItemsSource;

if (_items != null && !string.IsNullOrWhiteSpace(DisplayMemberPath))
 {
 _filteringProperty = _items[0].GetType().GetProperties().First(p => p.Name == DisplayMemberPath);
 }

ItemsSource = _filteredList;
 }

_filteredList.Clear();


 if (string.IsNullOrEmpty(filter))
 {
 _filteredList.ReplaceAll(_items.Cast<object>());
 return;
 }

var filteredItems = _items.Cast<object>().Where(i =>
 {
 var value = i.ToString();
 if (_filteringProperty != null)
 {
 value = _filteringProperty.GetValue(i) as string;
 }

return value != null && value.Contains(filter);
 });

_filteredList.ReplaceAll(filteredItems);
 }
 }

With the following complimenting style:


 <Style TargetType="controls:ListPicker">
 <Setter Property="IsTabStop" Value="False"/>
 <Setter Property="TabNavigation" Value="Once"/>
 <Setter Property="IsSwipeEnabled" Value="True"/>
 <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
 <Setter Property="VerticalContentAlignment" Value="Top"/>
 <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
 <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
 <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
 <Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto"/>
 <Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>
 <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
 <Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
 <Setter Property="ItemContainerTransitions">
 <Setter.Value>
 <TransitionCollection>
 <AddDeleteThemeTransition/>
 <ReorderThemeTransition/>
 </TransitionCollection>
 </Setter.Value>
 </Setter>
 <Setter Property="ItemsPanel">
 <Setter.Value>
 <ItemsPanelTemplate>
 <ItemsStackPanel Orientation="Vertical"/>
 </ItemsPanelTemplate>
 </Setter.Value>
 </Setter>
 <Setter Property="Template">
 <Setter.Value>
 <ControlTemplate TargetType="ListView">
 <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
 <Grid>
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto"/>
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>
 <TextBox
 Margin="0,0,19,0"
 PlaceholderText="search"
 x:Name="FilterTextBox"
 Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=FilterText, 
 UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
 <ScrollViewer
 Grid.Row="1"
 x:Name="ScrollViewer" AutomationProperties.AccessibilityView="Raw" BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsHorizontalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsHorizontalScrollChainingEnabled}" IsVerticalScrollChainingEnabled="{TemplateBinding ScrollViewer.IsVerticalScrollChainingEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" TabNavigation="{TemplateBinding TabNavigation}" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">
 <ItemsPresenter FooterTransitions="{TemplateBinding FooterTransitions}" FooterTemplate="{TemplateBinding FooterTemplate}" Footer="{TemplateBinding Footer}" HeaderTemplate="{TemplateBinding HeaderTemplate}" Header="{TemplateBinding Header}" HeaderTransitions="{TemplateBinding HeaderTransitions}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
 </ScrollViewer>
 </Grid>
 </Border>
 </ControlTemplate>
 </Setter.Value>
 </Setter>
 </Style>

Only caveat is  this style needs to be added to the resources collection of your main application.  Also, BasicObservableCollection is simply an enhanced version of ObservableCollection that allows for items to be added to the collection in bulk before raising the collection changed event on the UI t thread, courtesy of Cory Charlton.

If anyone knows how I can embed the style into code, so it is all self contained, please advise.

Happy Coding.