Aug 20 2009

An ASP.NET web root link handler

Category: .NET | asp.net | c# | Visual StudioJonathan @ 02:56
In order to get a useful, all purpose, all use client-side href link back to root, from anywhere down the web folder structure, and paying attention to IIS6, IIS7, Cassini and other Visual Studio internal web hosting scenarious and of course the odd bug within ASP.NET and your own web site code, I created a handler for ~/.


Here is the html I wanted.


<a href="~/">Some link to root of site</a>



public class RootHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            string toUrl = context.Request.ApplicationPath;
            context.Response.Redirect(toUrl);
            context.Response.End();
        }

        #endregion
    }


    <handlers>
      <remove name="root"/>
      <add name="root" verb="*" path="~/" type="Namespace.RootHandler, Assembly"/>   
    </handlers>


Then with a little more code in the ProcessRequest method, you could find the ~/ part of the url, strip it down and modify the url.


        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            
            string toUrl = context.Request.ApplicationPath + "/";
            string url = context.Request.RawUrl;

            int idx = url.LastIndexOf("~/");

            url = url.Substring(idx + 2);
            
            url = VirtualPathUtility.Combine(toUrl, url);

            context.Response.Redirect(url);
            context.Response.End();
        }


It is only with .NET Framework 3.5, where HttpHandlers have gotten to an acceptable bug free level for use.

Warning: this is a simplistic example for purpose of this post, please be careful in production scenarios.

Tags: , ,

Jul 23 2009

ASP.NET Framework Should Haves

Category: .NET | asp.net | c# | Design | Development Tools | Visual StudioJonathan @ 05:53


ASP.NET should have been a plug-in from the start. The IIS Handler, should have been split into (.NET with ASP.NET) and (.NET without ASP.NET). The idea of a config file and a WebConfigurationManager is not and should not have been specific to ASP.NET.

One cannot help but feel that ASP.NET was designed with Web Server Controls as the flagship feature. "Create that 3rd party market for web". No real thought paid into how people actually use the web on simple terms.

What I am writing here, probably resembled the paper David Heinemeier Hansson scribbled on when thinking and designing Ruby on Rails, but I have no intention of mapping features, just stating the obvious.

Get Server returns html
Post Server *saves data and returns html
Querystring may change what code is executed, and change the "context"
Url may require changing, remapping, extension changes etc

Now, to do this in ASP.NET is relatively straight forward?
Yes it is, simple enough to do each thing, but it gets more complicated when you want all these ideas together.

There is also a grey area as to what we should call easy. Yes it's easy to do x, but is it simple and will it remain simple as time goes by.
The minute you start asking some questions, ASP.NET starts to give varying levels of success. What if it was posted from a different server? What if the html had to be static and not dynamic? what if you need to create your own physical files and return those to the browser? What if you did not want an aspx page at all? What if your new Module wants to create the Page (HttpHandler)

Asp.NET is far too cluttered, and muddled. The design from, Web Server to a response, should have been completely extensible and pluggable.

The problems that I have come across, over the last few months (again), have all been relating to ASP.NET not being able to let go. ASP.NET has so many tenuous links to what you write, its everything but impossible to break away.

A framework should always be designed in layers. A framework should not be a large foundational block, written to sit at the bottom only.

if I am not entirely clear, perhaps a few links into oddities will help.
Actionless Form
Scenarios where switching viewstate off like this does not actually work.
and why caching problems like this does not work properly all the time.
Double postback scenarios
The ridiculous IsPostBack code and scenarios
and it does not end. Friendly adaptors, bad html to asp.net naming, lack of rudimentary support for url manipulation, deflected posts and more, makes ASP.NET a framework look like this.

