Jan 30 2009

My Interview with Kent Beck

Category: Development Tools | MethodologyJonathan @ 02:26

Hi there DevFans>

Next week, is going to be "just brilliant". I am going to have, none other than Mr Kent Beck, chatting to me about Extreme Programming (XP) and other software issues, right here on my website.

He is a pioneer and real credit to our industry, and I am delighted to have the opportunity to speak with him on your behalf.

The interview will be recorded, and then put up on my feed and of course in iTunes. If all goes well, it will be available on the Friday. So get subscribed, ready for action.
To subscribe, click on the PodCast icon on the top right of my website, or just search in iTunes for my name.

Now which brings me to...

Call to Action

Along with my questions, I would just love to pose some of your questions as well. So if you have anything you want answered, if you have anything you wanted to know from the man himself, now is your chance. Send me your questions, and I will choose the best ones for inclusion.


 

Kent Beck


Kent Beck 
Kent Beck is the founder and director of Three Rivers Institute (TRI).
His career has combined the practice of software development with reflection, innovation, and communication. His contributions to software development include patterns for software, the rediscovery of test-first programming, the xUnit family of developer testing tools, and Extreme Programming. He currently divides his time between writing, programming, and coaching.

Beck is the author/co-author of Implementation Patterns, Extreme Programming Explained: Embrace Change 2nd Edition, Contributing to Eclipse, Test-Driven Development: By Example, Planning Extreme Programming, The Smalltalk Best Practice Patterns, and the JUnit Pocket Guide. He received his B.S. and M.S. in Computer Science from the University of Oregon.
Three Rivers Institute 

Kent is currently researching effective software design. If your company is interested in sponsoring this research in return for early access to his results, please contact him directly. His other business activities include contract programming using Java/Eclipse, writing, consulting (mostly remote), and presenting workshops with his partner Cynthia Andres.

 


Tags: , , , , ,

Jan 29 2009

CodeGen and Visual Studio Snippets

Category: .NET | CodeGenWeek | Design | DOTNET | FrameworksJonathan @ 03:36
Code Snippets in Visual Studio is a form of CodeGen.

You have a template and its injected into your editor. I modify these quite a bit, mainly because I like my properties to have fields with an underscore and named the same as the property:

Here is my Prop.snippet (found in Tools|Code Snippet Manager|C#)
It is a little different as this one matches the variable name with the property, puts the brackets how I want them and also puts my _CamelCasedField name.

Also now with Visual Studio.NET 2008, we have a Code Snippet Editor to make life easier.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
            <Header>
                  <Title>prop</Title>
                  <Shortcut>prop</Shortcut>
                  <Description>Code snippet for an automatically implemented property</Description>
                  <Author>Microsoft Corporation</Author>
                  <SnippetTypes>
                        <SnippetType>Expansion</SnippetType>
                  </SnippetTypes>
            </Header>
            <Snippet>
                  <Declarations>
                        <Literal>
                              <ID>type</ID>
                              <ToolTip>Property type</ToolTip>
                              <Default>int</Default>
                        </Literal>
                        <Literal>
                              <ID>property</ID>
                              <ToolTip>Property name</ToolTip>
                              <Default>MyProperty</Default>
                        </Literal>
                  </Declarations>
                  <Code Language="csharp">
             <![CDATA[
private $type$ _$property$;

/// <summary>
/// 
/// </summary>
public $type$ $property$ 
{ 
  get
  {
    return _$property$;
  }
  set
  {
    _$property$ = value;
  }
}$end$]]>
                  </Code>
            </Snippet>
      </CodeSnippet>
</CodeSnippets>



Yeah, I know its longer, and some like the bracket on the top line {
}
like that, but thats the way I like it. Who can argue?
I know someone who still prefixes everything with str_, int_ and so on. We are all different.

Round Trip Engineering (RTE) for Code Snippets

I believe, the next generation of code snippets, and CodeGen as a whole, should have rte capabilities. using Code snippets as an example, when we embed a code snippet, in our code, it should always understand that it was/is a code snippet.
That way we could change the variable and have it change the expression in the code snippet. In fact this is simply refactoring, but keeping the Expression and code snippet metadata is an important step.

Tags: , ,

Jan 28 2009

Code Generation and Source Code Baking

Category: Jonathan @ 04:42

What if you baked your code?
'CodeBaking' is a design time, optimization process, code snippet engine, code reviewing, validation, code generation tool. It aids you by injecting real code into your existing code. The longer you leave it in the oven (based on settings), the more it can do (based on settings).


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

Do you feel let down, because this doesn't actually exist?

Create your code. Any code, you may but don't need to put directives for the baking process. Your real code mixed with special template constructs that request of the oven, certain things. SExpressions such as
<% expression %> where expression is lambda, and/or oven instructions. For example Nullcheck(variables), will inject code for all variables to be check. Also, exclusions like NoLog, or Ignore or perhaps even range checking ValueRange(0-9), injects code to make sure the parameter is as required. Of course it could also look at real Attributes as well.

By clicking the Bake button (next to the build and run commands), it iterates and applies baking across the project. However, you can also right-click a file, or context selection and bake just that segment. A toggle view of generated code and template expressions should exist, so you can always change things back.

For a moment, forget about the actual syntax and semantics of the Expressions , but consider only one pseudo example.

    public class MyClass
    {
        
        public int MyMethod(string p, <% ValueRange(0-9) %>int i)
        {
            <% LogException %> // think of this as a code snippet like command

            string myP;
            /* only created when PushToFields is baked
            int myI;
            int result = 0;
            */
            <% Validate(parameters) %>; //creates validation and injects the code here
            <% PushToFields(parameters) %>; //maps the data to the fields
            
           if (result >0)
           {
               <% LogValue(result) %>;
           }

           return result;

        }
    }


Now, you push your code into an "oven". Put it in for 20 seconds (perhaps microwave would be better). It iterates through your code, and with each iteration positively affects the code. something like this:
  • Using the Expressions, generates your requested code
  • Validates your code and inserts type checking, null checking
  • Adds Exception handling around blocks of code
  • Applies something else

Then you have a new code file based on your old one, but it always knows what was yours and what it inserted, therefore a simple click, would remove the generated code from your selected property or method. You now continue writing, amending code. the code gets more complete, more robust.

Why stop there.

The Oven, is also capable of looking at running processes and compiled code. After a session of usage, it learns what it should do. So you then bake the code again, so it can apply the learnt aspects. Now it injects more error handling on methods that failed, more logging, splits methods out so that there is a more fine grained error graph and so on.

Codebaking coming soon ?

Tags:

Jan 27 2009

The Top CodeGen App on CodePlex?

Category: .NET | Design | DOTNETJonathan @ 05:53

With downloads of 1294
It's

SubSonic

Ruby On Rails is propelling a new wave of programming - one that drives "Convention Over Configuration". This simple, elegant approach is attracting many developers who find the intricacies and complexity of Java and .NET to be daunting. SubSonic is our attempt to bring this ...

View the project


The nearest one to that amount of downloads is T4 Toolbox
T4 Toolbox is a library of code generation templates for Visual Studio.
T4 Toolbox has 321 downloads, which is sure to increase.

The creator Oleg Sych, will be joining me on a podcast. Subscribe to TalkWare to hear what he has to say about his creation.

PS. I am not affiliated with SubSonic
Although I do like it.

Tags: ,

Jan 27 2009

CodeGen on the Web

Category: Jonathan @ 03:44
Advanced code generation patterns with T4 & DSL Tools (VSX209)
"Code generation is an increasingly common technique in application development and forms a part of many Visual Studio extensions."

Code generation technique using MS codename "Oslo", T4 templating engine and VS Custom tool

Martin Fowler on Oslo

Episode 123: Microsoft OSLO with Don Box and Doug Purdy

First Look at Quadrant – Oslo’s Modeling Tool

T4 Templates in Visual Studio for Code Generation Screencast - David Hayden

"My observation is that the main technique Rails uses to improve developer productivity is code generation, even though Ruby's dynamic nature makes the code generation less obvious..."
- Bill Venners

"Three years ago, in November of 2005 we started a project to upgrade Mono's code generation..."
- Miguel de Icaza's web log

"I had been wanting this functionality since the early days of .NET 2.0, and now it is finally there in the form of the ProcessGeneratedCode virtual method on ControlBuilder."
- Nikhil Kothari

"CodeSmith is a very generic generator. IUt doesn't really favor one way or another"
- World of .NET show

Random CodeGen Tweets

I still had habit side effect from CSLA.net codegen IdString{ get; }
- Chorn Sokun

"Ready to reap the benefits of new CodeGen tool on a largish schema."
- BillB

Other Interest

Prof. Saman Amarasinghe Prof. Martin Rinard
MIT 6.035 Computer Language Engineering
On i-Tunes

Tags:

Jan 27 2009

How to Boost Website traffic and Twitter Followers

Category: Jonathan @ 03:14
10 Ways To Increase Your Twitter Followers
Kevin Rose Here is No.11

Become Robert Scoble (I took the background pic down, see below)
from Imposter


While you are there say Hi.

Tags:

Jan 27 2009

CodeGen in DSL's and Oslo?

Category: Jonathan @ 02:35
If you have some interesting points, views and descriptions of the Code Generation aspects within DSL tools, Oslo etc, please post some comments. I don't know much about OSLO, and I am going to begin my journey into it soon.
However, since my commitment currently is to CodeGenWeek, I thought I would start on Code Generation from a Domain Specific Language pov.

If further, you want a discussion on Skype, that would be excellent too, as I would love a podcast on the topic.

Don't be shy.

A small overview by Darren Jefford and of course subscribe to Don Box spoutlet, the COMFather ,XMLFather and now OSLOFather? Which do you prefer?

But of course, I must also mention The Software Factory God's, Keith Short's blog and Jack Greenfield and Steve Cook and Stuart kent

Tags:

Jan 26 2009

An Even better Idea: Abstract the Code file from the Language

and the editor provides you with visualizations of the code file, which contains a base language, metadata and more contextual information.

The Web 2.0 of Code Editing?

Currently, and even our new tools, like OSLO, when its released, is and will be file based.
Now that in itself is fine, to keep in line with source control and other file based tools. But our Integrated Development Environments require a better, a whole new kind of Code Editor.

I believe that we need to create what I tentatively call ActiveEditors. An ActiveEditor is one which as described above surround code snippets, understands a lot more about Context and the code we write. In order to do that, it should build a Code Tree, Abstract Syntax tree -LIKE, Object Model, separating the FILE from the Editor.

This means that we open a FILE, but view an ActiveEditor, showing a generated “view” of the file.

The actual file and the contents could be XML, or MSIL, but what we see (via built in CodeGen), is c# or vb. So the actual code file needs not be in a particular language.

What does this do? It provides an abstraction that creates a dynamic representation of the code file, in your language. Have a look at the picture. The file could store c#, but it never directly puts the textual content of that file in the editor. Instead, it generates the code, from the model, built from the file, and pushes that into your editor. Based on a setting, the file could be MSIL, and your view could be C#, or any combination.



Now you could write an entire project in c#, but at anytime, switch to VB.NET, and it would never affect anything, because the compiler is compiling the actual file, not your Visual Display within your ActiveEditor that was created.

How would it help?

We could potentially store MetaData within the Code Tree, that would be excluded from viewing, although kept in the file. Your language choice and the code could still be generated as you are used to it. (think code-behind, where the sub document is the base language, which you can show/hide).
This new MetaData, would then actively describe the code so that Code Generation tools and the Editor can manipulate it for context, refactoring and other.


The next big thing? Coming to Visual Studio 10? is it too late ?

Imagine your Visual View of the code had toggle switches, to show/hide comments, show/hide regions, show/hide methods, show/hide classes - it would still be in the actual file, but not in your Visual Display. In the same way, I could switch my Visual Display to VB.NET to edit something, and then switch it to c# to edit something else.
Each developer on the team can view and edit in the language of their choice, it would not matter.
If a team of two was using vb.net, and then 3 more developer were brought on the team, they could continue in the same project in their own language, and it would not change anything.

Tags: , ,

Jan 26 2009

Code Snippets should have Context

"A revolution for editing code in .NET"

One of the most common Code Generation tools involve databases and are called O/R Mappers. This is going to change with the likes of OSLO and DSL's. But historically, Object-Relational Mappers have been the predominant force in CodeGen and they are usually CRUD based. (create, read, update delete) They come in various flavors and I have not used one before now that I still use today. That is, I could never find one that gives me enough freedom to design and implement my project the way I need to, and very quickly I leave them behind. Most have limitations, and don't actually do what it says on the tin.

For example, more than most try to sell you the idea, that it removes the database from you, you can talk to it via the objects, however, I have never found one, that I have not had to go “under-the-hood” to modify a Stored procedure or some aspect of the generated code. So if you do choose to use an O/R mapper, you must be sure, that you can make changes deeper down in the generated code. CodeGen is not good enough yet, to be a black-box tool

But thats one flavor of CodeGen. Other flavors involve Wrappers, Code Snippets, Designer Tools, and general utilities that can generate entire projects and/or layers and everything in between. This post, I would like to concentrate on Visual Studio .NET Code snippets.
Visual Studio.NET Code Snippets currently have a few problems. No editing tool, no built-in way of designing snippets easily. It is one way. It injects the snippet into the Editor and when done, forgets everything about the Expressions. The Refactoring Engine and the Snippet are not friends. They do not communicate.

Code Snippets

Lisa Feigenbaum - Code Snippets in Visual Studio
Ken Levy takes his camcorder over to interview Lisa Feigenbaum and get a look at the new Code Snippets feature in Visual Studio.

Code Snippets Solution applied to all code files, LIVE

A Code Snippet should not “lose” knowledge of the parameters/expressions. Anytime, I click on an Expression (example: PropertyName) that was inserted with a Code Snippet or NOT, it should still understand it. Refactoring would be automatic. Why should it be two separate tasks? Have you ever changed a Property Name, without wanting to change where its referenced?

Consider adding the “prop” Code Snippet. It asks you for Field and PropertyName. Now I believe that this is “kind-of” there for Visual Studio 2010.

But the key missing ingredient, is having our code “always aware”, especially of “expressions”. If you click on a Field it should highlight and as you make the rename change, it should alter your references automatically.

But a Code Snippet is only a small utility, but I wanted to use it as a small example of how code snippets need to keep context and knowledge of its injection, and in the same way Code generation in general has to be able to do this too.

If you generate a class for my person table in a database, and I change the class name, it should, by means of Code Snippet Expressions, Refactoring Engine, understand and align the change across to the database and the the code that references it.

Tags: ,

Jan 26 2009

Whats being said about CodeGen on the NET

Category: Code Generation | CodeGenWeekJonathan @ 10:54

Code Generation Network


CodeGeneration.NET | CodeGeneration.NET FORUM

Listen to CodeGeneration NETWORK - conference of 2007

Episode 1: UML vs DSL: A False Dichotomy?
Includes Steve Cook's emphatic view.

I absolutely love it. Truth with conviction.


Episode 2: The future of


Download the Episodes

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 25 2009

Building My Own Music for PodCasts

Category: Jonathan @ 15:24
So, there are free to use music sites out there. Royalty free, but I could not find something I liked, so I am going to create my own.

Now of course, I don't plan to create master pieces, but I would like something interesting, and slightly repetitive.
And like all radio background tunes, it should have breezes and breaks, hi's and lows.

My first podcast, had music, I made, and here, in advance is the second podcast tune.
Feel free to use it for your podcast, if you like it.

All I ask, is "Please let me know you used it and a brief mention... Like the tune? I got it from jonathancrossland.com."
We all need promotion :)



