adrian’s blog

September 17, 2009

XPath2 in .Net

Filed under: Software — Tags: , , , — Adrian @ 2:02 pm

“What? No XPath2 in .Net? Only v1?”
This is how it starts. At first you can call Microsoft however you want for not implementing XPath2, not even in .Net framework 4. But then you should come together and do it yourself. Actually doing a small workaround, that will enable you to use XPath2 functions in .Net.
First of all see the difference between the XPath functions implemented by Microsoft and the XPath2 standard functions.
Most likely for XSLT transformation in .Net you will use XslCompiledTransform. The workaround is based on adding an extension object.

// creating the XSLT transformation object
XslCompiledTransform xslTransform = new XslCompiledTransform();
// loading the stylesheet - see the Load method for all the possible arguments
xslTransform.Load(...);
// create the transformation arguments object
XsltArgumentList xslArg = new XsltArgumentList();
// the extension object needed for the workaround
xslArg.AddExtensionObject("urn:xpath2", new XPath2());
// apply the transformation
xslTransform.Transform(inputXmlDocument, xslArg, output);

And now we have to define the XPath class

using System.Text.RegularExpressions;
public class XPath2
{
	public int compare(String comparand1, String comparand2)
	{
		return comparand1.CompareTo(comparand2);
	}

	public String replace(String input, String pattern, String replacement)
	{
		return Regex.Replace(input, pattern, replacement);
	}
}

For the sake of example and simplicity I included in here only two example functions, compare and replace. But you can implement here all the XPath2 functions that you need, as methods (not static ones) of the class XPath2.

In the XSLT file it is mandatory to have

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xpath2="urn:xpath2">

as the first line. And then using any function will be simple and straightforward:

<xsl:value-of select="xpath2:compare('xpath1', 'xpath2')" />

Of course another way will be to simply use Saxon, an open source implementation for XSLT 2 for both Java and .Net. But if you just need an XPath2 function, it should be simpler what I described above.

September 6, 2009

Patu Digua – JavaScript/HTML/CSS Obfuscator/Compressor

Filed under: Software, Web — Tags: , , — Adrian @ 4:04 pm

I finally managed to get a first version done for a web obfuscator and compressor.
First of all, why to use such a program. Some may say to hide your HTML/JavaScript/CSS code. Right. This could be one option. And it is powerful enough to do so. But I would personally use it to reduce the size of the code. I tested on a few projects and the code gets reduced up to 60-70% from the initial size. It’s not like a zip but quite good if you take into account that you’re dealing only with scripts.
It is very good practice to comment and indent your code, but this doesn’t have any value at all for the end user, it only eats up his/her bandwidth.
The application has a very nice and intuitive interface (check out the screenshots), it is very customizable and it can be run on both UI and command line mode. A nice feature in the graphical interface is the drop zone, where you can drag and drop files or folders and they are automatically processed. Just switch first to the drop zone mode.
If you want to play with it you can download it from SourceForge or check out its home page.
I would gladly want to hear your opinion or how do you use it.

July 6, 2009

Swing tip: Move by dragging

Filed under: Software — Tags: , — Adrian @ 3:20 pm

A frame can be moved by dragging it from the title bar. But if you have a window without the title bar or you want to move it by dragging from wherever you want, this is the tip for you.
The MouseListener and MouseMotionListener will do the trick. They will be added to the JWindow that we want to move by dragging.

import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.*;

public class DragMove implements MouseListener, MouseMotionListener {

public static DragMove install(Component c) {
DragMove x = new DragMove();
c.addMouseListener(x);
c.addMouseMotionListener(x);
return x;
}

private Point start;

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
start = e.getPoint();
}

public void mouseReleased(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseDragged(MouseEvent e) {
Point p = e.getLocationOnScreen();
Component c = e.getComponent();
c.setLocation((int)(p.getX() - start.getX()), (int)(p.getY() - start.getY()));
c.repaint();
}

public void mouseMoved(MouseEvent e) {
}
}


