Google+ C# client

By Kenneth 'RabidDog' Clark at November 10, 2011 23:57
Filed Under: C#, Code, Web

After the hackathon, I noticed that the .NET realm is not covered by the current Google+ clients. This prompted me to write a client to facilitate the current APIs. It is strongly typed, easy to use and pretty handy. I have included basic tests to describe it’s usage. Currently it only supports the API Key. Next is the paging and OAuth 2. Check it out if you get a chance https://github.com/RabidDog/GooglePlusNet

 

Ciao

C# HttpWebRequest and HttpWebResponse

By Kenneth 'RabidDog' Clark at November 09, 2011 13:34
Filed Under: C#, Code, Web

 

Another quick post on doing a simple http request and processing the response. Working on the Google+ client for C# and due to the fact the API is REST based, I need to be able to make an HTTP request and process the HTTP response. When looking at the client I am implementing I decided to wrap the whole round trip into a single operation. Here is the results of my labor.

 

First let me give you the class definition:

 

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace CodeShark.Communication
{
    class HttpProcessing
    {
        public static String ProcessRequest(string requestUrl)
        {
            // This will be the raw string response
            String output;

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
            httpWebRequest.MaximumAutomaticRedirections = 4;
            httpWebRequest.MaximumResponseHeadersLength = 4;

            httpWebRequest.Credentials = CredentialCache.DefaultCredentials;

            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {

                Debug.WriteLine("Content length is {0}", httpWebResponse.ContentLength);
                Debug.WriteLine("Content type is {0}", httpWebResponse.ContentType);

                using (var responseStream = httpWebResponse.GetResponseStream())
                {
                    if(responseStream == null)
                        throw new InvalidDataException("Could not retrieve any data from the URL " + requestUrl);


                    var readStream = new StreamReader(responseStream, Encoding.UTF8);

                    output = readStream.ReadToEnd();

                    Debug.WriteLine("Response stream received.");
                    Debug.WriteLine(output);
                }
            }

            return output;
        }
    }
}
Now for a quick explanation. We create the HTTP request using the URL supplied. Then we set some limits on the bouncing the HTTP request can do and set the credentials. The request is fired off when we call the httpWebRequest.GetResponse(). Once we have the HttpWebResponse we need to read the response stream. We get the response stream by calling httpWebResponse.GetResponseStream(). Using this stream you can read the response (presumably text). Pretty simple, nothing to fancy but something we do quiet often without even knowing it.

C# XML and Binary Serialization

By Kenneth 'RabidDog' Clark at November 08, 2011 17:55
Filed Under: C#, Code, Architecture

Recently was working on a small project that required me to store a collection of objects. So I figured I would refresh my knowledge of the serialization available in C#.

 

First I had a look at the XmlSerializer. First you need to define an object to serialize.

 

[Serializable, XmlRoot(Namespace = "http://rabiddog.co.za")]
public class Dog
{
    public Dog(String name, int age)
    {
        this.Name = name;
        this.Age = age;
    }

    public string Name { get; set; }
    public int Age { get; set; }

    //The XmlSerializer requires a default Constructor
    public Dog() { }
}

 

Now that we have the class defined, lets create a collection and serialize that collection to an XML file. Create a console application and then add the following method

 

private static void XmlSerialize()
{
    Dog dog1 = new Dog("Charlie", 42);
    Dog dog2 = new Dog("Jim", 32);


    List<Dog> myDogs = new List<Dog>{dog1, dog2};

    using (Stream stream = new FileStream("MyDogs.xml", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Dog>), new Type[]{typeof(Dog)});
        xmlSerializer.Serialize(stream, myDogs);
    }
}

 

Then call the method from the Main() function, let it run and you should end up with a file called MyDogs.xml in the debug/bin directory. The file should look something like this

<?xml version="1.0"?>
<ArrayOfDog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Dog>
    <Name xmlns="http://rabiddog.co.za">Charlie</Name>
    <Age xmlns="http://rabiddog.co.za">42</Age>
  </Dog>
  <Dog>
    <Name xmlns="http://rabiddog.co.za">Jim</Name>
    <Age xmlns="http://rabiddog.co.za">32</Age>
  </Dog>
