Design Patterns #8: Iterator

Design patterns episode 8 – Iterator

Today’s pattern is the Iterator – an easy way to cycle through collections without worrying how it is achieved – in simple words. Let’s see what the Head First book has to say about that.

DEFINITION

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying implementation.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

This is achieved by two interfaces: one abstracts the iterator, the other abstracts the aggregator. To make things clear – the aggregator is a class that provides a collection we want to iterate through.

So, there is a class called ConcreteAggregator that has a collection of objects. The diagram above depicts a generic version of the pattern (this not a must, you can write your own specific iterator) so the collection stores objects of type T. The ConcreteAggregator doesn’t want to allow direct access to that collection so it implements the IAggregator interface to allow the client to use the iterator by invoking GetIterator() method which returns ConcreteIterator which in turn implements the IIterator interface. This interface is the core of the pattern: it provides methods to actually iterate through the collection: i) Reset() to move index pointer to the start of the collection, ii) HasNext() to indicate whether there are more elements in the collection, and finally iii) Next() to get an element from the collection.

ITERATORS IN .NET

The .NET Framework uses this pattern widely in collections. To make long story short – in System.Collections (or System.Collections.Generic) namespace you can find IEnumerable interface which has only one method: GetEnumerator() – sounds familiar, right? Most of the collections implement this interface – Lists or dictionaries for instance, not to look far. This method returns an object the implement IEnumerator interface. In this case this interface is slightly different:

This post .NET namespaces Explanation
void Reset()
void Reset()
no difference
bool HasNext()
bool MoveNext()
In .NET interface this method moves the pointer to next element and returns: true – if advanced successfully without passing the end, false – if passed the last element and set the pointer to the first element
<T> Next()
object or <T> Current { get; }
In .NET this property returns object at current position of the pointer without moving to next element

EXAMPLE

In the example we will create a book library. This class will store books in a private list but will expose an iterator. Let’s start with the interfaces:

They’ve been already discussed above so the only thing I would like you to pay attention to is the fact that they’re generic.
Next step – implement the iterator:

To complicate the code a bit the implementation will use an array to store the values, beside that we also have an integer to indicate current position. In the constructor we initialise the array of values and copy them from the list passed as an argument. The last thing we need to do in the constructor is to set the index indicator to Reset() the position indicator. The only thing that Reset() method do is to set value of position indicator to -1. Why -1 not 0? That is because we use Next() method to get values: this method first increments the indicator and then extracts the value. Method HasNext() simply check if position index increment operation would not exceed the length of the array of values.

The Library class is very simple – in its constructor we fill the list of books and implement the IAggregator interface: the GetIterator() method returns new LibraryIterator with list of books passed as an argument.
And everything works perfectly. Here’s some code to test that:

And that’s it – the iterator in its full swing:
Here’s couple of links that may also be useful:
Why iterator is important: [YouTube] by Christopher Okhravi
Another code example: [YouTube] by Michael

Source code: [TXT file]

Design Patterns #7: Template Method

Design patterns episode 7 – Template Method

This post is about template method pattern. Those who are familiar with the Head First book may be wondering where’s facade. The answer to that question is that I deliberately decided to skip the facade at this point. I will definitely come back to this, but maybe next time. Now, let’s move on to the template method.

DEFINITION

The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

What the above mean? It means that the pattern is built on base abstract class which has a public method which defines our algorithm by invoking in intended order some other methods which may be overridden by subclasses. The algorithm’s member methods may provide default implementation of be abstract forcing the subclasses to provide their own unique implementation.

EXAMPLE
Most of the examples you can find is based on preparation of pizza, coffee etc. And they’re really good. Pizza for instance: when you’re cooking a pizza no matter what style you basically do the same: prepare dough, add sauce, toppings, put it into oven and cut. That’s the algorithm. But you certainly do different dough for American pizza and for traditional Italian pizza, you add different toppings for vegetarian pizza and for meat pizza – and that’s the where we may want to override our sub-methods of the algorithm.