Just a few explanations. When the mouse button is pressed, then the starting location relative to the window is stored. Then as the window is dragged, its location is moved on the screen relative to this starting point. And the window is repainted.
Pretty fast and simple enough.

June 12, 2009

Integrated load testing

Filed under: Software, Web — Adrian @ 6:05 pm

There is a big hype since few years ago about continuous integration. There are a lot of tools helping you in this, mostly oriented in building releases.
For testing it stands out JUnit, but this is unit testing. I’ll show you now how to have continuous integration for functional and performance (load) testing for web applications.
Basically I will use only Ant and JMeter. I will not enter into any details of how to write your JMeter test plan. For this you have at your disposal the JMeter documentation and a very nice graphical interface. The fact is that you will have in the end a functional and load testing plan.
And now the integration part. Ant is a very good choice when it comes to this and I think this should be your first one to look into if interested in integration.
What I want to have in the end is an automated test plan, that runs (on a remote machine), generates some results and email them to me.
Another nice thing about JMeter is that it comes packed with an Ant task too, that you will find in the extras directory under the root.
So now we have everything, except the Ant file. I will write it now.

<project name="Integrated load testing" default="test" basedir=".">
    <description>
        This is the build file for integrated load testing.
    </description>

    <!-- set global properties for this build -->
    <property name="jmeter.home" location="c:/Program Files/jakarta-jmeter-2.3.3"/>
    <property name="testplan" location="test.jmx"/>
    <property name="log" location="log.jtl"/>
    <property name="report" location="report.html"/>
    <property name="reportd" location="report-detail.html"/>

    <!-- project libraries, for the JMeter Ant task -->
    <path id="libs">
        <fileset dir="${jmeter.home}/extras">
            <include name="ant-jmeter*.jar"/>
        </fileset>
    </path>

    <taskdef name="jmeter" classname="org.programmerplanet.ant.taskdefs.jmeter.JMeterTask" classpathref="libs"/>

    <target name="test">
        <!-- Delete previous reports files, if any -->
        <delete failonerror="false" file="${log}"/>
        <delete failonerror="false" file="${report}"/>
        <delete failonerror="false" file="${reportd}"/>

        <!-- Run the tests -->
        <jmeter jmeterhome="${jmeter.home}"
                testplan="${testplan}" resultlog="${log}"
                failureproperty="failed"
                >
            <!--proxyhost="a.proxy.if.needed" proxyport="8080"-->
            <jvmarg value="-Xincgc"/>
        </jmeter>

        <!-- Generate the reports from the log file -->
        <xslt in="${log}" out="${report}" style="${jmeter.home}/extras/jmeter-results-report_21.xsl"/>
        <xslt in="${log}" out="${reportd}" style="${jmeter.home}/extras/jmeter-results-detail-report_21.xsl"/>

        <!-- Mail the reports -->
        <mail mailhost="my.smtp.host"
              from="integrated@testing.com" tolist="all.interested@testing.com" replyto="no-reply@testing.com"
              subject="Testing report"
              messagemimetype="text/html" messagefile="${report}" files="${reportd}"/>
    </target>

</project>

Just to round up this nicely you have to schedule a task to run this Ant build whenever you think this is needed. Don’t run this too often on your production environment. Once a month, usually when you have low traffic hours should be fine. If you want to run this more often do it on a testing environment.
One more thing. For the mail to work in Ant and not to get the error Failed to initialise MIME mail: javax/mail/MessagingException you have to download JavaMail and JAF. Then just copy mail.jar (from JavaMail distribution) and activation.jar (from JAF) to <ant-dir>/lib.

And you’re all set up: a fast way to integrate functional and load testing for your web application.

May 12, 2009

Success in Open Source

Filed under: Software — Tags: — Adrian @ 8:59 am

