Inventor API: Custom add-in #2 – Functionality and UI

Hello!
Writing our add-in for Inventor continues! Agenda for today’s post is simple: first I will write a word or two about what is the functionality of the add-in, then I will present the UI and what settings it provides, finally I will present the code.

FUNCTIONALITY

So, what will the add-in do? It allows user to place initial break to the biggest view in the drawing. It is rarely required in real world but the purpose of this demonstration is not to write something widely useful but to present how to write basic add-in for Inventor. Nevertheless, I wouldn’t be surprised if someone finds actual use for it. Feel free to do that 🙂
Inventor allows to set some parameters of the break. First and the most important is orientation. In our case that will be determined not by the user but automatically depending on proportions of the view. The rest will be allowed for customisation. As this is not an Inventor tutorial I am not going to describe in details how to manually add the break and what exactly can be customised. For such pieces of information you can easily find something on YouTube (for example this[1]).

UI PRESENTATION

As our add-in is very simple its UI is equally simple. Combo box for break style, slider for number of symbols (for structural style), text box gap which value will be converted to double and is expressed in centimetres, and slider ratio of how much of the view will be removed (minimum is 10%, maximum is 90%, however if the view is to small the break will not be applied). This small dialog is built in WPF and follows the MVVM pattern.

CODE

As this add-in will use WPF user interface I want it to follow the MVVM pattern, therefore we need model and view-model.

Model
So, let’s start with the model as this one is the simplest:

Style parameter is represented by an integer property backed by a field. The property setter allows only two values: 0 and 1 – that’s how two possible options are represented. Other possibility could be for instance a boolean, however integer is simpler to use with combo box. Similar situation with Symbols where setter allows only 1, 2, or 3 to be assigned; and with Range which can vary from 10 to 90. Gap is auto-property of type double. Class constructor sets initial values which are hard-coded. Natural extension would be to save those values somewhere so they are saved between sessions, however it’n not the point at the minute. The model class SettingsModel is additionally abstracted by ISettingsModel interface.

View-model
The view-model is slightly more complicated, but still quite simple.

First and foremost – it implements INotifyPropertyChanged interface. Fields and properties reflect the model, there are two things that require explanation. Range field/property backing field is of type double which is consistent with its counterpart in the model, while property is of type int which is consistent with slider’s value property. Gap field/property is of type string which will be bound to a textbox. The view-model also contains reference to model which is set via default constructor, constructor also assigns values from the model to respective fields in view-model. There is only one method which is used to save values from view-model to model; and there is only one command which invokes SaveToModel() method and closes settings dialog.

As mentioned SaveCommand is used to save values from view-model to model. It can be executed only when Gap value in view-model can be parsed to doubleExecute(object parameter) method casts parameter to type Window and invokes its Close() method to close the window. This require passing open instance of settings window to command parameter, which will be explained below.

View
Now, the view. There is one trick with WPF windows in Inventor add-in. If you try to add a WPF component to the project you will see that only user control is available, but the problem is that we need a window. A way to tackle that (source[2]) is to add what we can – a user control, and then change it to window. You need to do that in XAML code of the window and in the C# code behind. In XAML change root node to <Window>…</Window>, in C# code modify your class so it inherits from Window not from UserControl. And that’s it.

The only intresting thing in the XAML code above is how current instance of window is passed as command parameter:

The command parameter value is set to binding with RelativeSource set again to RelativeSource in FindAncestor mode with type of Window. This way  the current instance of window will be passed as command parameter which in turn is closed by the command.
Other than that, there are not exceptional things in the XAML, simply built UI with typical binding to view-model.
What you probably noticed, is that data-context is not set, and instance of view-model is not created in XAML, which requires the view-model to have parameter-less constructor, therefore some changes to add-inn StandardAddInServer main class are required.
Another thing worth mentioning is that closing (without saving settings to model) by clicking ‘Cancel’ button is achieved simply by an event assigned to that button, not by a command. This way to do that is much, much simpler than a command and because of the fact that it doesn’t interact with neither model nor view-model it doesn’t break the MVVM pattern.

Updates in StandardAddInServer
First thing that we need to do is to instantiate a model. The main class will be equipped in private field of type ISettingsModel […]

[…] which will be initialised in the class’ constructor.