In my humble opinion, on design/framework notions here are some ASP.NET should haves.

  • The HttpRuntime and associated server objects should have been better formulated and allow for better involvement. Allow extensibility.
  • The runtime should have made Pages (HttpHandler) an optional unit of packaging and code, not the complete target.
  • Better fine grained Page type. Split it into more pieces, separating cache, viewstate and more from the design. So we can use at any of the levels of interest.
  • HttpHandlers should have been designed as a clear open and extensible list of handlers. The pattern should be more workflow like.
  • The compilation process of asp.net syntax and html should have been an exposed set of objects, also extensible. (build providers)
  • Expressions should have been designed much better, and give us control of more of the syntax.
  • It should have been easy to create an aspx file and not have code behind, and include your own syntactical sugar.
  • Asp.NET should have been a plug-in to the .net engine for the web, and not soo tightly coupled.
  • Classic ASP should have been a continued 'available' and compatible unit within the framework.
  • Should have reduced the gap between Server and Client side code. not server controls writing client code out, but rather a whole new better solution
  • ClientID $ in Form and _ in Page? why not allow us to switch it off?
  • All that time it took to develop usercontrols and pages and server controls, could have been better spent on using existing syntax and an html object model for controls. It would have been compliant, less error prone and significantly better.



Personally, I cannot wait for the rewrite of ASP.NET. Unfortunately with all the man hours, money and face they have put into ASP.NET - they wont be brave to throw it away. Yes folks you will be stuck with it, and its even going to version 4.

I like the .NET framework as a whole, I love the c# language, but ASP.NET is a beast. Why on earth they built MVC on top, I'll never know. If it was not for Visual Studio supporting ASP.NET, it would be a disaster.

ASP.NET just should not have!

Tags: , ,

Jun 23 2009

What I am building now

Category: .NET | c# | FrameworksJonathan @ 06:33

I have to build Forms. Web Forms, digital versions of paper forms. You know the kind. You get probably hate filling them in.
Currently there are a few forms, but expectations are, that many, many more forms are to follow. Forms for Edit, Forms with Permissions (part of forms visible to some, editable by others), forms saved as pdf, as html. Each form can expect largely varying workflows. Data from forms to varying database schemas. A complete nightmare to implement generically, but there is a need for a lot of it to sit on top of something familiar and useful across domains and clients.
Some of the goals include:


- easier to maintain, add forms etc, than previous implementations.
- easier to edit and deploy to different sites.
- customizable workflow
- customizable processing.
- Notifications, manual override of process, some manual flow points.

This is kind of like ruby on rails meets Windows Workflow foundation. But alas that wont work out very well, as a combined technology and WCF is overkill in some areas, and might be worth doing on another level. However this is a .NET team, with no WCF experience. Would a quick Activity based object model not suffice?

I have been sitting with this for a few weeks now, and I have 90% of my plan of attack. However, I have started developing already. You guessed it, I have already built a small Framework of my own that will suit this development.
If you have bright ideas, let me know.

Tags: , , ,

May 22 2009

Lack of MetaData on code and .NET Framework libraries


Although .NET Reflecton offers a decent look at the Types you build, it is pretty generic in its offering. For example, it does not yet provide us with capabilities to control and secure how Reflection can inspect our Types. If you do not want a Type to be Instantiated via Reflection, or if you would like to restrict certain Types from being visible at all. Further there is no idea for extension or change. One cannot simply plug into Reflection and override behaviour.

High abstractions and higher flexibility

Many more wrappers are needed, at a higher level, which would sit on top of .NET Reflection. For example, architectural dependencies. Agile mechanisms, if code had enough metadata attached, one could alter the code via reflection/refactoring in a much more dynamic way. Consider the following two web service methods in two different companies.
  public class PersonService
    {
        public void AddPerson(string lastname, string firstname, 
            string birthdate)
        {
        }
    }

    public class PersonWebService
    {
        public void AddNew(string firstname, string surname)
        {
        }
    }

You can see that they are completely different contracts. Interface and contract speaking they are like apples and sand. However, to your mapping, calculating, schema, metadata, tagging and understanding brain, its the same thing.

What we need, is to remove ourselves from Contracts to something more like guidelines.

  public class PersonService
    {
        [Operation(Schema:Person, "Add")]
        public void AddPerson([schema(LastName)]string lastname, 
             [schema(FirstName)]string firstname, 
             [schema(DateOfBirth)] string birthdate)
        {
        }
    }

    public class PersonWebService
    {
        [Operation(Schema:Person, "Add")]
        public void AddNew([schema(FirstName)]string firstname, 
             [schema(LastName)]string surname)
        {
        }
    }

Tags: , , ,

May 22 2009

Reverse Composite

