Search This Blog
Sunday, December 23, 2012
Java Vaadin controls - ControlHelper getParent()
/**
* The purpose of this class is to help with the management of Vaadin controls child-parent tree.
*/
public class ControlHelper {
private static final int _MAXIMUM_PARENT_ITERATION_COUNT = 100;
/**
* Get parent of the control which has a specified type.
*
* @param cls type of the control to return
* @param control origin control (where to start traversing the tree)
* @param <T>
* @return
*/
public static <T extends AbstractComponent> T getParent(Class<T> cls, AbstractComponent control)
{
if (control == null)
return null;
AbstractComponent parent = control;
for (int i = 0; i < _MAXIMUM_PARENT_ITERATION_COUNT; i++)
{
if (parent.getParent() == null)
return null;
//Return parent of the desired class type
if (parent.getParent().getClass().isAssignableFrom(cls))
return (T) parent.getParent();
parent = (AbstractComponent) parent.getParent();
}
return null;
}
}
Friday, November 23, 2012
Volvo C30 1.6D 2009 Momentum - Remove overhead console
Removing the overhead console from the headliner
To remove the overhead console from the headliner just pull the console FIRMLY downward. The Volvo manual DOES not specify how to do this (only says that a trained Volvo technician can do it) and VIDA only says to pull the console downward. I'll attach some pictures to show you how it's done - I didn't want to break my new ride so I hesitated whether to change the courtesy lightning on my own.
If the console has never been removed you NEED to apply some force to remove it. Don't worry about breaking the console - this should not happen.
The transparent plastic cover can be removed by teasing it out with a screwdriver.
After the console has been removed you should see the plastic framework in the roof with ONLY one connector and a few latches. I have marked the connector and one of the latches in the picture.
Soldering out old bulbs and soldering the new LED lightning in
To remove holder from the console just twist it out. You'll not be able to remove the bulb from the holder easily, however. You need to somehow break the bulb's wires to pull it out.
The rest of the soldering process includes pulling out LED bulbs from their holders and putting them into the old VOLVO's holders, soldering the LED's wires to the old Volvo's metal connectors and putting the holders again into the console.
I leave the decision as whether to buy the holders from ebay or customize them yourself to you.
Tuesday, November 20, 2012
Import postgresql dump file on windows
c:\Program Files\PostgreSQL\9.1\bin\psql --username=your_username --file=your_dump_file.txt --dbname=your_database
Wednesday, October 3, 2012
C#/.NET Get NHibernate session information/database type/capabilities
var dialect = (Dialect)HibernateTemplate.Execute(del => del.GetSessionImplementation().Factory.Dialect;
Commenting capability (which is impossible in SQLite) can be read from:
dialect.SupportsCommentOn
Monday, September 17, 2012
NUnit AutoFixture unable to create an instance from IList
I encountered a problem with creating fake fixture objects in .NET tests for classes which contant a property with IList<T> (instead plain List<T>).
Suppose you have:
public class A
{
public IList<B> {
get { return list; }
set { list = value; }
}
private IList<B> list;
}
and you want to create a fake object like this:
var fake = new Fixture().Build<A>();
You'll get an error:
"AutoFixture was unable to create an instance from System.Collections.Generic.IList`1[A], most likely because it has no public constructor, is an abstract or non-public type."
What you need to do is tell AutoFixture what to use when it encounters an IList inferface:
(when there is an IList create a new List of some type):
var fixture = new Fixture();
fixture.Register<IList<A>>(fixture.CreateAnonymous<List<A>>);
fixture.Build<A>();
Thursday, September 13, 2012
log4net nhibernate stop logging to console
That's the configuration I used to stop nhibenrate from logging to console and force it to log to a separate file:
download
The important part is to use a filter inside a ConsoleAppender:
<filter type="log4net.Filter.LoggerMatchFilter">
<LoggerToMatch value="NHibernate"/>
<acceptOnMatch value="false"/>
</filter>
Tuesday, September 11, 2012
log4net quickstart; log4net FileAppender not working in ConsoleApplication
Add a section for log4net:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" requirePermission="false"/>
</configSections>
then add the section itself:
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss,fff} - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\a\xx.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="500MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
</log4net>
In your code do the following:
XmlConfigurator.Configure();
ILog logger = LogManager.GetLogger(typeof(Program));
logger.Info("a");
WARNING:
Do not use: BasicConfigurator.Configure(); as it does not work with this example.
Normally you'd declare a private variable for logging:
private static readonly ILog logger = LogManager.GetLogger(typeof (Program));
Sunday, July 15, 2012
Midnight Commander how to compress a file/directory; Make a tar archive with midnight commander
Tuesday, July 10, 2012
Silverlight set cell focus in DataGrid; Silverlight DataGrid set cell focus
<sdk:DataGrid>
<i:InteractionBehaviors>
<Behaviors:BrowserSelectedDataGridRowSelectsCellInSpecificRow ColumnNumber="1"/>
</i:Interaction.Behaviors>
<sdk:DataGrid>
where ColumnNumber specifies the column number to focus.
void DataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (AssociatedObject.SelectedItem == null)
return;
AssociatedObject.UpdateLayout();
//AssociatedObject.ScrollIntoView(item, (DataGridColumn)Target.Columns[ColumnIndexForEdit]);
AssociatedObject.Focus();
AssociatedObject.CurrentColumn = AssociatedObject.Columns[ColumnNumber];
AssociatedObject.BeginEdit();
}
source
Monday, July 9, 2012
Install Drupal 7.14 on Ubuntu 12.04
Download drupal archive from the site and copy it to the root of your www directory
(on Ubuntu that is: /var/www for apache2).
Unpack the drupal archive:
tar -zxvf drupal-7.14.tar.gz
Change the name to drupal (or any other):
mv drupal-7.14 drupal
Make sure ALL the files are owned by the www-data user (Apache2 user):
chown -R www-data:www-data ./drupal
Make sure you have the following packages installed:
php5-gd, libapache2-mod-php5, php5-pgsql (if you use postresql with drupal)
apt-get install php5-gd
(use apt-get, because aptitude uninstalls libapache2-mod-php5)
aptitude install libapache2-mod-php5
apt-get install php5-pgsql
Open the page (installation script from the browser):
www.yourdomain.com/drupal
That's about it.
Sunday, July 8, 2012
Configure Apache to host Tomcat 7 on Ubuntu
aptitude install tomcat7
Configure Tomcat
------------------
Edit /var/lib/tomcat7/conf/server.xml
Uncomment the line:
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
to tell Tomcat to use connector protocol on port 8009 for connection with Apache.
Restart tomcat:
/etc/init.d/tomcat7 restart
Check whether the connector is working with:
netstat -ln | grep :8009
Configure Apache
------------------
Install module for apache which will be used to connect to Tomcat:
apt-get install libapache2-mod-jk
Edit /etc/apache2/sites-available/default
and add JkMountCopy On in the <VirtualHost *:80> section
...
DocumentRoot /var/www
JkMountCopy On
...
Edit /etc/apache2/mods-enabled/jk.conf
<IfModule jk_module>
JkWorkersFile /etc/libapache2-mod-jk/workers.properties
JkLogFile /var/log/apache2/mod_jk.log
JkLogLevel info
JkShmFile /var/log/apache2/jk-runtime-status
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
JkMount /YouApplicationName/* ajp13_worker
JkMount /YouApplicationName ajp13_worker
</IfModule>
Note:
---------
the path should be accessible from Tomcat7 under the same application name as well. i.e:
localhost:8080/YourApplicationName
This is because Apache hosts your tomcat7's specific path.
Host jsp application from Eclipse on Tomcat 7 server
Let's suppose you have already installed tomcat7 on Ubuntu 12.04. Then you'll have tomcat root directory under:
/var/lib/tomcat7/webapps/
Create you own application directory:
/var/lib/tomcat7/webapps/YourApplication
We'll assuse this directory path to be $APP_ROOT. You need to have the following directory structure:
$APP_ROOT/META-INF/MANIFEST.MF
$APP_ROOT/WEB-INF/classes - this is where your *.class files need to be stored.
$APP_ROOT/WEB-INF/lib - this is where you *.jar need to be stored.
$APP_ROOT/WEB-INF/web.xml
(class files need to be stored in folders which correspond to their package names)
Create a Web application (Servlet context)
----------------------------------------------
edit the file /etc/tomcat7/server.xml
and create a line:
<Engine [...]>
<Host [...]>
<Valve [...] />
<Context path="/YourApplication" docBase="YourApplication" debug="0" reloadable="true" />
</Host>
</Engine>
and restart the tomcat server.
Your application should be server under:
127.0.0.1/YourApplication
Tip:
---------
You can redirect to your application from the root domain by editing the index.html under:
/var/lib/tomcat7/webapps/ROOT/index.html
<html>
<head>
<title>Your Page Title</title>
<meta http-equiv="REFRESH" content="0;url=http://yourdomain.com/YourApplication"></HEAD>
<BODY> Optional page text here.</BODY>
</HTML>
Edit your /var/www/index.html page as well.
Sunday, July 1, 2012
Postgresql 9.1 set default password on Ubuntu 12.04
Set default password for Postgresql 9.1 on Ubuntu 12.04:
Open a terminal
sudo -u postgres psql postgres
(run psql client as a linux user postgres and connect to postgres database)
ALTER USER postgres WITH PASSWORD '<newpassword>';
(change password for user postgres to <newpassword>)
Sunday, June 24, 2012
Git combine (merge) local commits into one
To combine (merge) local commits into one before pushing them:
1. Switch to your local branch where your commits reside (actually it does NOT have to be a different branch, you can combine git commits on your local master as well)
2. I suppose you have already made 3 commits which you want to combine (merge) into one.
3. Reset (soft) as many commits down as you want to combine in your branch. When you execute a soft reset on a branch you end up having the combined result of the commits in your index ready to commit.
4. Commit the changes from your index - you end up having a single commit which a combined (merged) result of the previous three.
Screenshots were done using "SmartGit" from syntevo.
Saturday, June 23, 2012
git://eagain.net/gitosis.git not found (setting up gitosis on ubuntu)
I found that eagain.net does not work for me. Alternatively you can clone gitosis from:
git clone https://github.com/tv42/gitosis.git
or download it from here.
Sunday, June 17, 2012
Ubuntu Server 12.04 xrdp failed to load session 'ubuntu'
This error is caused by xrdp trying to run the classic Ubuntu desktop when it is not installed. This can happen when you install Ubuntu server without graphical environment and then install gnome-classic desktop only.
There are 2 files you need to worry about:
/etc/xrdp/startwm.sh
which should have:
. /etc/X11/Xsession
at the end.
(there is a space between '.' and '/etc')
and ~/.xsession
(Don't worry if there isn't – it just means you haven't created it yet)
This file should have:
gnome-session --session=gnome-classic
restart xrdp with:
/etc/init.d/xrdp restart
Connect with
"sesman-Xvnc"
settings.
Thursday, May 17, 2012
Silverlight Force Binding update
//Force Binding update from TextBox
BindingExpression binding = pageSizeTextBox.GetBindingExpression(TextBox.TextProperty);
if (null != binding)
binding.UpdateSource();
Sunday, May 13, 2012
Can't uninstall an app in Android
I encoutered an app like this in Android 4.0 ICS called "Screen Timeout" that lets you set the screen timeout not only to the standard values. Unfortunately this app was buggy and crashed on ICS.
To uninstall an app like this just:
Go to: home screen->Menu->Settings->Security->Select Device Administrators
Find the application.
Then uncheck it from device administrators.
From now on the app can be force closed and uninstalled from the application list without any problems.
Friday, April 27, 2012
Visual Studio 2010 regexp replace decimal delimiter
I had to replace decimal delimiter using Visual Studio 2010’s regular expression built-in mechanism – i.e. “ctrl+h” or ‘find and replace’ option.
The idea was to replace tags in XML:
<value>17,1</value>
with:
<value>17.1</value>
I ended up using “tagged expressions” or “back references” in regexp which IS supported by VS built-in regex. To enter a back reference you simply use \1 (for the first back reference) and tag references by surrounding them with {} braces.
Find what:
\<value\>{-*}{[0-9]+},{[0-9]+}\</value\>
Replace with:
\<value\>\1\2.\3\</value\>
Possible minus sign is the first back reference, digits before coma are the second reference and digits after coma are the third reference.
Thursday, April 19, 2012
Android 4.0 mount sdcard as drive
With Android 4.0 the option to mount you phone memory and external SD card as drives in Windows just disappeared.
Fortunately on a rooted Android ICS phone you can still do that by installing this application:
Saturday, April 7, 2012
Android ICS 4.0.3 Official XXLPQ for Samsung Galaxy S2 (For Odin)
(Odin is included in the package).
Model: Samsung Galaxy S2 I9100
Android: ICS 4.0.3 XXLPQ kernel 3.0.15
TouchWiz
Files [ROM]:
Part1
Part2
Part3
Part4
1. Unpack
2. Run "Odin3 v1.83.exe"
3. Enter "Download mode" on your phone - downArrow, Home Key, and power button pressed simultaneously; Press upArrow to "continue"
4. [NOW - after running Odin] - connect the mobile via USB to the PC
5. Click PDA - select "I9100XXLPQ_I9100OXALPQ_I9100XXLPQ_HOME.tar.md5" file
6. DO NOT CHANGE ANY other settings
7. Click start
Your Odin should look like this:
Android 4.0.3 XXLPQ Screen timeout bug
I had an issue with my Android ICS 4.0.3 XXLPQ ROM.
The problem was that the screen did NOT turn itself off after a defined period of time so when
I received an sms or a call the screen remained lit till the time I actually came and turn it off manually.
It was annoying and drained the battery.
I turned out that it was a kernel problem. Updating the kernel to speedmod-kernel-s2 worked like a charm
and resolved my issue. It's supposed to be faster than the stock kernel but what I really cared about was
screen backlight timeout bug.
Kernel:
Working/Confirmed root for Samsung Galaxy S2 stock ROM on Android 4.0.3 version XXLPQ
Model: Samsung Galaxy S2 I9100
ROM: Android 4.0.3 stock ROM XXLPQ
1. download the file below
2. unpack it and copy the content to your SD card
3. enter CWM - upArrow, Home Key, and power button pressed simultaneously
4. search for "Install zip from sdcard"
5. choose "CWM.zip"
6. touch clockworkmod recovery will run
7. search for "Install zip from sdcard"
8. search for SU-Busybox-Installer.zip and apply the update
File:
OfficialICS_ROOT.7z
Guide for UNROOTING is available inside the package (in short: apply the SU-Uninstaller-Signed.zip update)
Tested on stock 4.0.3 LPH & LPQ rom.
Visual/Touch interface Clockworkmod recovery for Galaxy S2
Tuesday, March 13, 2012
Postgres using replace function; Postgres replacing phrase in an XML-typed column;
I wanted to replace column content '{ApplicationVersion}' with '{RegularMessage}' string. Postgres syntax seemed a little bit strange to me (because of the XMLPARSE) so I’m writing the solution here. As it turned I had to cast my content argument to text first as it was an XML-typed column - there is no automatic casting. If you forget to that the error pops up which suggests there is no replace function referenced but it actually means that there is no replace function with such arguments so you should cast your arguments:
ERROR: function replace(xml, unknown, unknown) does not exist
update messageset content = XMLPARSE(
DOCUMENT replace(text(content),'{ApplicationVersion}','{RegularMessage}')
)
where type = 'RegularMessage';
where content is the xml-typed column.
XMLPARSE can have DOCUMENT or CONTENT as arguments and you need to write one of the two keywords before the actual column name:
XMLPARSE (DOCUMENT '<?xml version="1.0"?><book><title>Manual</title></book>');
or
XMLPARSE (CONTENT 'abc<foo>bar</foo><bar>foo</bar>');
Thursday, March 1, 2012
GIT good practices; What to remember when coming from SVN; SVN to GIT tutorial
When working with a distributed repository system one needs to remember that it is slightly different from SVN and CVS repositories. I will put most aspects in points for easy remembering.
- Your LOCAL commit time/order is remembered when pushing your changes. So if you commit changes on master and then try pulling and pushing it will create a nasty “divide and merge” track on master. It looks like this:
To prevent this behavior always do REBASE instead of pull when syncing with the distributed repository.
Rebase in TortoiseGit is available from rightClick->Git sync->Fetch&Rebase
- If possible work on your LOCAL branch. For example, when your main branch is called “master”, create a branch called “localMaster” and commit changes to this branch. When the time comes to push your changes you will switch to “master”, pull the changes. Then switch back to “localMaster”, rebase localMaster in position to master to include all the changes which have been made on master and resolve any conflicts. Then switch to “master”, merge master from “localMaster” to include changes from “localMaster” in “master”. In the end you just push your “master” branch.
GIT good practices – using “master” and “localMaster” branches.
- You clone the repository from source. And create your “localMaster” branch. So you have: “origin/master”, “origin/HEAD”, “master” and “localMaster”.
- commit changes to “localMaster” branch
- Switch back to “master” branch and pull changes from repo
- switch to “localMaster” and do a rebase with “master”. In this way all the changes which have been pulled to master will be reflected in “localMaster” branch
- this is how it looks “as a pure concept” after the rebase. You need to resolve any conflicts that can occur during this process.
- switch to “master” branch and merge changes from “localMaster” to reflect commits made in “localMaster” to “master” branch
- now that you have merged “master” and “localMaster” you can switch to “master” and push your changes so that others can see your commits.
I hope this is helpful.
Wednesday, February 29, 2012
Silverlight animating PopupMenu–‘IsOpen’ property, translate transform and opacity
This sample shows how to animate System.Windows.Controls.Primitives.Popup ‘IsOpen’ property, its position and opacity.
To change the visual state from code behind use:
VisualStateManager.GoToState(this, "HiddenState", true);
VisualStateManager.GoToState(this, "VisibleState", true);
Thursday, February 9, 2012
Using StringFormat in Binding
I had a problem using string format for a simple task of just "following the string from Binding with a ‘:’ sign. This can accomplished with:
Content="{Binding a,Source={StaticResource b}, StringFormat='{}{0}:'}"
Don’t forget the ‘’ signs.
Silverlight set Binding to property from code-behind or ViewModel
There is a static class BindingOperations which has a method called SetBinding().
BindingOperations.SetBinding(targetObject, TargetObjectClass.AttachableProperty, new Binding());
Where:
targetObject – is the instance of the object we bind to
TargetObjectClass.AttachableProperty – is the static reference to the propety we want to bind from
new Binding() – is the Binding with the Path and Source properties appropriately set.
Sample usage is:
BindingOperations.SetBinding(observableResources,ObservableResources.CurrentCultureProperty, new Binding() { Path = new PropertyPath("CurrentCulture"), Source = LanguageManager, Mode = BindingMode.TwoWay});
You can also use:
targetObject.SetBinding(TargetObjectClass.AttachableProperty, new Binding());
Friday, February 3, 2012
Silverlight sdk:DataGrid Column Header DataBinding; How to set DataBinding in Column Header in Silverlight
There is a problem with setting DataBinding as a Header in Column (e.g. DataGridTextColumn) from Silverlight Client SDK. Unfortunately Header is not a dependency property, do binding to it will result in converting DataBinding to string (calling its ToString() method).
“System.Windows.Data.Binding”
To overcome the problem create a helper with a Dependency property (e.g. HeaderBinding). Change to HeaderBinding binding should set the real Header string.
Usage:
<sdk:DataGridTextColumn Controls:DataGridColumnHelper.HeaderBinding="{Binding Something” />
Helper:
public static class DataGridColumnHelper
{
public static readonly DependencyProperty HeaderBindingProperty = DependencyProperty.RegisterAttached(
"HeaderBinding",
typeof(object),
typeof(DataGridColumnHelper),
new PropertyMetadata(null, DataGridColumnHelper.HeaderBinding_PropertyChanged));
public static object GetHeaderBinding(DependencyObject source)
{
return (object)source.GetValue(DataGridColumnHelper.HeaderBindingProperty);
}
public static void SetHeaderBinding(DependencyObject target, object value)
{
target.SetValue(DataGridColumnHelper.HeaderBindingProperty, value);
}
private static void HeaderBinding_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridColumn column = d as DataGridColumn;
if (column == null) { return; }
column.Header = e.NewValue;
}
}
Monday, January 23, 2012
.NET C# Jasper Server SOAP Web Services using Microsoft.Web.Services2.dll
I had some problems connecting to Jasper server using SOAP web services and the standard library System.Web.Services.dll.
The solution uses basic connectivity, the runReport() method and Microsoft.Web.Services2.dll from “Web Services Enhancements 2.0 for Microsoft .NET Framework”. You can download the library here.
You need path to reference it Visual Studio:
C:\Program Files (x86)\Microsoft WSE\v2.0\Microsoft.Web.Services2.dll
Whole needed source is available here.
var jasperService = new JasperService("http://localhost:8088/jasperserver/services/repository");
var credentials = new NetworkCredential("perspectiv", "perspectiv");
jasperService.Credentials = credentials;
string requestXML = "[.....]";
jasperService.runReport(requestXML);
var attachments = jasperService.ResponseSoapContext.Attachments;
if (attachments.Count > 0)
{
var atach = attachments[0];
var atachStream = atach.Stream;
using (var fileStream = File.Create("C:\\test\\test.pdf"))
{
atachStream.CopyTo(fileStream);
}
}
Microsoft.Web.Services2 401 Unauthorized
If you encountered this error using Web.Services2 from Microsoft just try:
var service = new JasperService("http://localhost:8088/jasperserver/services/repository");
var cred = new NetworkCredential("someUser", "somePass");
service.Credentials = cred;
If this does not work for you try:
SoapContext requestContext = service.RequestSoapContext;
UsernameToken userToken =
new UsernameToken("someUser", "somePass",
PasswordOption.SendPlainText);
requestContext.Security.Tokens.Add(userToken);
requestContext.Security.Timestamp.TtlInSeconds = 86400;
Wednesday, January 11, 2012
Android delete national characters from SMS by default; Android send sms without polish characters
If you want to send sms without national characters (in other words delete polish or other weird characters from your sms) and save some money on sms bills try this on Android:
If you have Samsung Galaxy S2 (maybe some other Samsung devices as well):
- go to: SMS messages –> Settings –> Input mode –> GSM alphabet
(choose the option GSM alphabet instead of Unicode one and your smses will be sent without national characters)
If you have other devices:
- install “GO SMS Pro” from Market.
Gosms - setting – advanced settings – settings for sending - switch on national setting
This application has the option called:
“Localization support for accented chars: by enabling Czech, Polish and French SMS mode “ which will delete your national characters from smses in Android.
Tuesday, January 10, 2012
C# Using reflection to create an instance of a specific type; convert string to a specific type;
To create an instance of a compiled custom class in the assembly:
Assembly.GetExecutingAssembly().CreateInstance(YourCustomClassName);
To create an instance of a built-in type e.g. “System.Int32” :
Activator.CreateInstance(Type.GetType("System.Int32"));