</ArrayOfDog>
 

Well that was pretty simple. All we had to do was add the [Serializable] annotation to the class and then create an instance of XmlSerializer to write it to. You could also set the properties to be attributes by decorating them with the [XmlAttribute] annotation.

 

Cool, lets move onto the binary serialization shall we? Using the same Dog class we are going to serialize this down to a binary file.

 

We do that by changing the serializer we are using to the BinaryFormatter:

private static void BinarySerialize()
{
    Dog dog1 = new Dog("Charlie", 42);
    Dog dog2 = new Dog("Jim", 32);


    List<Dog> myDogs = new List<Dog> { dog1, dog2 };

    BinaryFormatter formatter = new BinaryFormatter();

    using (Stream stream = new FileStream("MyDogs.dat", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        
        formatter.Serialize(stream, myDogs);
    }
}

 

Don’t forget to call this method from the Main method. This should produce a MyDogs.dat file in the debug/bin directory. Happy days but there is just one problem. What good is it serializing it if we can deserialize it?

 

First lets deserialize our XML like so

private static void XmlDeserialize()
{

    using (Stream stream = new FileStream("MyDogs.xml", FileMode.Open, FileAccess.Read))
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Dog>), new Type[] { typeof(Dog) });
        List<Dog> myDogs = (List<Dog>)xmlSerializer.Deserialize(stream);

        foreach(Dog dog in myDogs)
        {
            Console.WriteLine("My Dog {0} is {1} years old", dog.Name, dog.Age);
        }
    }
}

 

And the method to deserialize our binary file would be something along the lines of

private static void BinaryDeserialize()
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (Stream stream = new FileStream("MyDogs.dat", FileMode.Open, FileAccess.Read))
    {
        List<Dog> myDogs = (List<Dog>)formatter.Deserialize(stream);

        foreach (Dog dog in myDogs)
        {
            Console.WriteLine("My Dog {0} is {1} years old", dog.Name, dog.Age);
        }
    }
}

 

It thought this was a particularly neat way of storing data on application close. Serialize your object graphs and exit. When you start the application deserialize back to the original state and off you go. No over head of setting up database connections or any other mechanisms of persistence.

 

Yes I know it is old school but is facilitates the requirements for the application I am using. The reason I raise it is because we far to often get caught up in distributed application mentality when something simple like this would do just fine! Below is the enter class file. I hope some one found this useful Smile

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace RabidDog
{
    class Program
    {

        private static void XmlSerialize()
        {
            Dog dog1 = new Dog("Charlie", 42);
            Dog dog2 = new Dog("Jim", 32);


            List<Dog> myDogs = new List<Dog>{dog1, dog2};

            using (Stream stream = new FileStream("MyDogs.xml", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Dog>), new Type[]{typeof(Dog)});
                xmlSerializer.Serialize(stream, myDogs);
            }
        }

        private static void XmlDeserialize()
        {

            using (Stream stream = new FileStream("MyDogs.xml", FileMode.Open, FileAccess.Read))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Dog>), new Type[] { typeof(Dog) });
                List<Dog> myDogs = (List<Dog>)xmlSerializer.Deserialize(stream);

                foreach(Dog dog in myDogs)
                {
                    Console.WriteLine("My Dog {0} is {1} years old", dog.Name, dog.Age);
                }
            }
        }


        private static void BinarySerialize()
        {
            Dog dog1 = new Dog("Charlie", 42);
            Dog dog2 = new Dog("Jim", 32);


            List<Dog> myDogs = new List<Dog> { dog1, dog2 };

            BinaryFormatter formatter = new BinaryFormatter();

            using (Stream stream = new FileStream("MyDogs.dat", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                
                formatter.Serialize(stream, myDogs);
            }
        }

        private static void BinaryDeserialize()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (Stream stream = new FileStream("MyDogs.dat", FileMode.Open, FileAccess.Read))
            {
                List<Dog> myDogs = (List<Dog>)formatter.Deserialize(stream);

                foreach (Dog dog in myDogs)
                {
                    Console.WriteLine("My Dog {0} is {1} years old", dog.Name, dog.Age);
                }
            }
        }

        static void Main(string[] args)
        {
            XmlSerialize();
            BinarySerialize();
            XmlDeserialize();
            BinaryDeserialize();
        }
    }

    [Serializable, XmlRoot(Namespace = "http://rabiddog.co.za")]
    public class Dog
    {
        public Dog(String name, int age)
        {
            this.Name = name;
            this.Age = age;
        }

        public string Name { get; set; }
        public int Age { get; set; }

        //The XmlSerializer requires a default Constructor
        public Dog() { }
    }
}