The code below will not be about pizzas, it’s going to be a generic code that does nothing but show how the pattern may be implemented.
Let’s take a look at our base class:

As you can see our TemplateMethod() is not marked as virtual therefore it cannot be overridden – this is the skeleton of the algorithm. In its body this method invoke all member methods – subOperations from 0 to 3. Interesting thing is that the last member method will be executed only if a condition is true. This is called a hook. This is one way to alter the invocation list of the algorithm. You don’t need to use is but it’s good to know. Besides that we have combination of  methods with default implementation, abstract methods and those you cannot overwrite. In our case only one methods needs to be implemented in a subclass – let’s take look:

So, our concrete implementation overwrites one method with implementation in  base class and provides implementation of one abstract class. Simple, so let’s see how it works:

To witness the template method we instantiate new ConcreteTemplate and observe how it behaves – with optional method executed and without.

And that’s the template method pattern. The best explanation of this pattern I’ve found so far is in the Head First book but below you will find also one link to a YouTube video with Phil Japikse – you may find it useful.
Thanks for today and expect the next pattern next week.

Design Patterns: Template Method – YouTube
Source code: TXT file

Design Patterns #6: Adapter

Continuing with design patterns. Time for Adapter. This pattern is a structural pattern whose purpose is to convert interface (in a meaning of public members of the class, not necessarily interface as a programming language feature) so the class is usable with client’s code. The Head First book defines this pattern as:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work that couldn’t otherwise because of incompatible interfaces.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

Generally, it may be said that the adapter pattern wraps an object that cannot be used by a client and exposes an interface that allow the client to use that object. Let’s take a look at the diagram:

So, we have a client that wants to use an object that implements IExpected interface, however we already have a class that does what we need but doesn’t have a compatible interface (unsupported class). So, to solve the problem we need an adapter. The adapter will have all public members that the client expects – will implement the IExpected interface and at the same time will privately wrap an instance of unsupported class (passed in a constructor, for instance). Once the client calls the adapter, the adapter will in turn call the wrapped unsupported class and return results to the client (and if required convert them to what the client expects). And that’s it, simple as that.

EXAMPLE
Let’s take a look at code example now. We have a class that calculates area and perimeter of a rectangle. (These calculations are very simple but to give the example a little bit more depth think of them as of very sophisticated and complicated). That class operates on double type. Our client, however wants to calculate area and perimeter of squares only and operates on integers. We could i) write a new class to handle that but we don’t want to do that because we already have a class that is capable to perform such calculations (square is a rectangle after all, right?); ii) modify our client to work with the existing class, but again we don’t want to break anything elsewhere (OCP right?). That’s why the right solution here is the adapter.
Let’s compare what we have and what we need:

So, the differences are: i) types (already mentioned int vs. double), ii) method names, iii) number or arguments required for counterparting methods.
Now the adapter. First of all it needs to wrap the already existing class and set its instance by passing it through constructor; then we need to implement methods required by IExpected interface in a way that they call the wrapped object and return values converted to integers.

Let’s write a quick test:

Everything works perfectly.

Object adapter vs. Class adapter
The explanation and code example is an object adapter. This means that the adapter works with a concrete instance of adapted object. Advantage of this solution is that this type of adapter will work also with objects of classes which are derived from adapted superclass.
There is also another adapter-type pattern called class adapter. In this type you don’t need an instance of adapted class, instead the adapter class inherits from both: expected class (or interface) and adapted class. Remember that inheriting from more than one superclass is not possible, what could be done is to create new class that inherits from a class that needs to be adapted and implements expected interface. This approach may also be useful but keep in mind that it looses the advantage of composition over inheritance.

To sum things up: adapters are extremely useful everywhere there is a need to use something that can do what we need but doesn’t have compatible interface.
Plan for next week: Facade

Don’t forget to check the links below!

Christopher Okhravi about Adapter Pattern: [YouTube]
Source code: [TXT file]