Category: .NET | c# | Design | Design PatternsJonathan @ 04:19
Not sure if there is a Design Pattern relating to this kind of need in another pattern catalogue, but it seemed simple enough to reverse the GOF composite. A class with a collection of leaves, that iterate, recurse its way up to the root. This needs work in terms of combining or actually making a variation on the composite. I think that this is perhaps only a .1 degree of separation.

Problem

You have a list of Items, that may or may not be related. There may be 1 or more trees. You have a bag of unsorted or related objects as a signle array. You need to maintain a complete list of leaves, but also need the relationship/heirarchy to become apparent. You want to express the heirarchy in a Composite Pattern, but it would exclude certain leaves has it has no part in the particular root that the composite gets built on.

Context


You need a collection of leaves, from across the composite tree. You need to have access to the parent and/or recurse to the root.

Types are stripped from its branches.

 

Structure

A class that works with a collection of leaf classes, that each point to it's parent. In effect a composite in reverse. Keep all the leaf objects in a collection and build the heirarchy from the bottom up.




One of the main reasons behind this is multiple paths to a set endpoint. The root becomes the set endpoint where by we can plot a course from a leaf. The Leaf though is where we start from and full knowledge of all leaves should be known at the outset. 

By adding a Parent on the Composite (GoF), you can achieve a similar result, but you will not have a flat list of leaves.

Tags: , ,

Apr 20 2009

Refactoring complex classes using Composition Part 3

Category: .NET | c# | Design | Design PatternsJonathan @ 02:55

To conclude the previous two posts on using composition for refactoring complex classes

Refactoring complex classes using Composition Part 1
and Refactoring complex classes using Composition Part 2

Why should complex classes be refactored? To make code smaller and more manageable. To separate code that changes at different rates, and which are not concerned with the same things.

Composition vs Inheritance? Composition = "has a" relationship, Inheritance "is a" relationship. Inheritance quickly makes you feel like you create Object-Oriented code, but its one of those devices that should be used for a real reason, not just off the cuff.

Reading
- Some background from C2 Wiki - Composition Instead Of Inheritance
- A good principle from Evolve aggregations from inheritance heirarchies - Brian Foote and William F. Opdyke
- Look at Adaptor, Facade, Proxy from Design Patterns (GoF) and also the Stategy, which is mentioned here by Erich Gamma A Conversation with Erich Gamma, Part III
- Refactoring Catalog - Martin Fowler
- Refactoring posts - Martin Fowler

Tags: , , , ,

Apr 9 2009

Refactoring complex classes using Composition Part 2

Category: .NET | c# | Methodology | Refactoring | Visual StudioJonathan @ 04:07

Please Note: Please make sure you have proper unit test coverage on your classes, as you refactor.

From Part 1, I showed you how I initially split a large class into a few more, splitting the complexity of having the code in one place. However, you will still find that for a really complex class, there will still be quite a lot to do. Here are a few more composition based things to consider for continuing the refactoring process.

More...

Tags: , ,

Apr 8 2009

Refactoring complex classes using Composition Part 1

Category: .NET | c# | Methodology | RefactoringJonathan @ 04:09

Please Note: Please make sure you have proper unit test coverage on your classes, as you refactor.

Using Design Patterns which deal with compositional power, such as Wrapper, Facade, Adaptor, Bridge, Proxy and others are extremely useful for breaking large classes down. Rather have 10 smaller classes than 1 large one.

Well here is a very simple start to how to get your refactoring of that large class under way. Please be sure to compile your project after each step, to fix any errors, before moving to the next step.

More...

Tags: , ,

Mar 30 2009

How much should you design Upfront?

Category: .NET | c# | Design | Design Patterns | Methodology | Visual StudioJonathan @ 07:22

FeelGoodFactor

I follow the FeelGoodFactor principle. Requirements at first glance can be cloudy and messy. It can ambiguous and abstract, or it could just be plain daunting. However, you need to list what you can, and the attempt 'solves'. By solves, I mean a logical route to a solve, a prototypical solution to that problem, or at least common consensus by a few good men (cough). You need to get most of the areas in your head sorted, and then commit a bit of that solution in your head to paper and a review by your peers.

More...

Tags: , , , , ,

Mar 25 2009

ExtensionMethods repository