Download

Tags:

Jan 25 2009

Automatic CodeGen from Design Patterns


An old paper, but worth a read if you are interested in Patterns and CodeGen

Automatic Code Generation from Design Patterns
Frank Budinsky, Marilyn Finnie, Patsy Yu, Toronto Software Laboratory, John Vlissides, T.J. Watson, Research Center

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 9 2009

WCF MaxStringContentLength and Config

Category: .NETJonathan @ 02:47
The data I am sending through the service is very large and very soon, I got the following exception message: "... There was an error deserializing the object of type MyType. The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. .."

By default when using Visual Studio and WCF, your app.config will be injected with some servicemodel settings
Using XMLSerializer on a Type received from my wsdl, I get the error, however, I am not passing it through to the server, just client side serialization, I get the same error.



WCF injects xml configuration into your app.config as below.

 <system.serviceModel>
    <services>
      <service behaviorConfiguration="PublishingService.ProductServiceBehavior"
        name="PublishingService.PublishingService">
        <endpoint address="" binding="wsHttpBinding" contract="OxiNet.Publishing.ITarget" > 
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
         ............cut short



But it did not contain a vital attribute on the endpoint. "bindingConfiguration="WSHttpBinding_ITarget"

 <system.serviceModel>
    <services>
      <service behaviorConfiguration="PublishingService.ProductServiceBehavior"
        name="PublishingService.PublishingService">
        <endpoint address="" binding="wsHttpBinding" contract="OxiNet.Publishing.ITarget" bindingConfiguration="WSHttpBinding_ITarget>  bindingConfiguration="WSHttpBinding_ITarget"
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
         ............cut short