Design Patterns #5: Command

Fogadtatás,
delayed but here I am with the next design pattern. This time it’s the command pattern. Those who are familiar with the Head First book might be wondering where’s singleton. The Some time ago I wrote a post about singleton (which you can find [here]), so there’s no point in going back. Therefore we go straight to the command.

The command pattern encapsulate calls to objects and provides undo mechanism for those calls. This is achieved by command classes which can perform an action over an object and are assigned to callers. Let’s take a look at the diagram:

Let’s start discussing the above from the ICommand interface and its concrete implementation. The interface has two methods: one for proper action, one for undoing the action. The implementation additionally has reference to IReciever object which defines over what type the command can execute. This is not mandatory, for instance you can declare your execute() and undo() methods to take IReciever as parameter. The important thing is that concrete command operates on certain type, however the caller doesn’t know anything about the receiver, the only responsibility of the caller is (so to speak) to call.

The example in the book is really great. The authors presented a programmable remote controller for an intelligent house. The controller has multiple buttons which can be assigned with a command that can operate lights, home cinema etc.

EXAMPLE
Our example will be programmable counter. The counter will have 5 buttons to manipulate the value of the counter. The counter will have undo feature. This time the code example will have WinForms GUI with custom controls for buttons-callers and counter-receiver.

The caller will have a button to execute a command and a drop-down list to ‘program’ the button with one of the available commands.

 The receiver will have a text-box with current value, button to reset the counter, button to undo last command and a list of all executed commands (operating in FIFO-like mode, the newest on top, the newest first to undo). This user-control will also implement IReceiver interface which provides integer property CounterValue (which play the role of action() method from the diagram) on which the commands will operate and AddToTrace methods which will be used by a command to enroll itself to a command trace for undoing.

Now, the command. Let’s start with the interface:

Beside two already discussed methods Execute() and Undo() the interface provides also Name property (which will be used by the UI) and Receiver property for referencing the counter on which the command will operate.

Concrete command
Now, let’s take a look at one of the commands which implements ICommand interface:

The Execute() method increments the value of the counter and puts the command to the top of the command trace for undoing. The Undo() method simply does the opposite of the Execute() method which is to decrease the counter by one. Removing it from the command trace will be the responsibility of the undo button in the counter user-control.

Command trace
To make it possible we need to keep track of what commands have been executed. For that reason our counter user-control is equipped with a private list that holds objects of type ICommand. The command can enrol itself to the list by invoking AddToTrace method of the receiver and pass itself as an argument.

Once we have the list we can use the undo button which takes the first element off the command trace and invokes the Undo() method.

And that’s it. Take a look how this operates. 

So, that’s it for today. Don’t forget about the source code below and come back next week!

Source code: ZIP file

Design Patterns #4: Factories

Hello there!
It already is a weekend so time for next pattern from the list: factories. Factories are creational-type patterns which means they are used to (surprise, surprise) to create instances. There are three types of factories (of which only latter two are considered as design patterns): simple factory, factory method and abstract factory. Let’s start with the non-pattern one.

SIMPLE FACTORY
Simple factory is a class that has a method to create a certain types of objects where the decision what exactly type to create is made by the factory itself based on given parameters. Assume that we’re building a book store and we want to sell paperbooks, audiobooks and ebooks. We have definitions of a sub-class for each of them implementing IBook base interface. We can build our simple factory in a way that we pass a char parameter and if it matches with first letter of our sub type we create that sub-type:

And that’s it: we have our simple factory. But the problem is that when we want to introduce another sub-type it is necessary to modify that class. And we don’t want that. And why you find [here].

FACTORY METHOD
About factory method I’ve already written [one post]. Consider this post as a supplement to the previous one.
Factory method solves the issue we had with simple factory by removing it’s responsibility to decide (based on the parameter) what type exactly to create. If we want to modify the factory we’ve created above we would need to create separate classes responsible for creating each type of book. And that’s what was done in my [first post] about this pattern:

Now, if we need another sub-type we simply create another class that will create new sub-type.
Let’s take a look at the definition:

Factory method pattern defines an interface enabling to create a single object making the sub-class implementing this interface to decide what exactly type of object to create.

What does the above mean? It means that the client at the point of invocation of factory method doesn’t care (and doesn’t need to care) what type is going to be created: the client wants an object and is going to get one. Very good example is provided by Christopher Okhravi [here] – a simulator a national park where multiple types of animals dwell and the simulator care only about the right number of animals, when it needs an animal to spawn it just calls the factory and the factory decides what animal to create. (I’ve already said that multiple times but I highly recommend his [playlist] about design patterns.)
And now the UML:

We have an abstraction of factory method class and its concretion that creates an instance of a class which is a concretion of one interface common to all sub-types of product.

ABSTRACT FACTORY
If you know how the factory method works understanding the abstract factory will be a piece of cake. Let’s start with the definition:

Abstract Factory provides an interface for creating multiple related or dependent objects without necessity to define their concrete classes.

And the UML:

So, the client uses a factory to create instances. The factory is abstracted by the interface which has multiple (in the case above two) concretions which create two related sub-types of ProductA and ProductB. The IFactory interface doesn’t specify what concrete classes will be instantiated and the client doesn’t care. It is the concretion of the factory which specifies what sub-types of products exactly to create. So, in really really short we may say that the difference between factory method and abstract factory is that the former creates only one type objects while the latter can create multiple types of objects (related and/or dependent).

And that’s it. Before I say goodbye: have a look at the links below to find out more about factories; plan for next week – singleton.

Christopher Okhravi: Factory Method Pattern – Design Patterns (ep 4)
Christopher Okhravi: Abstract Factory Pattern – Design Patterns (ep 5)
CODE Project: Factory Patterns [Snesh Prajapati]

Design Patterns #3: Decorator

Design pattern number 3 – decorator. The decorator allows to dynamically modify behaviour of an object, and by ‘modify’ I not necessarily mean to swap completely.
The idea behind decorator pattern is that you take an object and wrap it with another object. Calling the outer object (decorator) will in turn call the inner object (component) and before returning any value will do its part with the value.

The example given in the book is a coffee shop where base coffee can be decorated with multiple toppings such as cream, sugar etc. And all those addition will make their own impact on price and name. The important is that the base product (component) and the decorator implements the same interface, the difference is that the decorator has a reference to the component.

And while the decorator itself can be a component it also can be decorated. And so on, and so on… Let’s take a look at the exemplary diagram: the decorator implements the component’s interface and has a reference to a component (we can say in short: the decorator has a component and is a component).

CODE EXAMPLE
Let’s now move on to the code example. My example will be similar to one presented in the book – orders that can be decorated with discounts, extra costs etc. So let’s start with abstractions.

Abstractions
Our IOrder interface will have its name and cost. Decorator interface will extend IOrder with property of IOrder type with public getter only.

Implementations
Concrete classes will be very simple. Order class will have two automatic properties (with private setters) and a constructor that sets those properties.

Things get a bit more complicated with the decorators. Here I will describe only one example but in the source code linked at the bottom of the page you will find two more (however they are very similar). The most important difference (as indicated already twice in this post ;)) is that the decorator has a reference to IOrder object. It will be set int he constructor. As this decorator’s purpose is to apply discount  to the order we will need another property for that (of type int and it will also be set in the constructor). Now the essence of the pattern. As the decorator itself is of type IOrder we need to implement Cost and Name properties. These properties will call counterparting properties in referenced IOrder object, get their values and modify them appropriately. In this case the cost will be reduced by discount value and the name will be equipped with a suffix informing about the discount. We can build as many decorators as we please, and use them as many as we please.

Usage
To test our orders and their decorators we’re gonna instantiate a pack of orders, decorate them and decorate again. They all will be stored in a list and then we will iterate through the list and print to screen their names and cost.

