-----------
Java
@Override
public synchronized Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/logbookentries/nextid", LogBookIDRessource.class);
router.attach("/employees/{id}", EmployeeRessource.class ); //http://localhost:8111/
router.attach("/employees", EmployeesRessource.class );
router.attach("/employees/", EmployeesRessource.class );
router.attach("/employees/{id}/logbookentries", EmployeeLogBookEntries.class );
router.attach("/logbookentries/", LogBookEntriesRessource.class);
router.attach("/logbookentries", LogBookEntriesRessource.class);
router.attach("/logbookentries/{id}", LogBookEntryRessource.class);
router.attachDefault(BaseServiceRessource.class);
return router;
}
try {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8111);
component.getDefaultHost().attach("/api", new RestletApplication());
component.start();
//new Server(Protocol.HTTP, 21524, new RestletApplication()).start();
} catch (Exception e) {
e.printStackTrace();
}
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="test">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:int" name="id"></xs:element>
<xs:element type="xs:string" name="name"></xs:element>
<xs:element type="xs:long" name="testlong"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="testMore">
<xs:complexType>
<xs:sequence>
<xs:element type="xs:int" name="id"></xs:element>
<xs:element ref="test" maxOccurs="unbounded"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
throw new ResourceException(418, "Could not find Employee! (Wrong ID)");
doError(Status.CLIENT_ERROR_BAD_REQUEST, "ID must be an Integer!");
ClientResource resource;
resource = new ClientResource("http://localhost:8111/api/");
baseService = resource.wrap(IBaseService.class);
@WebServlet(urlPatterns = "/employees")
public class EmployeesServlet extends HttpServlet {
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPostAndGet(req, resp);
}
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPostAndGet(req, resp);
}
@SneakyThrows
protected void doPostAndGet(HttpServletRequest req, HttpServletResponse resp) throws JAXBException {
User user = (User) req.getSession().getAttribute("user");
if(user == null || user.getUserID() == null) {
req.getSession().setAttribute("errorMessage", "No user selected!");
resp.sendRedirect("index.jsp");
return;
}
String id;
if((id = req.getParameter("deleteID")) != null) {
try {
int userID = Integer.valueOf(id);
TimeTrackingRestClient.getInstance().getEmployeeService(userID).deleteRestCall();
} catch (Exception e) {
req.setAttribute("error", "Could not delete User. Invalid ID!");
}
}
if(req.getParameter("add") != null) {
TimeTrackingRestClient.getInstance().getEmployeesService().addElement(new Employee());
}
if((id = req.getParameter("saveID")) != null) {
try {
int userID = Integer.valueOf(id);
String userIDField = req.getParameter("idField");
String firstname = req.getParameter("firstnameField");
String lastName = req.getParameter("lastnameField");
String date = req.getParameter("birthday");
Employee employee = new Employee();
employee.setEmployeeID(new BigInteger(id));
employee.setFirstName(firstname);
employee.setLastName(lastName);
if(!date.trim().isEmpty() && date.split("-").length == 3) {
employee.setDateOfBirth(HtmlDateConverter.convertFromHtmlValue(date));
}
TimeTrackingRestClient.getInstance().getEmployeeService(userID).putRestCall(employee);
} catch (Exception e) {
req.setAttribute("error", "Could not save User.");
}
}
req.setAttribute("employees", TimeTrackingRestClient.getInstance().getEmployeesService().getEmployees());
req.getRequestDispatcher("employees.jsp").forward(req,resp );
}
@Override
public void init() throws ServletException {
super.init();
}
}
<jsp:useBean id="testmore" class="package.TestMore" scope="request"></jsp:useBean>
<% if (BOOL) { %>
...
<% }%>
<%=e.getEmployeeID()%>
${employee.employeeID}
-----------
Java End
-----------
Load Images
private const string DIR_NAME = "/imgs/";
List<MyImage> images;
//Init the List
public Service1()
{
string dirPath = AppDomain.CurrentDomain.BaseDirectory + DIR_NAME;
this.images = SearchFolderRec(dirPath);
}
public List<MyImage> SearchFolderRec(string path)
{
if (!Directory.Exists(path))
{
return new List<MyImage>();
}
List<MyImage> results = new List<MyImage>();
//Get all files in dir
string[] files = Directory.GetFiles(path);
foreach(string file in files)
{
//Just check if it is a valid image
try {
Image img = Image.FromFile(file);
results.Add(new MyImage(file, Path.GetFileNameWithoutExtension(file)));
} catch (Exception e) {
}
}
//Open all dirs (Can be comment out if you don't want it)
string[] dirs = Directory.GetDirectories(path);
foreach(string nextDir in dirs)
{
results.AddRange(SearchFolderRec(nextDir));
}
return results;
}
public byte[] getImage(string name)
{
MyImage rightImage = images.Find((image) => { return image.Name == name; });
if (rightImage == null)
return new byte[0];
//Load image
string path = AppDomain.CurrentDomain.BaseDirectory;
Bitmap image1 = (Bitmap)Image.FromFile(rightImage.ImagePath, true);
MemoryStream ms = new MemoryStream();
image1.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imgData = ms.ToArray();
//Return image
return imgData;
}
public List<MyImage> getImageList()
{
return images;
}
-----------
Load CSV
public string getCSV()
{
string[] lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "test.csv");
string rest = "";
foreach(string line in lines)
{
foreach(string parts in line.Split(';'))
{
rest += parts+ "\t";
}
rest += "\n";
}
return rest;
}
-----------
Example Linq Csv
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
}
public enum Gender
{
Male,
Female
}
Then create a Service that can load Data from the File:
public static class PersonService
{
public static List<Person> ReadFile(string filepath)
{
var lines = File.ReadAllLines(filepath);
var data = from l in lines.Skip(1)
let split = l.Split(';')
select new Person
{
Id = int.Parse(split[0]),
Name = split[1],
Age = int.Parse(split[2]),
Gender = (Gender)Enum.Parse(typeof(Gender), split[3])
};
return data.ToList();
}
}
And then use that to populate the UI:
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
DataContext = PersonService.ReadFile(@"c:\file.csv");
}
}
XAML:
<Window x:Class="WpfApplication14.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="300" Width="300">
<DataGrid AutoGenerateColumns="True"
ItemsSource="{Binding}"/>
</Window>
-----------
DataBiding Examples
<Window x:Class="TwoWayBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid Height="54" Width="165">
<TextBox Name="textBox" Margin="0,-77,0,0" Height="23" VerticalAlignment="Top"
Text ="{Binding ElementName=listBox,
Path=SelectedItem.Content,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
Background="{Binding ElementName=listBox, Path=SelectedItem.Content, Mode=OneWay}">
</TextBox>
<ListBox Name="listBox" >
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Yellow" IsSelected="True"/>
<ListBoxItem Content="Orange" />
</ListBox>
</Grid>
</Window>
-----------
Databinding easy
<TextBox Name="txtValue" />
<WrapPanel Margin="0,10">
<TextBlock Text="Value: " FontWeight="Bold" />
<TextBlock Text="{Binding Path=Text, ElementName=txtValue}" />
</WrapPanel>
-----------
XmlSerializer
https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer.deserialize?view=net-5.0
-----------
XML-Docs
<Window x:Class="DefaultApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Path=Elements[Person]}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Path=Element[Surname].Value}"/>
<DataGridTextColumn Header="Phone no" Binding="{Binding Path=Element[PhoneNo].Value}"/>
<DataGridTextColumn Header="Country" Binding="{Binding Path=Element[Country].Value}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
using System.Windows;
namespace DefaultApp
{
using System.Xml.Linq;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void RefreshButtonClick(object sender, RoutedEventArgs e)
{
var peopleList =
XElement.Load(/*@"path to your xml file"*/);
this.dataGrid.DataContext = peopleList;
}
}
}
-----------Obersavable Collection
public class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
{
CollectionChanged += FullObservableCollectionCollectionChanged;
}
public TrulyObservableCollection(IEnumerable<T> pItems) : this()
{
foreach (var item in pItems)
{
this.Add(item);
}
}
private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
OnCollectionChanged(args);
}
}
public class Person : INotifyPropertyChanged
{
private string name;
private string surname;
private string phoneNo;
private string country;
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("Name")]
public string Name
{
get
{
return this.name;
}
set
{
if (value != this.name)
{
this.name = value;
OnPropertyChanged();
}
}
}
[XmlElement("Surname")]
public string Surname
{
get
{
return this.surname;
}
set
{
if (value != this.surname)
{
this.surname = value;
OnPropertyChanged();
}
}
}
[XmlElement("PhoneNo")]
public string PhoneNo
{
get
{
return this.phoneNo;
}
set
{
if (value != this.phoneNo)
{
this.phoneNo = value;
OnPropertyChanged();
}
}
}
[XmlElement("Country")]
public string Country
{
get
{
return this.country;
}
set
{
if (value != this.country)
{
this.country = value;
OnPropertyChanged();
}
}
}
// Create the OnPropertyChanged method to raise the event
// The calling member's name will be used as the parameter.
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public Person(string name, string surname, string phoneNo, string country)
{
Name = name;
Surname = surname;
PhoneNo = phoneNo;
Country = country;
}
public Person()
{
}
}
<DataGrid
AutoGenerateColumns="False"
Height="254"
HorizontalAlignment="Left"
Margin="12,12,0,0"
Name="personGrid"
VerticalAlignment="Top"
Width="479"
SelectionMode="Single"
CanUserAddRows="True"
CanUserDeleteRows="True"
ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Path=Surname}"/>
<DataGridTextColumn Header="Phone no" Binding="{Binding Path=PhoneNo}"/>
<DataGridTextColumn Header="Country" Binding="{Binding Path=Country}"/>
</DataGrid.Columns>
</DataGrid>
public TrulyObservableCollection<Person> People { get; set; }
public ObservableCollection<string> PeopleNameSelector { get; set; }
People = new TrulyObservableCollection<Person>();
personGrid.DataContext = People;