After my presentation about Motivation in Open Source, I had another one, this time even more focused on Open Source. I included, besides the motivational factors, the success criteria for an open source project, the driving factors to success and some adoption guidelines.
Also an interesting topic was the debate if to start a new open source project or join an existing one.
And if we talked about open source, what would have been more appropriate than an open presentation? (Open here is just another pretentious word for interactive). So, this is what we came up with.
Before reading below remember that in open source, everything relates to COMMUNITY SHARING KNOWLEDGE. And when we talk about community we have to divide it in two: users and developers. Here developers doesn’t mean exclusively software developers, but the ones that are giving the knowledge and users are the ones receiving it.

Success criteria

If for a commercial product, the only success criteria is the profit (or some other financial indicator related to it), in an open source project things are a little bit different.

  • Product functionality and quality. The obvious. The final product must do what’s intended to do and must do it well.
  • Community size (both of users and developers). When evaluating this you have to take into account the percentage of the target audience. If 5000 users represents a serious number for, let’s say, a Java or .Net framework, this will be disaster for a browser.
  • Community quality. This is more related to developers, than users. And that’s because quality people can create quality products.
  • Community energy or how active it is. If people are investing a lot of time and effort in developing and using something, most probably that something is worth.
  • Revenue. Intentionally I didn’t write profit here, because an open source community could not be profit oriented and could reinvest their entire revenue into the product itself, driving its development. But if people are giving money (in any way – paying for support, donations, buying promotionals) for something that was meant to be free, that it’s definitely worth it.

Driving factors to success

  • Goal. Your project must have a clearly defined and achievable goal. If it’s not well defined than you will not know what to do and if it’s not achievable you will just lose the enthusiasm and energy because you will never get where you want. It has to also be defined as long term and short term. The long term should be simple, usually compressed in one phrase (aka the mission) like: “Create a media player with 5% market share” or “Create an open-source alternative to SharePoint”.
  • Structure. Your community (and your project) must be well organized. Hierarchically and functionally. Doesn’t matter what kind of hierarchical structure you have (cathedral, bazaar, matrix, waterfall etc) but you have to stick to it. Also keep in mind what functional roles do you need to achieve your goal. If you want to “Create a media player with 5% market share” and you don’t have anyone with some degree of experience to handle the (online) marketing part, that’s a gap.
  • Focus. Always stick to your mission and don’t go sideways, whatever factors are driving you that way.
  • Marketing. A strategy in this matter is not optional. Either you want to create awareness, increase the adoption or expand the development community.
  • Business model. This is how you will generate revenue for your project, because generating revenue for your project will only help you driving it further. Choosing a business model can come later in the way, but having it from the beginning will only make things more clear.
  • Functionality – Quality – Accesibility. These are not trade-in’s in an open source project. Your product must do what should do, must do it well and must be easily reachable by your users.
  • Innovation. If you come up with something new on the market, your success is not 100% guaranteed, but your chances are totally boosted.
  • Future. If you earn the trust of your users in your project future, then you will also gain their fidelity.

You can read the presentation (in Romanian) or view some photos.

Again thanks goes to Razvan for offering me this opportunity.

May 11, 2009

MyUI – JavaScript library

Filed under: Software, Web — Tags: , — Adrian @ 10:15 am

I worked with JavaScript for more than 10 years. In different companies, in different projects, doing various things. Many times I ended copy-pasting the code from here to there.
Finally, a few months ago I decided to put all the common JS code that I have into one big library: MyUI.
Why MyUI?
UI because the library is mostly oriented on creating web user interface components and my because the scope is to make it easy to use and highly configurable. That’s why I paid attention to documentation and augmented it with lots of examples. There is also small demos for the most important features. I will also come back with tutorials on this blog.
So far the library is at the beginning and, if you use it, I will definitely value your feedback.

March 23, 2009

Calculating the angle between two points on a circle

Filed under: Software, Web — Tags: , , — Adrian @ 3:01 pm