Category: .NET | c# | Design Patterns | Visual StudioJonathan @ 07:15

Oh what joy. Fons Sonnemans and Loek van den Ouweland have created a repository for ExtensionMethods. Go on, you know you want to. The site ExtensionMethod, allows you to submit your own creations to the community.

Now I had this idea, just around 10 minutes before I found the site, so they beat me fair and square. (By a mile). So therefore here is my top three ideas for the site, which I had, and hope they think about.

1. Grade it
Allow us to vote for it. However more than that, flag it with Compiled, Tested. Little icons that the site show next to each method.

2. Open Source the ExtensionMethod
Allow the community to edit the code, which will improve it over time. If I use it, and it fails because of something small, allow me to edit it, and solve the problem for everyone. Add original author, and contributor names to the list. Perhaps allow an 'Editor' per Type, to look after it and make sure its tested and complete.

2. Give us an Assembly
Run a build, once a month, compile all the snippets, which could be done automatically, if you get the correct data from the submitted snippet.
As part of the grading, is whether your automated compilation worked, when including the snippet. (snippet compiler like, compile on the fly and validate the method).

Now we can all download an Assembly for all these community driven ExtensionMethods. Updated: I found this nice, yet strangely odd set of ExtensionMethods for boolean.

Tags: , ,

Feb 23 2009

Software Development Until Done

Category: .NET | c# | Design | MethodologyJonathan @ 06:56

I am touching some code at the moment from a past employee. I cannot say the code is bad, nor that he is at fault. But, the result of half cooked code, is that it takes longer to understand, longer to set up on a new machine, longer to debug, longer to find and fix errors.

I have some brains, but still after 4 hours of delving into a project that utilizes a web service, DotNetNuke and some other projects, could not find the database, then source was checked out, code was duplicated in places (not sure which section was to blame), configuration files named, "development.config", "web.config", "test.config", "x.config", "y.config" made it impossible to find out which things was expected. I have yet to find a single paragraph on what was intended by certain portions of the code.


This is still on going, driving me crazy. I will probably be busy with it for a few days now. More...

Tags: , ,

Feb 12 2009

A Tale of Two Types

Category: .NET | c# | Design Patterns | New IdeasJonathan @ 08:11

Something to think about

I would really like to see Design Patterns merge and disappear into our frameworks and runtimes.

For example, A Singleton could easily become a keyword and managed by the runtime.

But specifically here are two scenarios for merging a wrapper, or form of adaptor pattern.

Mapping Types
If you reference an Assembly (A) from your application that contains a Type that you want to use. Then you discover another Assembly (B), which references (A) you can. However, if the Assembly (B) and the Assembly (A) both reference the same Type from let's say a webservice, the code generated, thinks of these as two different Types. Although they come from the same WCF, or web service, they are treated as different. So creating an AssemblyA.Type and passing it to AssemblyB.Method wont work, as the Types are different. (no they are not). What if I could reference both Assemblies and interchange the two Types as if they were the same. Mark it as the same, and the CLR creates an adaptor/proxy for you.

Now if you have a system, and I have a system, both with a Person object, and happily coincidence it looks exactly the same. Albeit different assemblies, differently signed, it effectively could be the same thing, if only our tools allowed it. So what about being able to explicitly mark the two types so that it can be treated the same. A Wrapper within the CLR

yes we can code this manually
But it is not magically done, and that would save a lots of time. Take how .NET generates COM wrappers. Would you want to write it yourself?

In fact, add Duck Typing to this, method mapping, as explicit choices, a developer can make.
Mark the fact, declare that "treat these two classes as the same". Is this not in effect dynamic partial classes vs the traditional static partial class syntax we have now?

Tags: , , ,

Feb 10 2009

Visual Studio Fonts And Colours Export

Category: .NET | c# | New IdeasJonathan @ 08:52
Here is mine

FontsAndColours.vssettings (9.49 kb)


In gaming we usually share our configs. Wanna start a VS.NET config share?

I would like to export my code formatting and have it applied when I open a source file. BUT, it must not actually change the layout in file. Distinctly different. Just like fonts and colours are not stored in the code.

Just go to Visual Studio 2008, Tools | Import and Export Settings

Tags: ,

Feb 10 2009

Documenting is more Dynamic than you think