AND it also required a bindings node, of which I am not sure how much of it, it actually uses. My service fails if its not present.


   <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ITarget">
          <readerQuotas maxStringContentLength="2147483647"/>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="PublishingService.ProductServiceBehavior" ..... cut short
      


then your client can utilize a config or code way of dealing with the size.

<configuration>
<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ITarget" closeTimeout="00:01:00"
            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
            bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
            maxBufferPoolSize="524288" maxReceivedMessageSize=" 2147483647"  
            messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
            allowCookies="false">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
              maxBytesPerRead="4012" maxNameTableCharCount="8192" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00"
              enabled="false" />
          <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                algorithmSuite="Default" establishSecurityContext="true" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>


or within code you can get a "Max" version of the XmlDictionaryReaderQuotas configuration.


EndpointAddress endPoint = new EndpointAddress("http://localhost:8731/ProductService");
WSHttpBinding binding = new WSHttpBinding();
XmlDictionaryReaderQuotas readerQuotas = XmlDictionaryReaderQuotas.Max;
binding.ReaderQuotas = readerQuotas;

PublishingService.TargetClient target = new PublishingService.TargetClient(binding,endPoint);

Tags: , , ,

Jan 8 2009

Google and Semantics

Category: Jonathan @ 05:18
hahahaha remember this ?? - "A GOOGLE executive (AAAI Fellow Peter Norvig) told Internet pioneer Tim Berners-Lee that his idea for a Semantic Web will not work because users are too stupid."

link


Well its happening like we knew it would.
According to ReadWriteWeb, Google is already using triples and such to scrape semantic data.


NICE!! the stupid user, will be social networking tags soon - give them more tools.


But what's this about Scoble and facebook?

Tags:

Jan 5 2009

Twitter

Category: Jonathan @ 13:59
As you can see, by the side-bar on the right of my website pages, I am now on Twitter .

It took me months to become a blogger, but twittering came to me very, very late.

I have never really seen the point - but I am there now... lets see if I too get hooked like many many others.

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: