Friday, January 30, 2009

C# : Removing non-ASCII characters

I was trying to filter some files and remove all the non-ASCII characters. Using Mr. Google lead me to this very helpful
post.

Essentially:


string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]", "");


I didn't want control characters so my filter was \u0020-\u007F.

Enjoy!

Thursday, December 04, 2008

Java : Axis2 client and Log4J

I was busy testing a client developed using the Eclipse plug-ins in the previous post.

This came up with the following error message.

log4j:WARN No appenders could be found for logger (org.apache.axis2.description.AxisService).
log4j:WARN Please initialize the log4j system properly.

To set this up inside an Eclipse project:

* Create a new folder in the project called e.g. "log4j".
* Add a file to that folder called log4j.properties which contains something like:


# Set root category priority to INFO and set its only appender to A1
log4j.rootCategory=INFO, A1

# A1 is set to be a ConsoleAppender (writes to system console).
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n


* In the project's "Run Dialog", click on the "Classpath" tab / "Advanced" / "Add folder" and then browse to the "log4j" folder previously created.
* That's it

Enjoy!

Java : Tomcat / Eclipse and Axis2

I needed to develop a Java web service that ran inside Tomcat and used Axis2 as the web server component.

I use Eclipse as my Java IDE and was looking around for plug-ins that would automate and simplify the whole process.

Came across this excellent tutorial - Developing Web Services Using Apache Axis2 Eclipse Plugins - Part 1

This uses two Eclipse plug-ins:

Apache Axis2 Service Archive Generator Wizard and
Apache Axis2 Code Generator Wizard

which generate the proxies and then wrap everything up for deployment to Tomcat.

I highly recommend working through the tutorial and then using that knowledge to develop and deploy your own.

Enjoy!

Java : Finding jars and classes

I seem to spend half my life looking for jars and classes to solve the ubiquitous "Class not defined" problem.

Found this very useful resource which allows you to find which jar files contain the required class and then download them if needed.

Enjoy!

Friday, November 28, 2008

Visual Studio: Intellisense XML files

I was playing with Rhino Mocks which comes with a .dll and a .xml file (for the Rhino Mocks Intellisense) but couldn't get the Intellisense to work.

You need to put the xml file in the same directory as the dll file and then restart VS.

Then all should be fine.

I did find bits and pieces that lacked Intellisense but I guess that that's a problem with the XML file?

Enjoy!

Wednesday, November 19, 2008

LINQ : Simple LINQ to XML

It's really simple to construct XML documents with LINQ. This simple construct (inside LINQPad):


XDocument simpleDoc =
  new XDocument(
    new XElement("TopLevel",
      new XElement("SecondLevel",
        new XElement("a", "b",
        new XAttribute("class", "level"))
      )
    )
  );

simpleDoc.Dump();


produces:


<TopLevel>
  <SecondLevel>
    <a class="level">b</a>
  </SecondLevel>
</TopLevel>


Enjoy!

Tuesday, November 18, 2008

LINQ : LINQPad with auto-completion / Intellisense

This is in beta as we speak.

If you can't wait, invoke as:

LINQPad -beta

Really unlocks the power of LINQ since you can now see what options are available.

Enjoy!

LINQ : LINQ samples and ObjectDumper

There's a good selection of LINQ samples here. I ran up most of them in LINQPad.

However, some of these samples use a method called ObjectDumper (which does much the same job as object.Dump() in LINQPad).

The source for ObjectDumper can be found in this zip file. Save the files in an ObjectDumper directory somewhere and load them as a Project under Visual Studio. (Note that the sample is for VS 2008 but I had no problems doing this with VS 2005. Just remember to click on the .csproj to open the project and not the .sln!).

Then build the project which will create a .dll and add this .dll to the LINQPad "snippet" using "Advanced Properties" (F4)", then "Add" and then "Browse" to where you created the .dll.

Enjoy!

LINQ : Use of elements of string array

Again, using LINQPad:


string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

var getDigits =
from d in digits
where d[0] == 't'
select d;

getDigits.Dump();


This selects all elements in the array where the first letter is "t".

Result is:

two
three

Enjoy!

Wednesday, November 12, 2008

LINQ : ToArray() and Take()

Using the usual LINQPad and the Northwind DB:

So we first get the last names from the Employees table and put them into a string array using the ToArray() construct and then we get the first 4 using the Take() construct.


string [] allEmployees1 = Employees.Select (e => e.LastName).Take(4).ToArray();

allEmployees1.Dump();

foreach (string s in allEmployees1)
Console.WriteLine(s);


Enjoy!

LINQ : Some string handling

Based on an example by Eric White, here's some simple string handling (running as always inside LINQPad).


// Per Eric White. The following is a query to split a string into words, only
// allow words > 1 character, eliminate the ones that contain the letter
// "y", convert the words to lower case, count the number of occurrences of
// each word, and return the ten most used words.

string text = "Debugging LINQ queries can be problematic. One of the reasons is that quite often, you write a large query " +
"as a single expression, and you can’t set a breakpoint mid-expression. Is LINQ really that problematic? " +
"Queries can be fun as is debugging!";

var uniqueWords = text
.Split(' ', '.', ',', '?', '!')
.Where (i => i != "")
.Where (i => i.Count() > 1)
.Where (i => !i.Contains ("y"))
.Select(i => i.ToLower())
.GroupBy(i => i)
.OrderByDescending(i => i.Count())
.Select(i => new { Word = i.Key, Count = i.Count() })
.Take(10);

uniqueWords.Dump();


Returns:

Word Count
is 3
debugging 2
linq 2
queries 2
can 2
be 2
problematic 2
that 2
as 2
one 1

Enjoy!

Friday, November 07, 2008

LINQ : Some more on foreign keys

Continuing the series of LINQ to SQL using the Northwind DB:

Note: Can only be done if table has "Entity Set" relationship with another table i.e. green left-pointing arrow in LINQPad

Let's start with a compiled query:


var products = CompiledQuery.Compile ((TypedDataContext dc, decimal minUnitPrice) =>
from prod in Products
where prod.OrderDetails.Any (c => c.UnitPrice > minUnitPrice)
select prod
);

products (this, 20).Dump ("Unit price > $20");



OK - let's try that as a simple lambda without the compiled query:


var products1 =
from prod in Products
where prod.OrderDetails.Any (c => c.UnitPrice > 20)
select prod;

products1.Dump();


OK - let's try writing that again the "SQL" way with foreign key x = foreign key y:


var products2 =
(from prod in Products
from od in OrderDetails
where od.UnitPrice > 20 && prod.ProductID == od.ProductID
select prod).Distinct();

products2.Dump();


Hang on! There's far too many rows. That's because the relationship is duplicated so we need to add the "Distinct" keyword. You'd think that the construct would be:

select prod.Distinct();

but that doesn't work. If you look closely at the code snippet above, you'll see that the "Distinct" is applied to the whole clause (look at the brackets) rather than just the "Select" element.

Enjoy!