Category: .NET | c# | Code Generation | New IdeasJonathan @ 03:36
When we create objects and use config settings to ascertain context and things of that nature, it makes it harder to know what settings there are later on.

This is a significant fact across all things within software. Don't be scared to create small utilities and tools to aid your development. (As long as it does not affect your timelines).
Have you never got to a point in a project when you are wondering why something is not working and it ends up being a config setting?

Here is a simple solution for simple key/value settings More...

Tags:

Jan 25 2009

Code Generation Tools

Category: c# | CodeGenWeek | Design | Development Tools | DOTNETJonathan @ 18:11

All your code are belong to us

Send me a list of your favorites and I will compile a list of them on the website. For now, here are some ad-hoc random ones to perhaps try out. if you know anything about any of these, let me know what you think of them.

http://www.codesmithtools.com/
http://www.ibm.com/developerworks/rational/library/2949.html http://www.tangiblearchitect.net/visual-studio/
http://www.raboof.com/Projects/VsCodeGeneratorShim/
http://www.microsoft.com/downloads/details.aspx?familyid=89e6b1e5-f66c-4a4d-933b-46222bb01eb0&displaylang=en
http://www.jetbrains.com/resharper/
http://www.oracle.com/technology/tech/dotnet/tools/index.html
http://www.mygenerationsoftware.com/portal/default.aspx
http://www.codeplex.com/jeremydotnet
http://www.altova.com/solutions/code-generation-tools.html
http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/
http://www.eurowisesoft.com/
http://www.dotnetsavant.com/
http://www.adonetexpress.com/
http://www.bluage.com/
http://www.razorsource.com/SourceCutter/Overview.aspx
http://www.developerinabox.com/
http://www.innoq.com/iqgen/index.html
http://www.sd.nl/software/
http://www.radsoftware.com.au/codegenerator/

Steve Hansen sent me a link to m-Power

Tags:

Jan 24 2009

One important reason why your Code Generation tool does not get used

Category: .NET | c# | CodeGenWeek | Design | Development Tools | DOTNET | TalkWareJonathan @ 04:20

You say “m_” , I say “_”, lets call the whole thing off!

Code Generation has one tremendous problem.
We dont like the way the code looks.
Majority of the code spat out, is, if not badly formatted, then not formatted the way I like.


Hi, after you read this post, don't miss my Interview with Kent Beck coming soon.


and it does not change the formatting when you don't like the way it was generated or you have to fiddle with codegen settings (which for every tool is different). There are other reasons of course why codegen is not 100% accepted, like you cannot edit the generated code. If you do, it mostly quickly gets overwritten by the next run of the codegen.
But this is already being addressed (a little) by partial classes in .NET, BUT there is still no answer for the formatting problem.

AND let's face it, if any helpful and usable code was generated and it looked like our own code, we would be more inclined to use it.

Introducing JIT Code Formatting

it is not altering the actual layout of the file, it's just the "view" of it.
Just in time code formatting is the process of changing the formatting of any code, no matter how it looks on disk, "to the way you want it". Imagine I send you a small project, you open it and find I have prefixed all fields with an underscore. Your development tool, understanding the semantics and changes the variable prefixes for you when you open it. It formats out the code the way you like it and likewise, when I open it, its changes it the way I like it. It is not altering the actual layout of the file, it's just the "view" of it.

Checking the source into Source Control is not a problem, as it would convert it to a consistent format for before checking in.

For example: In Visual Studio, you would have settings for how you want your formatting. The formatting can be set and pushed to all developers and each developer can have the formatting the way they need and like it.

The JIT-CodeGen engine translates the code to your settings.

Now who wants to write this?

SideBar

Built-in CodeGen in Visual Studio

The T4 templates are an example of a powerful feature in Visual Studio, incorporating code generation, however it will generate the code based on the developers ideas, conventions and standards. This is one of the problems of codegen adoption.
However T4 from Visual Studio is still very cool. Read a little intro by Rob and from Scott

There are many new features coming in Visual Studio 2010, but where is this feature? There is still time, to add it in.

Listen Now:




Download

CodeGenWeekPodCast1.mp3 (7.55 mb)


iTunes

Copy this address: http://www.jonathancrossland.com/syndication.axd and paste it into iTunes.