I needed to calculate the angle between two points on the same circle. Don’t ask why, totally a new more complicated discussion.
So I had to remember a little trigonometry from the old days. Actually, this is done surprisingly easy, by simply using the atan2 method. Fortunately, this is available in JavaScript in the Math library.
In my problem, I had the center of the circle, one of the coordinates point(p1) and I had to find out the angle between the point (p0) at the 12-hour (imagine the circle as a clock) and the given one.

Angle between two points on a circle

Angle between two points on a circle


First of all the coordinates of the point at 12-hour is

p0(x,y) = (center.x, center.y - radius)

where radius is the circle radius and is calculated (according to Pythagorean theorem) as

radius = sqrt(|center.x - p1.x|2 * |center.y - p1.y|2)

Now let’s calculate the angle:

angle = atan2(p1.y - p0.y, p1.x - p0.x)

.
This will return the angle in radians. If you want to translate it into the interval [0,2 &#x3c0;] then simply multiply by two. If you want to transform it to degrees use angle * 180 / &#x3c0;.
Below you have a JavaScript function that receives as arguments the coordinates of the center and second point and returns the angle in degrees in the interval (0°, 360°) between the 12-hour point and the second point


function angle(center, p1) {
var center = this.lastPoint;
var p0 = {x: center.x, y: center.y - Math.sqrt(Math.abs(p1.x - center.x) * Math.abs(p1.x - center.x)
+ Math.abs(p1.y - center.y) * Math.abs(p1.y - center.y))};
return (2 * Math.atan2(p1.y - p0.y, p1.x - p0.x)) * 180 / Math.PI;
}

I also wrote a small demo.

Clonezilla – good user experience

Filed under: Software — Tags: — Adrian @ 2:08 pm

Lately, I reinstalled my wife’s laptop OS. And along with this all the necessary programs. So I decided to do a backup so I can easily reinstall next time, by simply restoring instead of installing the OS, drivers, applications etc.
After a little bit of googling and a short investigation, I decided to use Clonezilla. It is practically a live Linux distribution that can backup and restore your disks and partition.
I was totally impressed. The entire process of backing up and restoring (I restored once, just for testing) was so easy, that the only tip that I can give you is to simply follow the instructions. The interface is not in graphical mode, but in text mode, but it is so easy to use. A wizard like screens, very intuitive and everything works just out of the box. I backed up on an USB hard disk and it was simply recognized and automatically mounted in matter of seconds. And I finished everything in just minutes.
Backing up a partition of approximately 4-5Gb used space lasted around 5 minutes and resulted in a 2-3Gb image. Restoring it, even better: around 3 minutes.
This is the user experience that open source projects should offer. I can say that Clonezilla can easily compete with any commercial products.

February 1, 2009

Visual C in Ant

Filed under: Software — Tags: , — Adrian @ 7:37 pm

Sounds a little bit crazy, but you would probably need this more often than you think. If you develop some JNI applications this probability increases quite a bit.

Nowadays there is a big hype with the Continuous Integration and behind that usually sits a pretty solid build system. So most likely you will have to find a way to create your native libraries automatically and not from the development environment. Not to mention that you would probably want to generate your binaries on multiple environments to ensure compatibility for your JNI application. After all, it is write once, run anywhere.
And isn’t just nice to do everything from one place? One IDE, one build system, etc.

OK, I convinced you. But how do you do it? Ant is simply great when it comes about building Java applications, but what about compiling C code into native libraries? Now is the part where cpptasks jumps to give you a hand. So let’s see how your ANT file will look like for compiling your native library:

<property environment="env"/>
<condition property="iswin">
    <os family="windows"/>
</condition>
<taskdef resource="cpptasks.tasks"/>
...
<mkdir dir="${native.out}"/>
<cc outtype="shared" subsystem="console" outfile="${native.out}/${native.name}" objdir="${native.out}" name="msvc">
    <fileset dir="${native.src}" includes="*.c"/>
    <libset dir="${native.src}" libs="OtherLib"/>
    <sysincludepath location="${jdk.path}/include/"/>
    <sysincludepath location="${jdk.path}/include/win32" if="iswin"/>
</cc></pre

where

  • iswin is an Ant property set only if we are running on windows
  • native.out is the directory where the libraries and object files are generated
  • native.src is the directory containing the C source files
  • native.name is the name of the generated library
  • jdk.path is the JDK installation directory

.

As you can see the C compiler used is Visual C (name attribute of the cc task). And most probably you will need the WinAPI include file, so add the below inside your cc task:

<compiler name="msvc">
    <sysincludepath location="${env.WindowsSdkDir}/include"/>
</compiler></pre

And now comes the messy part. The environment variable WindowsSdkDir must be defined. Without this the compiler won’t even start and you will get an error like this:

Could not launch cl: java.io.IOException: Cannot run program "cl" (in directory "native\out"): CreateProcess error=2, The system cannot find the file specified

.

But fortunately there is a workaround and it is pretty simple, even tough not beautiful. In the Windows SDK distribution there is a .bat file that defines all the necessary environment variables: vsvars32.bat. And its location is defined in an environment variable: VS90COMNTOOLS for Visual Studio 2008 and VS80COMNTOOLS for Visual Studio 8.

So all you have to do is run (in the same CMD session) “%VS90COMNTOOLS%\vsvars32.bat” before running your Ant build (or launching your IDE). And no, there is no (clean) way to set an environment variable from Ant or Java.

January 31, 2009

Sending mail in .Net – just a few tips

Filed under: Software — Tags: , — Adrian @ 8:29 pm

Sending mails in .Net is actually very easy. In just a few lines you can send you very first mail automatically:

MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("myfriend@domain.com"));
mailMessage.Subject = "Adrian's blog rocks";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Check out this cool blog";
SmtpClient emailClient = new SmtpClient();
emailClient.Send(mailMessage);