All works perfectly:

That’s it for today. Next week it will be time for factories. So I hope we see again!

Source code: download txt file

Design Patterns #2: Observer

Dzień dobry!
Continuing on design patterns – it’s time for the Observer. This pattern allows linkage between one observable and many observers that when the observable changes its states the observers are automatically notified and updated. So, the observable has a collection of observers, it performs its actions and when certain defined event happens it notifies its own observers. Let’s take a look at the diagram:


Let’s start with the observers: their interface defines only one method: Update(). That method returns void and can take parameters. In fact parameters are used to notify the actual change and not only the fact that the value has changed. It will be later shown in the example.
Now the observable: it must have possibility to add and remove observers (Register() and Unregister() methods respectively, as an argument they take  object that implements IObserver interface) and to notify its observers about the change. Concrete implementation of the observable also has some sort of observers collection. (This collection is not part of the interface because a) it doesn’t have to be public, b) methods to register and unregister the observers are exposed publicly and that’s enough for the client, it doesn’t have to know how references to the observers are stored. Of course it doesn’t have to be like that. What we’re discussing here is just the pattern and its actual implementation may vary depending on every particular need.) Usual implementation of Notify() is iteration through the observers collection and invoking Update() method on each of them. And that’s it. Let’s go with the example.

EXAMPLE
Example given in the book (previous post explains what book) is a weather station (measures temperature, pressure etc.)  and several types of display (current conditions, stats etc.) I think that’s a really good example but our example will be simpler but similar to some extent. We’re going to build number generator and two types of display.

Interfaces
Have a quick look at the code below:

Hey, where’s Notify() method?! We don’t want that method to be exposed publicly therefore it won’t be here in the interface. As said earlier, the design patterns are not exact implementation nor have strict code structure, they are more of a general ways to achieve some result. But if you hear from another developer that he has used the observer pattern (or any other pattern) you will instantaneously know what to expect.
IObserver interface defines only one method which is Update() that takes one integer parameter which will be passed to our observers.

Concretions – Number Generator

Our number generator will – surprise, surprise – generate random numbers within given range (which is specified by constructor’s parameters). It has list of objects of type IObserver and two methods that allow adding and removing from that list. Method notify() is private as we don’t want to make it possible from the outside of the class to force the observable to notify its observers. This method (as you can read above in this post) simply iterates through observers collection and invoke Update() method on each of them. This method is invoked inside Next() method which generates next random number. Parameter of the Update() method is last generated number.

Concretions – Observers

These two implementations of IObserver using their Display() method print their current readings to console. One of them displays aggregated value of all random number passed from the observable, and the other displays average value. Their Update() are consistent with the interface they implement.

Wiring all together
All the above classes will work together in this small console app.

As you can see once we have an instance of NumberGenerator we can register some observers. Our console app will iterate 10 times and draw 10 random numbers and display readings of our observers.

Self-registration/unregistration
The example above shows basic implementation of the observer pattern. It may be improved by allowing object to self-register/unregister. This can be simply done by storing reference to observable in the observer. In this case observer will need appropriate methods: to register that takes observable as an argument, and to unregister with no arguments. Let’s take a look at its interface:

It extends existing IObserver interface and adds two methods as described earlier. Now, the concretion:

So, it now has a reference to the observer which initially is null. When we want to self-register it to a particular observer we simply invoke SelfRegister() method and pass the observer as an argument. The method will save the reference to the observer and invoke observer’s Register() method with this passed as an argument. SelfUnregister() method performs opposite actions. The code says it all 🙂
Below you will find to txt file with the source code. Thanks for today, and hopefully see you next week. Cheers!

Source code: download txt file

Design Patterns #1: Strategy

Nau mai!
Time for design patterns. Whenever I tried to find out anything about them I encountered this pretty good explanation what are they and why we need them:

Someone has already solved your problems.

‘Head First Design Patterns’ (page 1)

And after Wikipedia:

In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

[source]