The last thing we need to do is open the settings window when appropriate button is clicked. To do that we need a method that will be fired when the button is clicked.

The method above creates new settings window, sets it data-context to new instance of SettingsViewModel with current model as constructor’s parameter and finally shows the window as dialog.

And that’s it. Next (and the last) step will be to make ‘Apply!’ button to work. So, don’t forget to check my blog a little bit later.
Thanks, Michal!

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

Sources:
[1] – https://www.youtube.com/watch?v=BzUAb9Qvu98
[2] – http://adndevblog.typepad.com/manufacturing/2015/11/wpf-window-inside-an-inventor-add-in.html

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

WPF: TreeView control

Hello there! It’s been a while since I finished GetNoticed contest and my last post here. I am done with SheetMetalArranger – at least for the minute. But that the contest is done doesn’t mean that I am done with programming. Not at all!

I started new project (maybe one time I will get back to SheetMetalArranger to improve it, but after ten weeks I need something fresh now). It doesn’t matter what the project is about at the minute (I will probably write a post or two about that), the important thing is that I’m continuing with WPF and the time has come to take a closer look at TreeView control.

Basics

TreeView control is used to display hierarchically organised structure. The best example is folder tree, for instance the one you have in Windows Explorer.

Here’s simplest example:

To build hard-coded tree you simply nest one <TreeViewItem> into another and build your structure. Notice that Header property is what is going to be displayed in your application. There are two other properties of TreeViewItem that should be mentioned here: IsExpanded and IsSelected which are pretty much self-explanatory but it is worth to mention them as they are fundamental for controlling behaviour of the control.

Binding

Binding a collection to TreeView can be easily achieved, it is no different as other controls. You simply bind a collection to ItemsSource property. But the tricky thing is that you need to reflect the hierarchy somehow. One way to do that could be binding a collection that contains objects of class TreeViewItem which is equipped in collection Items which contains child objects. Here’s the same example but with the difference that all data is stored in data model:

1) Lets start with the data model: our library node will consist of name, collection of books (stored as strings) and collection of sub-nodes.

2) Our actual data for the purpose of this example will be stored in static class with one static method GetData() that return instance of LibContainer

3) Our view model will consist of observalbe collection of TreeViewItems and in its constructor it will get data from the above static class. Inside the view model there is also one small private method that converts LibContainers to TreeViewItems

4) We set instance of view model and set it as data context. For example as below. Now, after that our tree view can be simplified just to only one line.

Load on-demand

The above example is nice and easy. It gets a bit more complicated when you want to load content of your tree view on-demand when content of your tree is huge and loading all data at once would be lengthy operation – I guess that’s common situation.

To achieve that we need to build custom class that will replace TreeViewItems in collection in our view model. That class must have: 1) collection of child items of the same class, 2) Parent, IsExpanded and IsSelected properties, 3) method to load children, 4) property that defines if the element can be expanded.

Here’s our example build this way:

What’s important in the code above is that Children collection must contain dummy element before actual elements are loaded. This is necessary because it would not be possible to expand the element, therefore it would not be possible to execute method that load further elements.

ViewModel class will now have only collection of TreeElement and will gather data from DataModel in its constructor.

Now, we need to define our TreeView control to display our custom items correctly. This is done by creating local style where we bind IsExpanded and IsSelected properties of TreeViewItem with counterparting properties of our custom TreeElement

And that’s it. This is how I use TreeView control. Possible extension to the above would be to create custom WPF control to handle custom types of tree elements and equip it with dependency property that exposes currently selected item. But that’s easy to do and isn’t in any way specific to TreeView.

So, thanks for today and good luck!

Sources:
WPF 4.5 Księga eksperta. Podręcznikprogramisty WPF 4.5! Adam Nathan (translated by Paweł Gonera, Ireneusz Jakóbik), published by HELION S.A 2005
https://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

 

EratoWPF – Sieve of Eratosthenes (WPF and MVVM)

Hello!
I have just finished another simple app. This time it’s an application to look for prime numbers. The app is again simple but the reason for that is I wanted to make an approach to something new. This time it is MVVM design pattern.
What is MVVM? It is a software design pattern which goal is to separate user interface form application’s logic and data model.
M – model – data source
V – view – user interface
VM – view model – logic and a ‘go-between’ model and view
Use of MVVM pattern allows for a project to be simultaneously developed by a graphic designer and a coder as the UI does not (and should not) require any code-behind. Another advantage is that the whole logic and data-model can be quickly ported to new UI. Microsoft emphasises use of Blend for Visual Studio which is a graphic-design tool for creating (not only, but also) WPF user interfaces to design UIs. In this case I didn’t follow that advice. XAML editor in Visual Studio is sufficient for me.