That’s pretty much it! You’ll probably ask about the from email address and the SMTP server. These are configured in Web.config:

<configuration>
    ...
    <system.net>
    ...
    <!-- the mail settings used to send emails -->
    <mailSettings&gt
      <smtp deliveryMethod="Network" from="admin@domain.com"&gt
        <network host="smtp.domain.com"/&gt
      </smtp&gt
    <mailSettings&gt
    ...
    </system.net>
    ...
<configuration>

But anyway you can specify them too:

mailMessage.From = new MailAddress("admin@domain.com");
SmtpClient emailClient = new SmtpClient("smtp.domain.com");

Multiple recipients

If you want to send your message to multiple recipients, just use message.To.Add. So if you have a string with semicolon(;) separated email addresses here’s the code for you:

String emailAddresses = "a.friend@domain.com; another.friend@domain.com";
foreach (String to in emailAddresses.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(new MailAddress(to));
}

The same goes for CC, BCC, ReplyTo.

Flag a message

Are you a fan of those follow up message? Let me show you how to send them. The idea is pretty simple: those mail messages have two headers – one for the flag and one for the follow up date. To get/set headers of a mail message just use the Headers property.

mailMessage.Headers["X-Message-Flag"] = "Follow up";
mailMessage.Headers["Reply-By"] = DateTime.Now.AddDays(1).ToString("ddd, dd MMM yyyy HH:mm:ss %K");

The above will send a message to be followed up one day later from the sending time. The format of the date in the Reply-By header is specified in RFC822 and if you want to know how to format a date in .Net, see this. If you just want to send your message use what I compiled for you.

The invalid subject error

If you try to set the message subject to a string that contains invalid characters you will get the error System.Net.Mail: The specified string is not in the form required for a subject. This can be easily fixed with

mailMessage.Subject = Regex.Replace(subject, @"[^ -~]", "");

Older Posts »

Blog at WordPress.com.