Protecting a code base

By Kenneth 'RabidDog' Clark at October 17, 2011 16:32
Filed Under: C#, Java, Methodologies

Something that has bugged me for a significant amount of time is the guarantee that the software you deliver to your client / customer is not going to have an adverse or malicious affect on their business.

 

If we look at threats like viruses and malware applications we can protect against those. We have tools and scanners that pick up signatures and take the appropriate action. If we look at the vectors of these attacks they are always external. So something from the outside has to get into your machine in order for them to be effective.

 

First lets do a bit of digging. Generally the biggest threat to any internal business system is not external attacks, it is the internal attacks. How many times have you heard about a disgruntled employee using back doors or knowing how to access the devices remotely and wreaking havoc on the business systems. At a stage this type of attack was considered to be more prevalent and more successful than any other type of attack. The reason for this is a little thing called trust.

 

When a company employs an individual they entrust certain knowledge to this individual. If the individual is responsible for the I.T. systems then even more trust is placed in them. Unlike computers or routers or any other computational device that supports it, you cannot revoke access to the knowledge that the individual has gained while working on, configuring and perhaps even installing in your infrastructure. Some might suggest a segregation of this knowledge in such a way that one role / position does not have sufficient knowledge to compromise the infrastructure. This might work in larger companies but how do smaller companies manage?

 

Now lets take a look from a different perspective. What if you develop software for customers. Your code is going to be running in a trusted environment. It might require elevated permissions to perform the tasks that you are expecting it to. Your clients / customers are placing a significant amount of trust in the company you work for and thereby placing a significant amount of trust in your integrity and moral view points. Should a software vendors employees at any stage become upset with the company they work for and decided to teach their employers a lesson the impact on the client / customer could be catastrophic. Yes I am aware that the customer / client can take action against the vendor and in turn the employer takes action against the employee.

 

My main concern about this chain is how reactive it is. How do you proactively and cost effectively guarantee the code you are releasing will not harm the environment it is being deployed into. Perhaps the idea of paired programming would keep developers in check. The other angle is a dual sign off on a commit to the source repository. Much like banks that require the signature of all partners in a business to authorize spends, dual sign off on a commit would require that two developers approve the code before it is committed to source control. If one developer has some nasty ideas, the second developer can spot them and rectify the code or raise a flag. I don’t see a way that an automated tool could accomplish this. Perhaps it could look for certain signatures and point them out for manual verification but there is no way to decide if something is not supposed to be there.

 

Either way, if you are entrusted with a code base best you remember that with great power comes great responsibility. Any one with other ideas, please share.

Visual Studio 11 on the horizon

By Kenneth 'RabidDog' Clark at October 03, 2011 21:15
Filed Under: C#

Well I never. 2010 is almost over and just when you though it was safe to get to know Visual Studio 2010 Microsoft releases developer previews of version 11. Of course this means there will be an update to the .Net runtime but I am not 100% certain how much is going to change.

 

One of the big pluses is the Async Feature which makes programming wit asynchronous calls far easier. From the article “The Async feature provides an easy and intuitive way to write asynchronous code. This feature makes asynchronous programming almost as straightforward as synchronous programming.” http://msdn.microsoft.com/en-us/library/hh156499%28v=VS.110%29.aspx

I can only suppose the reason for the async hype is the fact that the Silverlight platform and RIA services advocate asynchronous operations over synchronous calls.

 

Although it seems cool, I won’t be downloading the developer preview as we all know what happens when you install beta products from Microsoft on your Windows machine. If you have a virtual machine that you don’t mind bombing then go for it! Me personally, I will wait for the RTM Smile

 