So, how the separation is achieved? In EratoWPF case, first  I created a model which is PrimeNumbers class in PrimeNumbers.cs file. To be sure that it is working as it should I also created another project called PrimeNumbersSieveTester which is a small console application that tests the class.
Next, I started building the view in XAML with input text boxes and some buttons to run the algorithm or clear inputs.
Finally, I started building the view model. It represents the content of the UI. The view model also privately instantiates the model. The UI will not have access to it.

Binding
To allow the UI use (to display and/or update) properties from view model we use data binding. To achieve that first we need to set data-context for the UI.

The XAML code above will create an object viewModel which is an instance of ViewModel class. The code below will set main grid data-context to viewModel.

Now, to bind a property from viewModel to a control in WPF user interfaces:

The code above binds Text property of a text box to InputRangeStart property in viewModel and IsEnabled to InputsEnabled. Modes specify type of binding. OneWay allows only to dispaly data from viewModelTwoWay allows also to update data in viewModel.
This also requires a view model to implement INotifyPropertChanged. It’s quite simple:

That creates an event handler which is fired every time a property is changed. To set up a property to fire that event it is required to invoke OnPropertyChanged(“PropertyName”); method in a set accessor of this property.

Commands
As it was written earlier in this post, an application designed according to MVVM pattern should not have any code-behind. Therefore, it is required to use commands instead of events.
First, we need to create command class which implements ICommand interface:

That is basic implementation of a command. However, if a command operates on view model instance it is advisable to add private and readonly field for view model and create a constructor that sets it to viewModel defined in XAML.

After that, we need to create an instance of this command in our view model to allow it to be bound to a control in the UI.

Now, to bind the command to a control:

And that’s pretty much it. This is very basic introduction to MVVM, but good enough for a start. There are other aspects of MVVM (such as converters or dependency properties any many many more that I am not aware of at the moment) but I am sure that I’ll come to that as well. As they say: Rome wasn’t build in a day!
Good luck!

Source code: https://github.com/mickaj/EratoWPF
Readme: https://mkajzer.pl/?page_id=200
Installer: https://mkajzer.pl/download/EratoWPF/EratoWPF_installer.zip

Recommended reading (in Polish): “MVVM i XAML w Visual Studio 2015”, Jacek Matulewski, published by Helion, 2016, ISBN: 978-83-283-2867-9
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

Delegates, Lambda expressions, callbacks and events

Shalom!
Since my completion of the course (read here) I have turned my focus onto delegates and events. All in order to fully comprehend the MVVM pattern. This post will be mainly about delegates and events, but I will also write a bit some of the related topics (Lambda expressions, callbacks and Func, Action and Predicate delegates).

Delegates
In short words delegates are types that can hold a reference to methods. Those methods must be consistent with delegate type signature. They can hold a named methods, anonymous methods and Lambda expressions. Interesting feature of a delegate is that its instance can hold references to more than one method which can be added/removed simply by using + or – operator. Here’s an example of delegate signature:

To create an instance of a delegate:

To invoke methods referenced in the delegate simply invoke it exactly the same way as regular methods or use Invoke(); method.

Delegate can hold references to more than one method. These methods will be invoked in the same order as they were added. If a delegate returns a value it will return value from the very last method in its invocation list.