Tags: , , , , , ,

Jan 13 2009

Do you think .NET namespaces are good to go?

Category: .NET | c# | Design | Design PatternsJonathan @ 14:03

We need to have a lot more control over our Namespaces!

Namespaces offer categorization within your classes and assemblies. Two assemblies could be adding to 1 or more namespaces. But are you not increasing getting two problems.
More and more classes in more and more namespaces. After you look at the Enterprise Library or one of your own applications, or Object Models to give to a client, I bet you have many Types you wish you could hide from them.

Except for adding MyNamespace.Data or some other categorization, a namespace is pretty much useless. They cannot be made private, internal or anything else.

Namespace MyNamespace
{
  //they are always public - no modifiers or accessors allowed.
}


What I find confusing, is how we can get complex features like Generics, but not easier features like namespace control.

The problem

As the .NET Framework grows, and it is continuously, we need to be able to better facilitate visibility across our Assemblies.
If you add the number of Types within the number of Namespaces that you reference compared with Types within those Namespaces that you actually use, you will probably find a huge range from project to project.

When you get your Intellisense window up, you are confronted with miles of Type Definitions, that not only do you not need, but the developer probably never wanted you to actually see it either.

I touched on visibility of classes and members in a previous post regarding Modifiers and InternalsVisibleTo which is not the answer. (although a lot of people seem to site it as a silver bullet, its actually limited.)

What we need is to be able to mark a Namespace with private and internal etc.
We can therefore hide classes within these from the client. Also the whole "x is less accessible than y" needs to be looked at.

Problems

If a Type X has a Property of Type Y. X is contained within Public Namespace, but Y was declared within an "Internal Namespace", it should compile and run without problem. The user should then only see TypeY when in the context of TypeX.

The above rule in psuedo code:

public class client
{
  //from intellisense
  //visible 

  MyNamespace.TypeX
  MyNamespace.TypeX.TypeY.Name // TypeY creatable because its created by TypeX
  

  //NOT Visible - ie. Not creatable 
  MyNamespace.Data.TypeY - 
  
  //TypeY not creatable because it cannot be created outside of TypeX
}

public namespace MyNamespace
{
    public class TypeX
    {
        //Accessible and visible to this Assembly as TypeX.TypeY and 
	    public TypeY Property
	    {
		    get 
            { 
                return _Property;
            }
		    set 
            { 
              _Property = value;
            }
	    }
	
    }
}

//Accessible and visible to this Assembly
internal namespace MyNamespace.Data
{
    //Accessible and visible to this Assembly as MyNamespace.Data.TypeX
    public class TypeY
    {
        public string Name
	    {
		    get 
            { 
                return _Name;
            }
		    set 
            { 
              _Name = value;
            }
	    }
    }
}


Conclusion