In a nutshell: common solutions to common problems. And that should be sufficient to start with first design pattern: Strategy. But, before that quick introduction to this series. It is inspired by Christopher Okhravi and his playlist. I will do basically the same: go through all design patterns in Head First Design Patterns book by Eric Freeman, Elisabeth Freeman, Bert Bates and Kathy Sierra. I have Polish edition but that does not make any difference for you, I will not give any quote in Polish (probably I won’t give any quote at all). To make this series somehow different and not to copy either the book or videos linked above I will use different examples. So, with that being sad we can cut to the chase.

Definition
Strategy defines common abstraction of set of algorithms, encapsulates them and make them reusable and interchangeable in run-time.

How is that achieved:

  1. Define abstract class or interface that has one common method which invocation will perform some action
  2. Define concretions for the above
  3. Add variable of type strategy abstraction to your client class
  4. Add method in your client class which will execute strategy
  5. Add method in your client class that will allow to change strategy

    And that’s basically it. Now, let’s move to example.

    Example
    Example given in book is a duck simulator. It uses different types of duck where actions such as quack or fly are abstracted and encapsulated into strategies. Good example in my opinion. Our example is magic box that consist of an array of 10 integers which can be displayed in console. But the way the numbers are displayed varies depending on enumeration strategy. Let’s start with abstracting the enumeration strategy:

    So, our strategy is used to return string that enumerates all numbers in given array.
    Now, let’s implement different strategies: enumerate as is (without changing the order), bubble sorted and shuffled.

    What could be done better in those three implementations is that part of the code that build output string is common so natural reaction would be to encapsulate it somehow, but please, turn a blind eye for that 🙂
    Next step – writing our MagicBox class which has an array of 10 integer, randomly generated in the constructor, private field of type IEnumerateStrategy accompanied by a method for changing the strategy, and Display() method that writes numbers to the console using the strategy.

    To test the example in application’s Main() method, we will create new MagicBox object and assign new AsIsEnumeratorStrategy, then invoke Display() method, and then assign some other available strategies and again invoke Display() method.

    So, as a result we get number listed using three different strategies. Advantages of using Strategy Pattern is that you can write as many strategies as you want without changing the class that uses them and interchange them during run-time (the definition, right?).So that’s it when it comes to Strategy Pattern. If you’re interested in next pattern (which is going to be the Observer) please come back (probably) next week. Thanks!

    Source code: download zip file

User-defined value type

Hello there!
Something basic today: how to write your own value type. In C# we distinguish two kinds of data type: value type and reference type. The former is a) stored on stack, b) is by default it is passed as an argument by value; the latter is a) stored on heap and only its address is stored on stack, b) is passed as an argument by reference. At this stage the important thing that is needed to know is that point a makes impact on performance [more]; point b makes impact of how data is circulating through methods. If an argument is passed by value only the value will be taken into the method and, we may say, the link between variable name and its value will be gone from method’s point of view, this means that the original variable cannot be modified by the method. If an argument is passed by reference that link will still be valid meaning that whatever changes a method do to the data it will be reflected everywhere that data is used. The code below will make it much clearer:

The output of the above would be:
As you can see modifications to our list of strings which is a reference type have been done to our object, however our integer variable which is a value type have not changed because only its value was passed to the method. That’s the main difference. The good thing to know is that value types can also be passed by reference – to do that we use keyword ref before an argument we want to pass by reference. This keyword must be present both in method signature and in its invocation place.

And the result:
So, that explanation is enough. We know what is the difference between value and reference type and what implication does that difference bring to behaviour of these types. Now, let’s move on to our custom value type. These are basically structs. They (similarly to classes) can consist of fields, properties, methods etc. and struct’s members can be static, but the struct itself cannot be static. Another important feature is that a struct cannon be derived from a class (that’s obvious) or another struct, however they can implement interfaces.

Our value type will store coordinates assuming that point 0,0 is the bottom left corner of our plane – this means that only positive values of component X and component Y can be assigned. This is due to way of how our value type will be assigned:

So, let’s start with required properties for X and Y coordinates, and distance from point 0,0. That’s simple:

Now, time for constructor. What it is actually going to do is decomposition into two coordinate component. It is also going to be private as we won’t be creating variables of this type using the constructor but simply by assigning a double.

This decomposition is achieved by using some of the static methods of Math class [see here].

Now, the fun part: how to make it possible to assign double value to our struct using ‘=’ operator? Simply by defining new implicit conversion operator that will use already defined private constructor to create an instance of our struct.

Next step would be to override three methods: ToString(), GetHashCode() and Equals() methods. A word of explanation here: although a struct is a value type it is derived from ValueType type, which in turn is derived from Object, and despite the fact that it is not necessary to override those three methods we want to be sure that they will act as we intend: ToString() will return X and Y components separated by comma, GetHashCode() will return hash code for double created based on X and Y, and Equals will check if the argument is of our user-defined type and if it does the method will compare X components and Y components:

And now we’re at the point where we could stop. Having the above done is enough to use our struct but we want to override some of the operators to make it easier to use. We will override pair ‘==’ and ‘!=’, and ‘+’ and ‘-‘ operators. For the comparison operators we assume that our structs are equal if both counterparting components are equal, for addition and subtraction we will add or subtract components X and Y:

And that’s it. Our user-defined value type is ready to use. Of course we could override more operators and I guess is-bigger-than and is-lesser-that would be a good idea but it’s easy to do so if you want to extend the struct your good to go. Below you will find complete code for all above and code for unit tests.

Regards, Michał!

Coords
Tests

Inventor API: Custom add-in #3 – Working with the API, implementing the functionality

Hello there!
It’s time for the last part of our small tutorial on writing Inventor add-ins. Today we’ll write the actual implementation of the functionality described in previous post and explain some other small details. So, let’s get to work!

INVENTOR HANDLER

Our main functionality will be performed by a single class – InventorHandler (which will also be abstracted by IInventorHandler interface). It’s going to have only one public method AutoBreak() which will be responsible for applying the break to correct view. Let’s start with constructing it.

Private fields

It consist of three private fields: invInstance which stores reference to current instance of Inventor apllication, settings which stores reference to settings model and comparer which stores reference to IComparer implementation for sorting drawing views descending, area-wise.

This implementation is actually an internal class within our InventorHandler class. We won’t need that anywhere else.
Next, we have static list which contains orientation types which can work with our auto-break. This means that all views which are different orientation will not be take into consideration when executing auto break.

That list contain only perpendicular projections (back, left, right etc.) and the one called kArbitraryViewOrientation. This is the type of all views generated from a base view. This mean that although isometric views are not present this our collection the add-in will break that kind of view if it is created from an existing view.
The last thing is a predicate that is used for removing all views which are orientated differently than types allowed in the collection that we have just explained.

Constructor

The constructor for our InventorHandler class is very simple. It sets invInstance and settings to those given as arguments and instantiates new DrawingViewSizeComparerHelper class.

AutoBreak();

Now, let’s go through our only public method in the class:

It takes current active document in running Inventor application and sets a reference to in in a local variable drawing as a type DrawingDocument. Although property ActiveDocument of invInstance is of Document type (which is more general than DrawingDocument) it is safe to set is as DrawingDocument as our button to execute will be visible only in Drawing ribbon, therefore we’re sure that the active document IS DrawingDocument.
Next, we set another local variable which is of type DrawingView and assign result of getBiggest method executed with argument of drawing.ActiveSheet. This gets currently activated sheet in active document. If it’s null (meaning no drawing views are in the sheet) or it is too small to be broken the add-in will display a message and terminate execution of AutoBreak method. Otherwise, it continues.
Now, it checks if there already is a break applied to the view. If it is, again, it displays appropriate message and terminates.
Next step is to determine start and end points for the break. They are of type Point2d and they are set as local variables inside the method’s body. To give them appropriate values one of two methods is invoked: horizontalPoints or verticalPoints. These methods return boolean whether it is possible to break, and outs break points.
The last step is to apply the break:

It is done by executing Add method of BreakOperations collection in a view. It takes several arguments, as follows:

  • BreakOrientationTypeEnum – break orientation;
  • Point2D – start point;
  • Point2D – end point;
  • BreakStyleEnum – style of break, rectangular or structural;
  • integer – display level, in our case we pass default value of 5;
  • double – gap between left and right part of the view;
  • int – number of symbols, works only for rectangular view;
  • bool – propagate to parent view, defines if the break will be visible in parent view, in our case we pass default value true.

And that’s it. That’s the workflow. Now, as you probably noticed the method described above uses few private methods. To fully comprehend how the add-in works it is necessary to describe them as well.

DrawingView getBiggest(Sheet _sheet)

This method finds the biggest view in the given sheet. All views which are not orientated correctly (remember the list of ViewOrientationTypeEnum?) will be excluded from the selection.

bool isHorizontal(DrawingView _view)

Simply checks if a view is wider than higher and returns true if does.

bool canBeBroken(DrawingView _view, bool _isHorizontal)

This one checks if a view is sufficiently wide for horizontal break, or sufficiently high for vertical break. Minimum height/width is 5 cm plus gap. Remember that the API operates on centimetres expresses in variables of type double.

bool horizontalPoints/verticalPoints(DrawingView _view, int _percentage, out Point2d _start, out Point2d _end)

These two counterparting methods calculate start and end points based on given view and percentage of the view that needs to be removed. Methods return boolean whether a break can be applied and outs the points.

Converters

As some values from settings model are of simple types while methods exposed by the API require some arguments of different enum types there are two converters in the InventorHandler class: one is to convert boolean to BreakOrientationEnum

and the second one is to convert integer to BreakStyleEnum:

And that’s it if it comes to our InventorHandler class. However, to make the add-in actually work there are some changes needed in StandardAddInServer class.

CHANGES IN MAIN ADD-IN CLASS

First of all, we need an instance of InventorHandler. We’ll create a private field for that and initialise it in the constructor:

The last step is to modify action that is fired when the ‘Apply’ button is clicked:

And that’s it. The add-in is now functional. See the demo below:



FINAL REMARKS

There are two things I want to mention at this point. First, is about embedding the stdole assembly. When it’s added to the project and the project is built you will get a warning message:

Although, it does not affect the build you can get rid of these messages by setting Embed Interop Types property of stdole reference to false:

The other things is a word of explanation about NameValueMap interface. It used (amongst other uses) in the API to pass parameters in the events (as in our case events fired by clicking buttons). It works similarly to dictionaries, it stores pairs of name (which are strings) and values (which are of type object). I will not describe it in details (if you need that, simply go to its metadata in Visual Studio), but now you know the main thing – it is name/value pair to pass event parameters.

 

CONCLUSION

A vast portion of things can be manually done in Inventor can be automatised. However, the freedom in modelling that software gives you makes it really difficult to develop universal add-ins that will work always, no matter what you’re modelling. But all of translation, conversion, export things can be easily worked with. I know that there are some add-in that allow to generate models of sprockets, pulleys etc. and that works perfectly.
The hard thing when developing add-in is debugging. Possibilities here are limited because every time you want to debug you need to build your project and run the application, and you won’t get any error messages – either the application will crash, the add-in will be disabled or it won’t be executed.

To make things clear – I have worked with that software as a professional for more that 5 years and I am a big, big fan. I have experience with others systems, but this one seems to be most user-friendly, most of the features works as you would expect and has that professional-feel. But, it’s not a review, so I’ll stop here.
Thanks for your time, I hope that it is in any way useful for you. Good luck!
Michal

GitHub repo: https://github.com/mickaj/AutoBreaker-Inventor

Inventor API – Custom add-in Part #1
Inventor API – Custom add-in Part #2