Anyways for more info check out http://msdn.microsoft.com/en-us/vstudio/hh127353

 

Oh and for those of you that use the twitter notify plugin for Windows Liver Writer. The download is available here http://plugins.live.com/writer/detail/twitter-notify. Almost lost my mind trying to find it! Thanks for moving the link Microsoft!

SOAP Message validation in WCF

By Kenneth 'RabidDog' Clark at September 27, 2011 18:16
Filed Under: C#, Web

Well, after a bit more research it seems that Microsoft does support validating outgoing messages. It still doesn’t resolve the issues in my post (http://kenneth.gotcheese.co.za/post/Microsoft-cannot-stop-being-a-rebel.aspx) but does answer where Microsoft feels any validation should be done regarding SOAP. On one hand I agree with them but on the other I disagree. They allow for the INotify property if you enable data binding but they can’t enable the max length on field? Strange I know but I suppose they have their reasons!

 

Anyways, you are able to validate the outgoing message against the declaring XSD. Again this sounds fine but has a few issues, namely those around exposing the XSDs for public consumption. I suppose you could get round this via HTTP authentication but that means you have to push authentication backwards and forwards. The other option is to distribute the XSDs with the client proxies. I see that the Service Reference created in Visual Studio 2010 does exactly this (after rewriting your XSDs for you Smile).

 

To perform the validation you need to first create a client message inspector that implements the IClientMessageInspector.

 

Something like this:

public class MessageInspector : IClientMessageInspector

 

Once you have done that you need to implement the relevant methods (those that the interface declares).

 

The method we are going to focus on is the BeforeSendRequest method. In this method we will perform the validation using the XSD for the message. What you will need to do is check that the Message object is not a fault. If it is a fault return at this point. Next you want to get the Body of the Envelope. This can be achieved by calling GetReaderAtBodyContents()

var bodyReader = message.GetReaderAtBodyContents();

 

Next you going to need to get the XSD for your message. This might prove tricky if you have not got a naming convention that can be used to derive the name of the XSD. A way around this might be to load up the locations of the XSDs into a dictionary (perhaps even load all the XSD Schemas into that list so you can look it up via targetNamespace) but that I will leave to your imagination.

 

Once you have the body contents you open up the XSD file, load it into an XmlReader and read the XML document. If any errors occur, the callback method attached to the XmlReaderSettings.ValidationErrorHandler will be called.

 

First we configure the XmlReaderSettings:

var xsdPath = "path\\to\\your\\file.xsd";

using (var stream = File.OpenRead(xsdPath)) {

   var schemaReader = XmlReader.Create(stream);

   var readerSettings = new XmlReaderSettings
                              {
                                     CloseInput = true,
                                     Schemas = new XmlSchemaSet(),
                                     ValidationFlags = XmlSchemaValidationFlags.None,
                                     ValidationType = ValidationType.Schema
                              };


   readerSettings.Schemas.Add("http://yournamespacehere.com", schemaReader);
   readerSettings.Schemas.Compile();

    //Attach to error event handler
   readerSettings.ValidationEventHandler += new ValidationEventHandler(InspectionValidationHandler);
}

 

Then to validate the document you create an instance of a reader, attach the reader settings and read the document like so:

 

var wrappedReader = XmlReader.Create(bodyReader, readerSettings);

var startDepth = wrappedReader.Depth;

while (wrappedReader.Read())
{
      if (wrappedReader.Depth == startDepth && wrappedReader.NodeType == XmlNodeType.EndElement)
      {
             break;
      }
}

If there are any errors in the document they will be raised while reading and pushed to the callback handler.

 

For more information one solving this problem check out the references I found while solving it:

 

Microsoft cannot stop being a rebel.

By Kenneth 'RabidDog' Clark at September 27, 2011 10:34
Filed Under: C#, Architecture

Well they have done it once again. Microsoft has never been know to conform to what the world of software engineering classes as best practises. They are also known not to confirm to widely published standards.

 

This is true in their Internet Explorer browser (although with the new versions they seem to be getting there) and other products. Yes I know that is how they make money but it is also the way they are losing a great deal of potential customers.

 

I was investigating the SvcUtil tool earlier and was asked to figure out how to enforce the declarations in the XSD limiting the length of string values. Now it would make sense for a client to support this right? Well not according to Microsoft. The XSD.exe utility also doesn’t support doing this.

 

The ONLY reason I can figure Microsoft didn’t do this is because they believe that the service should truncate and enforce the maximum lengths of the strings being supplied. While this might have you nodding your head going “ah yes, well then they have a valid point” my next question to you is, why is that valid?

 

Sure the contract needs to be enforced on the server side, that is a given. If it is not enforced on the server side it is not really a contract is it? However, does this mean that we should allow huge sets of string data to be transmitted if the first 250 characters are going to be consumed? I don’t think that is viable as you are polluting a call that was probably designed to be as efficient as possible. Still not convinced?

 

Well let me throw it back to the consumer or client. If you are generating a client for a web service and you have not explicitly checked the XSD will you be aware of the restrictions? Well you won’t if you haven’t checked it. Then next thing is this. If the validation of those maximum lengths has fallen to the client to verify, how are you going to do that? How are you going to know that string you are submitting must only be a length of 200 characters? The only way you can do this is to verify that the restriction exists inside the XSD and then implement some sort of check on the field with a message letting you if the max length is exceeded.

 

While this might seem like a viable solution, I am incline to disagree. There is a significant amount of work attached to doing this and if the contract should change for what ever reason, you will have to go back and find all the places you have implemented this.

 

I will be contacting Microsoft with regard to this and try and figure out their thinking behind it and if there is a road map to fix it. Until then, if you have any ideas or suggestions please let me know.

JavaScript Hashmap and MVC 3

By Kenneth 'RabidDog' Clark at September 22, 2011 23:00
Filed Under: C#, Code, JavaScript, Web

I was fiddling with an idea that allowed rows to be dynamically added to an html page and deleted off the page. This became a bit tricky because I couldn’t identify the row I wanted to get rid of.

 

Eventually what I ended up doing was maintaining a list of the rows in a JavaScript object that functioned the same as the hash map and as opposed to deleting one row at a time I would remove the entire list from the page and re render it. The reason for this is when submitting arrays to an MVC 3 controller based on a strongly typed model you have to name the hidden input fields sequentially. Something like this:

 

<input type="hidden" id="EventList_0_SomeId" name="EventList[0].SomeId"  value="myid" />
<input type="hidden" id="EventList_0_Capacity"  name="EventList[0].Capacity"  value="25" />

 

As you probably gathered the next one would increment the 0 in the id and the 0 in the name to 1. The next one 2 and so on and so forth.

 

<input type="hidden" id="EventList_1_SomeId" name="EventList[1].SomeId"  value="myid" />
<input type="hidden" id="EventList_1_Capacity"  name="EventList[1].Capacity"  value="25" />

<input type="hidden" id="EventList_2_SomeId" name="EventList[2].SomeId"  value="myid" />
<input type="hidden" id="EventList_2_Capacity"  name="EventList[2].Capacity"  value="25" />

<input type="hidden" id="EventList_3_SomeId" name="EventList[3].SomeId"  value="myid" />
<input type="hidden" id="EventList_3_Capacity"  name="EventList[3].Capacity"  value="25" />

Just as a pointer, the name and the id of the input have to be declared or the MVC 3 controller will not resolve the values. The above example is a model that contains a list of objects that contain a property called SomeId and Capacity. If you do it the way I have illustrated above, it will resolve into a nice object representation in the controller that you can manipulate.

 

The Hashmap declaration:

function Map()
{
    // members
    this.keyArray = new Array(); // Keys
    this.valArray = new Array(); // Values
        
    // methods
    this.put = put;
    this.get = get;
    this.size = size;  
    this.clear = clear;
    this.keySet = keySet;
    this.valSet = valSet;
    this.showMe = showMe;   // returns a string with all keys and values in map.
    this.findIt = findIt;
    this.remove = remove;
}

function put( key, val )
{
    var elementIndex = this.findIt( key );
    
    if( elementIndex == (-1) )
    {
        this.keyArray.push( key );
        this.valArray.push( val );
    }
    else
    {
        this.valArray[ elementIndex ] = val;
    }
}

function get( key )
{
    var result = null;
    var elementIndex = this.findIt( key );

    if( elementIndex != (-1) )
    {   
        result = this.valArray[ elementIndex ];
    }  
    
    return result;
}

function remove( key )
{
    var result = null;
    var elementIndex = this.findIt( key );

    if( elementIndex != (-1) )
    {
        this.keyArray = this.keyArray.removeAt(elementIndex);
        this.valArray = this.valArray.removeAt(elementIndex);
    }  
    
    return ;
}

function size()
{
    return (this.keyArray.length);  
}

function clear()
{
    for( var i = 0; i < this.keyArray.length; i++ )
    {
        this.keyArray.pop(); this.valArray.pop();   
    }
}

function keySet()
{
    return (this.keyArray);
}

function valSet()
{
    return (this.valArray);   
}

function showMe()
{
    var result = "";
    
    for( var i = 0; i < this.keyArray.length; i++ )
    {
        result += "Key: " + this.keyArray[ i ] + "\tValues: " + this.valArray[ i ] + "\n";
    }
    return result;
}

function findIt( key )
{
    var result = (-1);

    for( var i = 0; i < this.keyArray.length; i++ )
    {
        if( this.keyArray[ i ] == key )
        {
            result = i;
            break;
        }
    }
    return result;
}

function removeAt( index )
{
  var part1 = this.slice( 0, index);
  var part2 = this.slice( index+1 );

  return( part1.concat( part2 ) );
}
Array.prototype.removeAt = removeAt;

 

The usage is just as simple. Include the JavaScript file and then:

var map = new Map();

map.put("key", value);
map.remove("key");

//etc

 

A really nice feature is that it does not duplicate keys but performs an “update” on the object at that key. So if you want to retrieve all the keys you can do something like this:

 

for (var i = 0; i < hashMap.keyArray.length; i++) {
    var value = map.valArray[i];
    var key = map.keyArray[i];
    console.log(key, value.toSource());
}

 

 

I found the Hashmap declaration over here http://freecode-freecode.blogspot.com/2007/06/hashmap-object-in-javascript-like.html

 

Some other interesting tid bits on the MVC embedded arrays, lists and editors for:

The importance of rigid definitions – or why a verbose explanation is sometimes a good idea.

By Kenneth 'RabidDog' Clark at September 14, 2011 00:20
Filed Under: C#, Java, Architecture, Work, Code

So I have been wiping the cobwebs from my Java skills and kicking myself for neglecting them. I suppose with work being focused on .NET development, two young children and a training schedule that leaves very little time for exploration on personal projects, it was bound to happen.

 

Anyway, things have changed now and I am able to squeeze in personal development time by sleeping less Open-mouthed smile. Right, lets get to the point of this article. While designing an API in Java I noticed that I was finding it very difficult to package my classes the way I was doing it in .NET so I started doing some digging.

 

My first thought was to have a look at the access modifiers available in both languages. Do a like for like comparison and see if there were any equivalents. So the C# language has the following access modifiers:

 

C#

  • Public: This is pretty much a free for all. The class can be accessed by everything inside the assembly and anything referencing the assembly. This applies to types and type members.
  • Private: This makes members of the class only accessible to operations in the definition of the class. Kinda like private parts Surprised smile
  • Internal: This allows the the types or type members to be visible from the within the same assembly. So even if a different assembly shares the namespace (for whatever reason) it will not be able to access the internal types or methods of the referenced assembly.
  • Protected: This is a member access modifier that dictates that only types that extend the declaring type can access this member. So a shared property, field, method or function that you want to be visible inside a type extending the type declaring the members but not available internally to the assembly or publically.

 

Right lets move on shall we?

 

Java

  • Public: Pretty much the same as C#. Free for all on everything declared.
  • Private: Again, pretty much the same as C# and the private parts.
  • No Access Modifier: This means that anything declared in the type or the type itself will only be visible in the package space it is declared in. Remember this! It is the topic of this post.
  • Protected: Available to types extending the declaring type.

 

Right lets get to the point of this article. Now that we have established each languages modifiers, lets have a look at this http://www.javacamp.org/javavscsharp/internal.html

 

Looking at that you will see that the C# access modifier “internal” is implied to be the equivalent of the Java default or no access modifier declaration. Does the Java definition behave the same as the C# internal definition? Well have a look at the definitions again:

  • C# Internal: Accessible to everything inside the assembly. This means namespaces moving up to the root namespace and down to the last namespace node.
  • Java No Modifier: Only available inside the package it is declared in.

 

Can you see it yet?

 

Lets have a look at a code sample real quick:

C# Code sample

//Assuming this is inside assembly my.cool.dll
namespace my.cool.project{
  internal class Cheese(){}
}

namespace my.cool{
    public class StartTheCheese(){
        var cheese = new Cheese(); //valid
    }
}

namespace my.cool.project.goes.on{
    public class DigestTheCheese(){
        var cheese = new Cheese(); //valid
    }
}
//end assembly

//Assuming this is inside assembly my.ref.dll
namespace my.cool{
    public class DoWeHaveCheese(){
        var cheese = new Cheese(); //invalid
    }
}

Java Code Sample

package my.cool.project

class CatchMe(){ // note that no access modifier is declared
 //body
}

package my.cool

public class TheCheese(){
    CatchMe catchMe = new CatchMe(); //fails!   
}

You can see it now right? The primary, intrinsic difference is that the C# internal modifier can span multiple namespaces in the same assembly. The Java declaration with no access modifier cannot be seen outside the package my.cool.project. This means that there is no equivalent “internal” in Java. So here is the crux of the matter. If making comparisons, like in maths, we have to find the lowest common denominator before comparing or performing operations of logic in deciding the equivalents. Compare apples with apples to avoid confusion. Things we might take for granted will drive other people mad!

 

References:

Fluent Email and Git hub

By Kenneth 'RabidDog' Clark at September 07, 2011 23:05
Filed Under: C#, Code, Open Source

So after submitting the changes for Fluent Email to the initial developer and him suggesting that I create a fork of the repo to contribute via, I finally got round to doing it. So what I am going to do is share my experience here.

 

First thing you need to do is git installed on your machine. The installer can be found here http://code.google.com/p/msysgit/downloads/list (I went for the full installer download). Then proceed to install the package and follow the instructions. Once you have completed that install you are going to need to set up your RSA keys to be able to connect to git hub via the bash. You can add your keys at the address https://github.com/account/ssh.

 

Right the next thing you might want to get is tortoise git. Simplifies the process of using git quiet significantly! Yes I am going to learn the command line stuff Winking smile Tortoise Git can be found at http://code.google.com/p/tortoisegit/downloads/list

 

Right now we got everything set up the next thing you need to do is fork the repo you want to work on. The instructions can be found here http://help.github.com/fork-a-repo/. Once you forked the repo you can now clone it to a directory on your machine (much like SVN), then edit away and when you ready you can commit your changes and push them.

 

I updated the Fluent Email to allow use of the template parsing outside the context of the Email class. I thought this would be handy for situations like I had recently where I needed the parser but not the email. I would have created another project for the parser but figured that the credit is due to the initial developer so left it in there. Then I refactored the addressing mechanism to remove duplicate code. It now reuses a single mechanism to parse the email addresses and names. Anyways if you interested check out https://github.com/RabidDog/FluentEmail



I am South African. Always have been always will be. I love my country. I love my wife and two children.


I also really enjoy solving problems. I currently work as a Software Architect exploring new solutions for business problems. Having been round the block a few times I enjoy showing new developers how best to solve problems, how to find answers and how to approach solution development.


In my spare time I enjoy riding my super bike, training in Systema and horsing around with my family.


Month List

Visitors

Twitter Feed

21. May 10:15
Still can't believe that they used american actors in Invictus. Just doesn't fit!

17. May 17:12
@UnexpectedPippa only 3? "Don't touch me on my studio!"

17. May 17:12
@SaartjieJoan if you look around you might see many forks hanging out of eye sockets

17. May 17:09
@SaartjieJoan That truly is amazing HAHAHAHA!