None of this would change the way you currently do things, just enable you to better fine tune it. If we have the power (including the .NET Framework libraries to change what is visible in this way, we will be reducing the amount of types and namespaces presented to us within intellisense. We would be able to present a smaller amount of Types and namespaces to our clients (they do get confused or rather scared of something large). Microsoft would benefit from making the .NET Framework appear smaller that it is, programmers would not see namespaces they dont need to see.

Tags: , , , , ,

Jan 11 2009

NonSerializable, and Cloning of Objects with Serialization

Category: .NET | c#Jonathan @ 10:10
Creating a Deep Clone of an object in C#.

Usage:


//Item is a class you have created. substitute it with your Person object or other
CloneFactory<Item> clone = new CloneFactory<Item>();
Item item = clone.Clone(item);


CloneFactory class code.


    public class CloneFactory
    {
        public CloneFactory()
        {
        }

        public virtual T Clone(T toBeCloned)
        {
             T copy = default(T);

            if (toBeCloned == null)
                return copy;

           

            #region if it supports ICloneable
            if (toBeCloned is ICloneable)
            {
                copy = (T) ((ICloneable)toBeCloned).Clone();
             
                return copy;
            }
            #endregion

            #region Does it Contain SerializableAttribute ?
            int serialized = (int)toBeCloned.GetType().Attributes & (int)TypeAttributes.Serializable;

            if (serialized == 0)
            {
                //No serialization Attribute found
                return copy;
            }
            else
            {
                try
                {
                    //It has a Serializable Attribute, lets try serialization
                    using (Mutex mutex = new Mutex())
                    {
                        mutex.WaitOne();
                        lock (toBeCloned)
                        {
                            MemoryStream stream = new MemoryStream();
                            BinaryFormatter binFormatter = new BinaryFormatter();
                            binFormatter.Serialize(stream, toBeCloned);
                            stream.Close();

                            byte[] buffer = stream.GetBuffer();
                            MemoryStream mem = new MemoryStream(buffer);

                            object obj = binFormatter.Deserialize(mem);

                            copy = (T)obj;

                            mem.Close();
                        }
                        return copy;
                    }
                }
                catch (Exception ex)
                {
                    
                    throw;
                }
            }
            #endregion

      
        }
    }


When serializing using XmlSerializer and/or the BinaryFormatter, if you have events hooked up within the object graph, with handlers on your form, you can get serialization errors. if you do, you will get an error like the one below. To remedy this, your must specify that you do not want to serialize certain objects, events by using the NonSerialized for binary and XmlIgnore ? for xml serialization.

For example, often if you are creating proper business objects, you will be implementing the IPropertyChanged interface. A good thing to do! But when trying to serialize you may get errors, if your form has eventhandlers attached.
The answer is to tell the .NET runtime, to not serialize the event. However, you cannot place the [NonSerialized] attribute on an event.
The answer is to tell the runtime that the field (behind the scenes, holding the property event delegate) should be marked as NonSerializable by specifying the field: prefix.



Example error:

Type 'Form1' in Assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Answer: Put NonSerialized on all fields and/or public event declarations

[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;


Tags: , , ,

Jan 5 2009

Accessors for Object Assignment

Category: c# | DOTNETJonathan @ 08:50
How much code do you write, how many bugs occur because one of your objects is null, not set by some piece of code? How many lines of code includes, if (this!=null) etc ? I have seen my fair share of null reference exceptions and you have probably too.

So with Null Reference Exceptions being a very big part of development still, we really do need a way to combat it better. One way I believe would help is by giving us the opportunity to have Accessors on an Object. Just like we have a Constructor, the Accessor, should have the same name, but contain a get and set declararion.

More...

Tags:

Jan 2 2009

Interface Contracts and Access Modifiers

Category: .NET | c# | Design | Design Patterns | DOTNETJonathan @ 05:05
Easier than before, we create Interfaces and contracts quickly and easily, with little or no attention to detail.

Increasingly I have the opinion that we are in a need to control and define our contracts to levels yet unseen. As a base for this, comes the "Public is NOT Published" thought from Martin Fowler

And before you say combinations of ObsoleteAttribute, InternalsVisibleTo and public, private, internal modifiers etc - They do not all add up to the same thing!

Martin Fowler said here and also he said it eloquently enough here , for me to not rehash the argument.


But, "Publishing an Interface" must be thought of as being as complex as in any print media business, where the term is strong. If we are creating contracts, its a shame we have much less control on it than we thought.

And there are a few ways of thinking about what we need.

Do we need access modifiers of type published/unpublished or Attribute based?
Can it be role based, versioned, per client? (I wish to publish these two additional methods to the Administrators group)
Should it be Attributed/Annotated with tools or within the language itself.?

From an Artima interview Erich Gamma says "And in Eclipse we have the conventions for that difference. Actually we even have tool support. In Eclipse 3.1 we have added support for defining rules for which packages are published API. These access rules are defined on a project's class path. Once you have these access restrictions defined the Eclipse Java development tools report access to internal classes in the same way as any other compiler warnings. For example you get feedback as you type when you add a dependency to a type that isn't published."

Is it a good feature in Eclipese? Should we not have something as powerful in Visual Studio and languages?

So where will it go?

Well, I think its extremely important for our future contracts and interfaces to be malleable, and towards that end, Duck Typing , dynamic "versioned" proxies, and other technologies need to come into the frame.

I also believe that a split between Internal and External lines is needed within our code.

Example: Partial Methods is an internal tool, where as Partial Classes is an External tool. By internal, the Partial Method, can never be public, since its an internal feature of the class. The Partial Class can only be declared and partial'ed within the same .NET Assembly Module. This kind of feature (and many more to come) will aid Code Generation directly, making it a far more reliable and superior form of tool. We require these 'internal' helpers for code maintenance and as a "code file splitting technique", but we also need the External (traditionally Interfaces) to be revved up.

btw: Partial methods and classes is one of my favourite features. I like the way it now embodies a design pattern into the inner workings. (Template Method Design Pattern)

CodeGen meets Refactoring, meets new Interface Contract

Consider a tool in your IDE, where you select a class, and select 'Build Facade', which presents you with options and then ultimately creates an Adaptor/Facade for the selected model.

Can Rational do this?

However, importantly it will also set up the access modifiers for the selected classes which will allow us to present the Adaptor to a Client, without them seeing, being confused by, wanting access to additional non essential interfaces. In effect, we now have a new Assembly in Visual Studio, named, code generated talking to the bottom layers. The bottom layers would be marked as InternalsVisibleTo the new generated assembly. I can now supply the Adaptor/Facade to a client. I can then version that off, and create a new generated version of it. We can Select which members to Publish as a set and which to remain public

But thank MS for InternalsVisibleTo

By using the internal and public modifiers. together with InternalsVisibleTo Attribute on the Assembly, the client code, will be able to
  • Call the public member
  • Call internal member (if inheriting from the class)
  • Call the internal member (if InternalsVisibleTo) is added to the assembly attributes




namespace ClassLibrary1
{
    public interface InterfaceA
    {
        void methodA();
    }

    public class TypeX : InterfaceA
    {
        public TypeX() {}

        public void methodA() {}

        public void methodB(){}

        internal void methodC(){}

        private void methodD() {}
    }

    public class TypeY : TypeX
    {
        public TypeY()
        {
            //I can see
            base.methodA();
            base.methodB();
            base.methodC();
        }

        public void methodD() {}

        internal void methodE() {}

        private void methodF() {}
    }
}


So with the code above in one Assembly and the code below in another referenced assembly, the methods you see below are visible.


    //Client Code within a different Assembly.
    public class Class1 : ClassLibrary1.InterfaceA
    {
        public Class1()
        {
            //base contains nothing

            ClassLibrary1.TypeX x = new ClassLibrary1.TypeX();
            x.methodA();
            x.methodB();
            x.methodC(); //if InternalsVisibleTo
            
            ClassLibrary1.TypeY y = new ClassLibrary1.TypeY();
            y.methodA();
            y.methodB();
            y.methodC();//if InternalsVisibleTo
            y.methodD();
            y.methodE(); //if InternalsVisibleTo

        }

        #region InterfaceA Members
        void ClassLibrary1.InterfaceA.methodA() { }
        #endregion
    }

    public class Class2 : ClassLibrary1.TypeX
    {
        public Class2()
        {
            base.methodA();
            base.methodB();
            base.methodC(); //if InternalsVisibleTo

            ClassLibrary1.TypeX x = new ClassLibrary1.TypeX();
            x.methodA();
            x.methodB();
            x.methodC();//if InternalsVisibleTo

            ClassLibrary1.TypeY y = new ClassLibrary1.TypeY();
            y.methodA();
            y.methodB();
            y.methodC(); //if InternalsVisibleTo
            y.methodD();
            y.methodE(); //if InternalsVisibleTo
        }
    }

    public class Class3 : ClassLibrary1.TypeY
    {
        public Class3()
        {
            base.methodA();
            base.methodB();
            base.methodD();
            base.methodC(); //if InternalsVisibleTo

            ClassLibrary1.TypeX x = new ClassLibrary1.TypeX();
            x.methodA();
            x.methodB();
            x.methodC(); //if InternalsVisibleTo
            
            ClassLibrary1.TypeY y = new ClassLibrary1.TypeY();
            y.methodA();
            y.methodB();
            y.methodC(); //if InternalsVisibleTo
            y.methodD();
            y.methodE(); //if InternalsVisibleTo
        }
    }


InternalsVisibleToAttribute needs to also be available to Classes and Members, as well as excluding a member from visibility to the outside. Also it should not be for internals only, but also for public, so therefore VisibleTo Attribute, and ExcludeTo Attribute



Tags: , , , ,