Anonymous methods and Lambda expressions
Anonymous method is a method which is declared and its body is defined when assigning it to a delegate. Lambda expressions (introduced in C# version 3.0) are more or less the same as anonymous methods but with simplified syntax.

Lambda expressions use ‘=>‘ operator. It can be understood as ‘becomes’ or ‘goes to’. In other words what’s before the operator is inputs and what’s after the operator it output. Input and output has to be consistent with delegate type to which you want to assign the expression. If there is only one instruction after the operator and the delegate returns a value it is not necessary to use ‘return‘ keyword.

Func, Action, Predicate
These are ‘built-in’ generic delegate types introduced in C# 3.0. Generic parameters represents type of arguments and type of returned value (if any).

One of the purpose where you can use predicates is filtering a collection. For example, you can use RemoveAll(Predicate<T> match); method to remove from a list all elements that satisfy the condition.

Callbacks
While doing research about delegates it was often claimed that main purpose of delegates is allowing communication between two classes. Original meaning of ‘delegate’ noun is someone who is sent to other party with a message. And this is how delegates should also be comprehended in C# and programming.
Imagine that there is a class with a method that takes a significant amount of time to execute. To keep application responsive it would be worth to have some feedback about the status or progress of this time-costly method. It is possible to achieve via callbacks.
Here’s a Calculation class with a method simulating some lengthy calculations:

This class defines CallBack delegate type which takes one integer argument and doesn’t return any value. This delegate is also an argument in our Process method that want’s to send feedback to another class which is achieved by invoking that argument somewhere in the method.
UI for this example is a WPF window. It consists of a textbox where user gives number of cycles that Process method will run and a button that executes that method. There is also a numeric indicator of current cycle and a progress bar. Those two controls receive feedback from Process method. There is also a text box to witness that the UI is responsive while the Process method is runnind. Here’s XAML code:

Code-behind the main window consists of Click event for a button that starts the process and UpdateUI method.

Process method is started as a new Task to keep the UI responsive. UpdateUI method must have signature consistent with CallBack delegate defined in Calculation class as this method is used as an argument in Process method.

Events
Concept of events enables a programmer to use a kind of notification system between objects. To depicts that I prepared small program that imitates a wallet and adding money to it. Here’s listing of Wallet class:

First of all it has a delegate GotSomeMoney declared that defines event handler signature. Event handler is a method that is executed when an event occurs. It takes two parameters: object sender (which is an object that fires the event) and EventArgs e  (object of an EventArgs class that holds argument that you want to pass with the event).
At the very end of the file above I declared a new class MoneyEventArgs which is derived form EventArgs class. This class has two properties that will be passed with the event.
Having these two parameters in event handler is to follow the .NET guidelines. It is not necessary but if you take a look at all the events for all of the controls (in WinForms and in WPF as well) you’ll see that they follow the same guidelines.
Now, if you analyse setter for Money property in Wallet class you will notice that FireEvent method is executed in some particular circumstances. This method takes one integer argument. Now, if we move on the the code of this method that it creates new instance of MoneyEventArgs class and assign certain values to its properties. Then, it checks if there are any subscriber for the OnGotSomeMoney event and if affirmative it fires the event with this as an object argument and that newly created instance of MoneyEventArgs class.
Now, let’s move to the UI. It has a text box to provide owner’s name and a button that initializes new instance of Wallet class. It also has a counter that displays content of the wallet and buttons that allows a user to add some money. The are disabled until the initialize button is clicked. Here’s XAML code:

This XAML code also defines myWallet instance of Wallet class. It all happens in <Window.Resources>. This instance will be available also in code-behind.
Now, let’s take a look at code-behind:

Code-behind has ThisWallet_OnGotSomeMoney method which signature is consistent with GotSomeMoney delegate in Wallet class. This method will be assigned as a subscriber to OnGotSomeMoney event of thisWallet instance by clicking Initialize button. Note, that this assignment is achieved by using ‘+=’ operator. To avoid clearing all subscribes it is not possible to use ‘=’ operator event. You can only subscribe to event by using ‘+=’ or unsubscribe by using ‘-=’ operator.
ThisWallet_OnGotSomeMoney method takes some values from sender and MoneyEventArgs and creates some strings that will be displayed in a message box when the event occurs.

Understanding all of these concepts required to be quite focused and multiple reading or watching of the sources I had available. If I were to recommend something that helps to understand these aspects of programming here are some links:
Jesse Dietrichson: https://www.youtube.com/channel/UCiA3tURI8dwCOUzCeM90c2g
https://www.youtube.com/watch?v=8e2GEFNctwQ&t=1466s

.NET Interview Preparation Videos
https://www.youtube.com/channel/UCHI5xgQujSyqz_UyKdLFaqw
https://www.youtube.com/watch?v=ifbYA8hyvjc&t=416s

All of the code presented in this post can be found here:
https://github.com/mickaj/DelegatesLambda
Feel free to test it!

That’s it for today. Next, I will post something about interfaces. Hopefully, shortly…
Regards, Michal

RomanDecimalConverter

Greetings,
I have finished another quick project. The plan for this was to introduce myself to WPF and XAML. My general thoughts are that despite that WinForms seems to be easier and quicker way to design a Windows application I find WPF more organised and more controllable that WinForms. I designed all windows for this application using only XAML editor (not the visual one) in Visual Studio. That gives better understanding what is happening with the window.

The application itself is quite simple: it converts Roman numbers to Decimal, and the other way around. Algorithms of conversion are quite simple so I won’t describe them here (they can be found in readme file, or by analysing the code).

That was quite a nice way to leap into WPF. Next week, I’m going to three-day basics of .NET programming course which I hope will give me more insight to WPF and MVVM model (which, I’ve deducted from some of the YouTube lectures about WPF, is essential for writing a well-organised and maintainable applications).

Stay tuned!

ClickOnce installer (*.zip)
Source code (*.zip)
Readme file (*.txt)

Localising your application

Hello!
Some time ago, while working on an abandoned project (which, I have to admit honestly, turned out to be too laborious and complicated for me at that point) I had worked out a method to localise the program using XML files. That worked perfectly okay but only recently I have that there are way easiest methods to achieve that.
Let’s start with XML method. Available languages have a unique file with all strings stored in. The file is organised as follows:

As you can see each window has a specific section in XML file, and only this section will be loaded when a window is displayed. Every window has a method which loads all related strings:

Drawbacks of this method are clearly visible: you have to write a method which will load all strings from XML file. And you have to be extremely careful not to omit any text you want to display. It worked but not effectively at all.

There is other much simpler method which I found at AltControlDelete.pl. It uses resource files and System.Globalization. General idea is that you create individual *.resx file for each language: Lang.resx for default (English) language and Lang.xx-XX.resx, where xx-XX is the name of a culture (for instance, pl-PL for Polish). What’s important is that access modifier for those files must be set as public as shown below.

lang_resx
These files must be stored in one folder (let say “Languages”). Now, you need to include them in your source code and you’re ready to use these strings in your code:

To use it with XAML you need to add appropriate namespace to Window element in XAML file:

Now, to switch between languages you need to change Culture in your process:

Of course, you need to build your app in a way that user has the possibility to switch between languages as he intends.

That’s about it. The method with *.resx files is much simpler and most of all quicker and to some point less prone to omissions and mistakes. Of course, there are other methods (for instance, Mulitilingual app toolkit  from Microsoft) but this one seems to me that is easy enough and does not require any add-on or third-party software other than Visual Studio).

