Tuesday 4 December 2007

log4net exception: System.Configuration.ConfigurationRecord.Evaluate

A new error has appeared, when making an application, which uses my proxy.

at System.Configuration.ConfigurationRecord.Evaluate(String configKey)
at System.Configuration.ConfigurationRecord.ResolveConfig(String configKey)
at System.Configuration.ConfigurationRecord.GetConfig(String configKey)
at System.Configuration.DefaultConfigurationSystem.System.Configuration.IConfigurationSystem.GetConfig(String configKey)
at System.Configuration.ConfigurationSettings.GetConfig(String sectionName)
at log4net.Config.XmlConfigurator.Configure(ILoggerRepository repository)
at log4net.Config.XmlConfigurator.Configure()
at DHE.IdhSession..ctor() in C:\DHE5\dev\client\net_client\DHEproxy\DHE.CommonInfo\IdhSession.vb:line 1027
2007/12/04 15:25:16.572 2912/5068 err 0 | init*start main DHE shared object: dhe
_process 0x0
2007/12/04 15:25:16.572 2912/5068 err 0 | gs_k_init*start main DHE shared object
: dhe_process 0x0


Which funny enough appeared because of a spelling error inside the App.config. Another reason for reading the exception messages... (evaluation error blink blink)

The problem is that its not always completely clear, when VS.NET sees it fit the override the config file in the bin dir, with the one you just corrected.

Tuesday 30 October 2007

The type of a vb.net Object

If you need to find verify that an object is of a specific type it can be done in the following way:

If TypeOf Err.GetException() Is DHEException Then

This uses the keyword "TypeOf" and "Is" I have used it to make sure that the exceptions, catched though the bad "On Error" statement, is still handled and the correct error code is returned.


If Err.Number <> 0 Then
If TypeOf Err.GetException() Is DHEException Then
Dim ex As DHEException = Err.GetException
cerr = ex.dheErr
Else
cerr = -(1000000 + Err.Number)
End If
errMsg += "|ExecService:" + Err.Description + " " + Err.GetException.StackTrace
log.Error(errMsg)
End If

Thursday 25 October 2007

Configuration exception for log4Net

I have been battling with the following error, for almost three days now:

System.Configuration.ConfigurationException: Error loading XML file c:\windows\microsoft.net\framework\v1.0.3705\Config\machine.config Request for the permission of type System.Security.Permissions.StrongNameIdentityPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. (c:\windows\microsoft.net\framework\v1.0.3705\Config\machine.config)


I have developed a proxy client which worked perfect when I ran my NUnit tests, but when I tried to make an external application which should use it, there was this error. I finally found the it was a version mismatch between two version of log4net, where I had used 1.0 net version for developing my proxy, I had by mistake added the 1.1 net version of log4net to the application.

Same problem also gave me the following error:


System.TypeInitializationException: The type initializer for "log4net.GlobalContext" threw an exception. ---> System.TypeLoadException: Invalid PInvoke metadata format.
at System.Net.OSSOCK.gethostname(StringBuilder hostName, Int32 bufferLength)
at System.Net.Dns.GetHostName()
at log4net.Util.SystemInfo.get_HostName()
at log4net.GlobalContext..cctor()
--- End of inner exception stack trace ---
at log4net.GlobalContext.get_Properties()
at log4net.Core.LoggingEvent.CreateCompositeProperties()
at log4net.Core.LoggingEvent.LookupProperty(String key)
at log4net.Layout.Pattern.NdcPatternConverter.Convert(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Layout.Pattern.PatternLayoutConverter.Convert(TextWriter writer, Object state)
at log4net.Util.PatternConverter.Format(TextWriter writer, Object state)
at log4net.Layout.PatternLayout.Format(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Appender.AppenderSkeleton.RenderLoggingEvent(TextWriter wriSystem.TypeInitializationException: The type initializer for "log4net.GlobalContext" threw an exception. ---> System.TypeLoadException: Invalid PInvoke metadata format.
at System.Net.OSSOCK.gethostname(StringBuilder hostName, Int32 bufferLength)
at System.Net.Dns.GetHostName()


So if you are fighting with a similar problem, check the versions of you .NET framework and the version of the log4net.

The hint was to read this (link)

Tuesday 23 October 2007

log4net troubles one among several

After having successfully used log4net to implement a new proxy client ( used nUnit tests to test) I now find myself in some difficulty. Because to test the proxy even further I want to run another program, which uses my Dll to talk to the server.

My first problem is of course that programs are never as loosely coupled as one could wish, and therefore I had to remove some hard coded references from the new test program.

Now that the tests actually run my code, I have a problem with configuring the log4net framework.

First thing is to study the application configuration file a bit, Visual Studio allows you to create a file called app.config by right clicking on the solution title in the solution explorer (the thing usually on the right). This file will then be copied to the bin dir, with the proper name, when the solution is compiled (link).

Solution:
The thing that should be remember is to add the following line somewhere its sure to be called before the log is used:

log4net.Config.XmlConfigurator.Configure()

At least if you are configuring the log4net in the app.config file.

Thursday 18 October 2007

Sets created by sql joins

Sorry, no explanation only a link to somebody who does explain, with diagrams:

http://www.codinghorror.com/blog/archives/000976.html

Tuesday 9 October 2007

There Ain't No Such Thing As Plain Text.

Encoding, is always a funny thing when you debug distributed application (also client server architectures). For the simple reason, that you test output from the client, might not look the same from the servers point of view, since there might be differences in the encoding.

So remember to think about, what happens to you request string. remember the following example:

Make a string in any given language:

String testString = "Test string";

to print this to the console, use:

System.out.println(testString) <- println uses a default encoding to print it, the bytes in memory.

When the testString goes through several steps, before it is reached by a server.
First et will be encoded to go on the network (socket), and decoded again by the server. There is therefore 3 different places, that a single debug output, can be different from the what the server actually saves.

The following article describe the very basics of encoding, do you self a favor and read it, or something similar.

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

Its easy and very understandable.

Wednesday 26 September 2007

Drop down list in Excel

I always have a hard time remembering how to make dropdown lists in Excel, her is a nice tutorial of how to do it:
Excel dropdown

And when you make a mistake, as me, this tutorial shows how to edit the list.

edit dropdown

Thursday 20 September 2007

Playing with sockets in vb.net

I am having trouble with sockets. I send a message and want to retrieve some information. Until now I thought that it was the receive which gave me the problems, but in fact the problem arrives before. Cause the send method throws a SocketException with the text “The attempted operation is not supported for the type of object referenced”.

nb = s.Send(ByteSend, ByteSend.Length, SocketFlags.Peek)

Now this doesn’t really help me. So I looked for the Error code, which were 10045. Looking in the error code list (link) gave me the following additional knowledge (or whatever you want to call this message) :
Windows Sockets Error Codes:

WSAEOPNOTSUPP 10045
Operation not supported.
The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.


Now did that help. I ended giving up on the code so I cant really tell you what the solution is. But for reference, I choose to publish this post anyway. Sorry

Wednesday 18 July 2007

got on the train of rails

Now its finally time for me starting to read the "Agile Web Development with Reails 2nd ed" so I can be updated at bit on how this rails works, not that there is any job related interest yet, just a wish to try and learn (and to code my secret project).

Anyway to start somewhere I just downloaded ruby 1.8.6 from www.ruby-lang.org where there also is an excellent tutorial called "ruby in 20 min" try it, its nice and fast (link).

Unittesting private methods

I found something that throws an exception in a private method, to make sure I correct it, and it keeps corrected, I would like to write a couple of tests for that method. But its private, so how do I go..

I read the following article, which do describe it for Java, but the same problems apply for vb.net (except I dont know if .net reflection allows one to access private methods like java)
Testing Private Methods with JUnit and SuiteRunner

As you will see, there is no nice way to do it, so I think I will try to rethink the design, and then see if I really need to test a private method.

Finishing with a quote:
In general, you don't want to break any encapsulation for the sake of testing (or as Mom used to say, "don't expose your privates!")

By Dave Thomas and Andy Hunt, in their book Pragmatic Unit Testing.

Monday 16 July 2007

Configuration of the tests

I find myself in the dilemma of having to run my tests in a new database with a new set of data. This should not be an surprising event, but it does require that I "update" my tests to the new reality. Cause I cant use the same keys, as before.

So how does one solve this problem. I thought up two different solutions, where one is pretty nifty but time consuming, and the other is more slow, but probably the one I am going for.

The first one, is to circumvent the util being tested, and access the database directly, and auto generate the needed row keys ect. here, one could use the loved (and hated) datasets of .NET

The second more boring one is simply to make an xml file, containing all the configuration- the key to be used for testing get methods, the search critia for the list search, and the expected size of the result, ect. For this solution one misses the ease of java's properties library.

After surfing the Net, I found this article on CodeProject "Managing configuration settings persistence in .NET applications", which describes how to read a xml file into a dataset. I will try that solution.

This post will be updated...

Monday 9 July 2007

logging in client proxy

I have found myself wondering what is a good logging strategy. There are several levels to consider, when you are implementing a client/proxy for an existing server. So far there are two major scenarios, where its interesting to log, one can be said to be sub case of the other.

-Regular logging where you are just interested in logging the fact that there is been send a request to the server, when, what and who.

-Debug logging where its interesting to look at the execution path through the client code. which will pinpoint anything strange. This can of cause also be done just by stepping through the code, but I would be much easier if one were able to insert enough debug writes to support an easy identification of the exceptional behavior.

Since the regular logging of the 3 w's is included in the debug logging, my plan is to include this info as a normal debug output, and then just filter it, to make the prober log file which is an requirement.

The overall strategy (using log4net) is the following levels:

- log fatal if the client losses the connection to the data source
- log error if there is thrown an exception or an err code is returned.
- log info when a workflow is finished. (for example the data written in a dump file)

More posts will follow of how to set up everything...

Monday 18 June 2007

removing spyware

Once again has the "Coding Horror" blog written a very useful blog. As a computer scientists I am always expected to know how to save virtually any system from virus and stupid users. One of the top problems, I always run into is people which have allowed spy ware onto their computers, making them slow and unpredictable.

In the linked blog, there is a description of how to remove spyware. (link)

Enjoy cleaning...

Tuesday 12 June 2007

Reflection

Reflection is the mechanism of discovering class information solely at runtime. Reflection has been introduced with the .NET framework, and its usage of metadata.

Metadata is data about data, and in .NET framework it is contained along the code, to allow, among others reflection. The Metadata consists of class names, method signatures and the like, to enable both for runtime lookup of a class (i.e reflection) but also to enable the cross language execution. When the compiler compiles code, it always create the metadata along with the compiled code, and puts it in the assembly.

Reflection means being able to get instantiate a class of a type, just by providing the name of the class at run time or invoke methods just by presenting their name.

The use of reflection is slow and should only be used when absolutely necessary (link).

Maybe more later

Friday 8 June 2007

Software developer you are you owne worst nightmare

Stop writing code, its just more lines where bugs and errors can hide. The following is snippet I have copied from one of my own favorite bloggers Coding Horror, which writes about "the best code, is no code at all" where he actually references another blog written by Wil Shipley who argues that we should rein in our natural tendencies to write lots of code:


The fundamental nature of coding is that our task, as programmers, is to recognize that every decision we make is a trade-off. To be a master programmer is to understand the nature of these trade-offs, and be conscious of them in everything we write.

In coding, you have many dimensions in which you can rate code:

* Brevity of code
* Featurefulness
* Speed of execution
* Time spent coding
* Robustness
* Flexibility

Now, remember, these dimensions are all in opposition to one another. You can spend three days writing a routine which is really beautiful and fast, so you've gotten two of your dimensions up, but you've spent three days, so the "time spent coding" dimension is way down.

So, when is this worth it? How do we make these decisions? The answer turns out to be very sane, very simple, and also the one nobody, ever, listens to: Start with brevity. Increase the other dimensions as required by testing.

Which is some very clever words. You cant have everything, and the things you want, always comes at a cost of something else.

Now go coding and remember to use the KISS principle (Keep It Simple Stupid)

Thursday 31 May 2007

Properties in C#

All good programmers have spend hours made getters and setters. So Microsoft have decided to make it a bit harder (I think now, I might change my mind later).

Heres an example of old time code

public class MyClass
{
private int x;
public int getX()
{
return x
}
}
ect.
In you application you can get x with the following code:
mc.GetX();

Now C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.

<acces_modifier> <return_type> <property_name>
{
get { }
set { }
}

This means that I can do the top example the following way:

Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor.

For example the above program can be modifies with a property X as follows.

class MyClass
{
private int x;
public int X // property
{
get
{ return x;}
set
{ x = value;}
}
}

The object of the class MyClass can access the property X as follows.

mc.X(10) // setter.
y = mc.X // getter.

I think its a step in a good direction, but splitting the attribute and the property is in my view, just as bad as not having them.

Wednesday 30 May 2007

equal types in vb.net and c#

Even though c# and vb.net uses the same libraries, there is some differences in what name identify the classes, below I will make a list.








vb.netc#
Booleanbool
DateSystem.DateTime
Stringstring
int32int


And keywords:







vb.netc#
Sharedstatic
Friendinternal
ReadOnly*const*



*)
const:

- Can't be static.
- Value is evaluated at compile time.
- Initiailized at declaration only.

ReadOnly:

- Can be either instance-level or static.
- Value is evaluated at run time.
- Can be initialized in declaration or by code in the constructor.

vb.net friend becomes c# internal

Porting a friendly structure from vb.net to c# is done by altering the "friend" keyword to "internal" in c#

Regions in .NET

As a fan of agile development, where everything should be structured into small classes, its hard to see regions as anything but a bad solution for a bad problem. But they are here, and people are using them, so no sense in not knowing what they do. Its a simple answer:

They do nothing, zip, nada. A region is simply a construct to enable Visual Studio.NET to hide pieces of code outside of the normal bounderies of methods, structures and classes.

In vb.net a region have the following for:
#Region "DataTypes"
' types of service:
#End Region

And in c#:

#region "DataTypes"
// types of service:
#endregion

So no magic here... Sorry

Garbage collecting in .NET

The .NET framework have automatic garbage collection, and uses an algorithm called “mark and compact” which is an variant of the “mark and sweep” algorithm, where the heap is compacted after each garbage collection. This makes the allocation very fast, since the heap is always compacted and the next free slot is just the bottom of the heap (the heap grows downwards)

Research has shown that you can split objects on the heap into two groups, the young ones which will only survive until the first garbage collection and the old ones which will stay in the heap through out the execution. The .NET garbage collector uses this by only garbage collecting the young generation each time, and the old only when its needed. [For more information read the article, or ask me]
Even though the garbage collector is automatic it doesn’t mean that you can make programs which will suffocate the GB. I the following is a list of some of the problems which can cause long GB breaks.

Performance:

• Too many allocations: Its very easy to create many temporary elements which will make the GB pause long. Don’t use f.x. String.Split, creates a new String object for each split
• Don’t make too large allocations
Its very cheap to make new allocations, and too big allocations will trigger the GB much more often, which is expensive
• Too many pointers
Structures with many pointers takes time to for the GB, because it has to run through all of them. For long lived structures this is not a problem, but if these structures will be made on a transitory basis. Even with a long lived structure can give problems, if the structure is changed over time, this can endup being distributed through out the heap and thereby make it harder for the GB to “compact” the heap
• Too many roots
Too many roots will make the mark process too long. Making deep recursive methods with many object pointers, is also a no no.
• Too many object writes.
Write to an object, and its pointers have to be checked by the GB, because the object will be registered in the card table
• Too many Almost-Long-Life objects
The biggest pitfall of them all. To avoid these kinds of objects, your best lines of defense go like this:
1. Allocate as few objects as possible, with due attention to the amount of temporary space you are using.
2. Keep the longer-lived object sizes to a minimum.
3. Keep as few object pointers on your stack as possible (those are roots).
• Use only Finalization when its necessary.
If an object is dead but has a finalizer it will be kept alive until the GB have time to run the metod body, and also all the referenced objects inside the object. Therefore use only a finalizer when its really needed. Move resources which need finalizing to a root object, to minimize the size of elements in inferno.
In many cases it is much better to implement the IDisposable interface.

To get the best out of the allocator you should consider practices such as the following:
• Allocate all of the memory (or as much as possible) to be used with a given data structure at the same time.
• Remove temporary allocations that can be avoided with little penalty in complexity.
• Minimize the number of times object pointers get written, especially those writes made to older objects.
• Reduce the density of pointers in your data structures.
• Make limited use of finalizers, and then only on "leaf" objects, as much as possible. Break objects if necessary to help with this.
Personally I think that these requirements above is a bit to restrict, because you will find other perspectives which will contradict these requirements. But I added them here as a guideline.

References:
[GB1] Mariani, Rico: Garbage Collector Basics and Performance Hints, 2003 (Link)

Structures in c#

A structure in c# is at first sight the same as a class, but there are differences, which I will describe in the following, but first the structure of the structure:


Structure:
A structure in c# has the following form:


<modifiers >
struct<struct_name>
{
//Structure members
}

or an actual example

struct Weight
{
public int
value;
public string
unit;
}


And is instantiated like this:

Weight ms = new Weight();

Unlike classes, the struct object can also be created without using the new operator.

Weight ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized.
At the bottom I have attached a larger example of a structure.


Properties of a Structure:

A structure can contain
fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

It is even possible for a structure to implement a interface or inherit from another structure.

interface PhysicalUnit
{
public int getValue()
}


struct weight : PhysicalUnit
{
private int value
public int getValue(){
return value
}


The difference:
The difference between a structure and a class is the place it is put in memory. Because as we all know an object of a class type is put in the heap, with a reference (pointer
) on the stack which points to the object. An object of structure type on the other hand is placed on directly on the stack.

Example:

Below is an example of a structure which shows how a constructor, properties ect.

using
System;
struct
Complex
{
private int
x;
private int
y;
public Complex(int i, int
j)
{
x = i;
y = j;
}
public void
ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}
}
class
MyClient
{
public static void
Main()
{
Complex c1 = new
Complex(10,20);
c1.ShowXY();
// displays 10 & 20
Complex c2 = new
Complex();
c2.ShowXY();
// displays 0 & 0
c2 = -c1;
c2.ShowXY();
// diapls -10 & -20
}
}


Operator overload
It example above also includes an example of an operator,

public
static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}


which is new to me from the Java world. but a nice feature, which should be used
carefully, since in this example its quite intuitive what happens if you take one element and subtracts it from another. But in more complex types of structures this can be more misguiding than helpful.


Tuesday 29 May 2007

Nunit in action

On my new project I am implementing a proxy, in the .NET framework. Its currently in Beta (implemented 2 years ago), and is implemented in VB6. So to be more clear I have some old VB code which should be ported, updated and tested. I vote for implementing (porting) it in C#, since I like brackets and ";" and just think its a better language than VB.NET. Anyway this blog is about how I am going to use NUnit it my new C# project (which Im starting while they are making the decision).

For info on NUnit go here (Link)

I have made a new C# project in Visual Studio 2005. which should be the actual project. In this I will add a new project to be my NUnit test project called test, which should be console application. If my new project is called "Proxy" my folder structure is as follows:
My main project: \projects\Proxy
My test project: \projects\Proxy\Test

My test project be in the same namespace as the Proxy namespace otherwise the tests wont run on private methods. You may need to add the Proxy project to the NUnit test project. so it can see the methods it should test.

Now every time I make a new method, I will make one or more test methods, to test it. And a new test class for each new class.

When I have implemented a couple of lines, I compile the testcode, and run the tests in NUnit GUI.

I just found this excellent tutorial about how to use NUnitTest in vb.net (link)

Thursday 17 May 2007

Learn your child to program

Carnegie Mellon has developed a tool called Alice, for kids and other children to learn how to use object oriented programming. The tool allows you to programming figures in a virtual 3D world. Its not rocket science, and if one need to learn programming one would probably move on quickly, but hey its fun, and introduces the concept.

Wonder how early a parent can start :)
http://www.alice.org/

In fact after looking a bit on the net, there is also other alternatives. Here is one from MIT research lab http://scratch.mit.edu/ which is a bit more complicated.

Tuesday 8 May 2007

The funny thing about SQL

I recieved a lession SQL logic the hard way, the other day.
Can you find the difference between the following two statements:
1)
select AY__ICODE, AY_UCODE, AY_SHNAM, AY_EXDES
from A_AYBOOK, A_ACTIVITY, A_MAYREQ
where MQ_IATTY = AY__ICODE
AND AK_AYCODE = AY__ICODE
and AK_BKCODE = 'IU010H01RNOL'
and MQ_IUNIT = 'SPEDA000001Y'
2)
Select count(A_ACTIVITY.AY__ICODE)
from A_AYBOOK, A_ACTIVITY, A_MAYREQ, A_SERPOIN
WHERE MQ_IATTY = AY__ICODE
and AK_AYCODE = AY__ICODE
and AK_BKCODE = 'IU010H01RNOL'
and MQ_IUNIT = 'SPEDA000001Y'
The from clause in the second statement contain a extra class A_SERPOIN. This makes the SQL return many more elements, because it interprets this as a inner join. Therefore read all your statement, before using.

Friday 27 April 2007

Middle age support

There are some things which can always make me laugh, this small movie is one of them:

http://www.boreme.com/boreme/funny-2007/introducing-the-book-p1.php

Now some friendly sole has added English subtitles, actually supertitles, and danish subtitles. But it doesn't ruin the fun.

Enjoy.

Not a blog without a manifesto

Hello reader (which is probably only myself),

This is my technical blog, lets see what kind of tech it will contain...

BC30560 asp.net

'xxx' is ambiguous in the namespace 'YYY'...


Is an error I had some fun with, because I, of course, thought it was something in the code. But finally (after googling a bit) I looked in my bin directory, where I found a dll-file that contained an old version of 'xxx', which made the 'xxx' visible to the application in two versions.

Upla... yet another example that it is a very good idea to read and understand the error messages.