Tag Archives: .net

Overriding and overloading in Java and .NET – differences, changes and gotchas

Foraying even more in the fundamentals of Java (coming from a .NET background) I’ve come across some interesting things, along with changes in Java SE 5. But first let’s clear up a bit these two notions (overloading and overriding).

Overriding

Is a language feature that allows a subclass/inheriting class to have a method identical (we’ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ.

This is by no means a definitive definition, Wikipedia, .NET CLS’s and JLS may very well differ slightly.

A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :

public class Dog 
{
    public virtual void MakeSound()
    {
         Console.WriteLine("Bark.");
    }
}

public class Hound : Dog
{
    public override void MakeSound()
    {
         Console.WriteLine("Wooofff!!!");
    }
}

Java developers unaware of the intricacies of C# will wonder what is that “virtual” thing. In C# all methods are “final” (sealed) by default unlike Java where methods are “virtual” (non-final / non-sealed) by default. This is a profound difference which we’ll discuss later. The “:” stands for “extends”. We’ll discuss the “override” keyword soon, also.

The equivalent piece of code in Java would look like :

public class Dog {
    public void makeSound() {
        System.out.println("Bark.");
    }
}

public class Hound extends Dog {
    public void makeSound() {
        System.out.println("Woofff!!!");
    }
}

Read more »

Beginning Java for .NET Developers

I’ve always wanted to learn another language and platform and being a long-time .NET developer Java seemed the closest to my knowledge and one which would seem easy to learn based on what I already knew.

I’ve put off this for various reason along the last 3-4 years, most of which laziness was chief.

Recently some colleagues moved from our project to another project that involves Java modules and since .NET is not a first-class citizen in my employer’s eyes I thought maybe it could serve me as a kind of an ‘insurance’ – to learn Java.

I’ve obtained (..) some ebooks (Effective Java and Thinking in Java), downloaded JDK, a few IDEs (IntelliJ IDEA and NetBeans, no Eclipse for me, thanks) and started doing HelloWorld’s and stuff like that. I noticed JavaFX (which is quite similar to WPF on which I currently work)

I’ve came across two nice comparisons of Java and .NET, written in a constructive manner (i.e. not “mine is better, na nanana”) :

Using these two articles I compiled (yes, that’s the original meaning of the word :P ) a PowerPoint slideshow.

Then I thought there might be other (.NET developer) colleagues that might be interested in my research and gave an internal presentation based on the slideshow and expanding each item by talk.

I thought I should share it with everyone so here it is (download here) :

I’ve written about Java / C# differences before, and I might continue that series in the near future, with practical examples and counter-examples.

A useful custom configuration section for inline unconstrained XML

As I was writing a small TCP server for serving a Silverlight local TCP policy, I came across a certain need. Inspired by Dan Wahlin’s server implementation, I chose to write a simplified version for myself. I needed to keep some XML in the App.config without constraining it with a schema.

The normal solution in this case is a custom section, sibling to appSettings if you wish. So my App.Config looked at first like this:

<configuration>
  <appSettings>
    <add key="ipAddress" value="127.0.0.1"/>
  </appSettings>
  <access-policy>
    <cross-domain-access>
      <policy>
        <allow-from>
          <domain uri="*" />
        </allow-from>
        <grant-to>
          <socket-resource port="4502" protocol="tcp" />
        </grant-to>
      </policy>
    </cross-domain-access>
  </access-policy>
</configuration>

Upon running the program, even addressing the “ipAddress” key in the appSettings section throws an exception like:

System.Configuration.ConfigurationErrorsException was unhandled
  Message="Configuration system failed to initialize"
  Source="System.Configuration"
  BareMessage="Configuration system failed to initialize"
  Line=0
  StackTrace:
       at System.Configuration.ConfigurationManager.PrepareConfigSystem()
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at System.Configuration.ConfigurationManager.get_AppSettings()
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Andrei\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Configuration.ConfigurationErrorsException
       Message="Unrecognized configuration section access-policy. 
               (C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config line 8)"
       Source="System.Configuration"
       BareMessage="Unrecognized configuration section access-policy."
       Filename="C:\\Users\\Andrei\\Documents\\Visual Studio 2008\\Projects\\ConsoleApplication1\\ConsoleApplication1\\bin\\Debug\\ConsoleApplication1.vshost.exe.config"
       Line=8
       StackTrace:
            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
       InnerException:

So something is wrong. We need to tell the runtime that the “access-policy” section is allowed.

<configuration>
   <configSections>
    <section name="access-policy" type="CustomSections.InlineXmlSection, CustomSections"/>
   </configSections>
  ...

At first, I didn’t place the type attribute in the “section” element, but it turned out it had to be specified and not be empty. Moreover, it must contain the fully-qualified class name and the assembly which contains it. The class must inherit from System.Configuration.ConfigurationSection.
Also ensure that the assembly name is specified after the coma, in the type attribute and the configSections section is the first child element of the configuration (root) element.

So, I created an assembly called CustomSections, and added references to the System.Configuration assembly and the System.Xml assembly.

All you need to do is override the DeserializeSection method and load the XML document in there:

using System.Configuration;
using System.Xml;

namespace CustomSections
{
  public class InlineXmlSection : ConfigurationSection
  {
    public XmlDocument Content { get; private set; }

    protected override void DeserializeSection(XmlReader reader)
    {
      (this.Content = new XmlDocument()).Load(reader);
    }
  }
}

The code is pretty self-explanatory: we instantiate a new XmlDocument and load it from the XmlReader provided to us by the configuration infrastructure. If anything goes bad, the exception handling will be the responsibility of the caller. In this case, the first call to ConfigurationManager.

Now, let’s put the code to use:

private static void Main(string[] args)
{
  expectedRequestBytes = Encoding.UTF8.GetBytes("<policy-file-request/>");
  listener = new TcpListener(IPAddress.Parse(ConfigurationManager.AppSettings["ipAddress"]), 943);
  var policySection = (InlineXmlSection)ConfigurationManager.GetSection("access-policy");
  policyBytes = Encoding.UTF8.GetBytes(policySection.Content.OuterXml);
  ...
}

The underlined code is the relevant portion (the rest is provided for context). We get the section via ConfigurationManager.GetSection, and we have to cast the result to the desired section type. Then we use the section as we see fit.

WP Like Button Plugin by Free WordPress Templates