This post is based on articles available at www.altcontroldelete.pl by Jerzy Piechowiak.

WPF TUTORIAL – APLIKACJE WIELOJĘZYCZNE
TWORZENIE APLIKACJI WIELOJĘZYCZNYCH Z C# I ASP.NET W VISUAL STUDIO

 

MakeNoMistakes 1.1

Greetings!

I have just finished the application introduced in previous post. To remind what the application is about: it is an implementation of a classic game Minesweeper. My addition to the idea is that once you click on a mine you have one chance to disarm the mine by solving small equation (addition or subtraction).

Here are links to ClickOnce installer and source code. As usual the code was written in MS Visual Studio.

ClickOnce installer (*.ZIP)
Source code (*.ZIP)

One note before you try it out – don’t mind the graphics. I am hopeless at drawings.

Enjoy!

MakeNoMistakes – my implementation of a classic

Hello All,
It has been a while since my last post in which I announced ‘another small app’. It is now time to publish its first version. Generally, it is another version of small game which is distributed with MS Windows and it is about finding mines. The app I have written is slightly different. It gives a player a possibility to disarm a mine if it is found by right clicking. In classic minesweeper it is possible to click with both mouse buttons to uncover all adjacent tiles. In my app it can be done by hovering a tile for a short moment. In this case uncovering the mine will result in an explosion and therefore the game ends.
This is the first version. It is not finished, but I would say it is 95% complete. What is missing is possibility to play a game on custom tile-board and a hall of fame (and nice graphics, but I am not an artist at all). Right now I am publishing only an EXE file (in a ZIP archive). Source code will be published when the application is completed.
Thanks, Michal

MakeNoMistakes (*.ZIP)