Class diagram: a easy way to understand code

Scope

This article has the goal to show how to create a class diagram and how we can use it to understand code.

Introduction

According to MSDN, a “Class diagrams help you understand the class structure of projects others have written (or that you wrote a long time ago). You can use them to customize, share and present project information with others.”

In this article we will use the sample Field Engineer from MSDN Samples which is an Azure Mobile Service sample, but where is not required to know about Azure Mobile Service and we will not talk about it. We only focus in the model classes as a sample.

Description

After open the Field Engineer Sample in Visual Studio, we will find a folder with the name “Model”, here are an image with it

model folderIn this case we do not have so many classes, that can be great because can be easy to understand the model. Maybe a lot of developers will start open all files to see the code, but why not create a class diagram?

Let’s create first a class diagram for see an overview about the model.

Creating a class diagram

Selecting the Model folder and opening the context menu, click in “Add” and then “Class Diagram” as following
add class diagram

then define the name of the class diagram as following

class diagram name
clicking in “OK” the diagram file will be added to the project and will be opened, as following
class diagram in projectnow we can select all files in model folder and drag and drop it to the class designer area and the result will be
drag and drop result

and now we should move each shape and should expand each one for see details.

Expanding classes

For expand click in the arrow in top, as following
expand shape

and the result will be
shape expanded

The class details

If we open the context menu under the shape we can select the “Class Details”
select class details

the result will be something like it
class details

With this user interface is possible to see more details about the class and is possible to create/edit/delete/hide each property, method, event… without coding.

Understanding different icons

After expand all shapes we will find that some shapes show the Fields, Properties, and Methods (and can show events, nested classes…).

Let’s see the case of the MobileServiceContext

MobileServiceContext shape

Looking to the image we can conclude

  • The connectionStringName is private and is a const field;
  • All properties are public;
  • The method MobileServiceContext that is the constructor is public and the method OnModelCreating in private;

How is possible to conclude it?

Each icon means something, for example the symbol * in each item means it is private. The best way to understand the differences between each icon is to create a sample with each possible case.

Let’s see a fake class created for this purpose

class details
When we select the shape and open the context menu we have options that allow to show/hide different details.

Let’s see the case for show the base class.

Show Base Class

base class

After it and after expand the shape for MyBaseClass we will have something like it

diagram

In this moment, there are one point that can be important to defined, to show the diagram what is the most important information that should show in the diagram?

It depend what each developer likes or wants to see, but in general we can defined as a pattern, we should show only public properties, methods and events and hide all others (in some cases can be useful to show all defined as internal or protected).

Hide compartment

Selecting the shape and the item we want to hide is possible using the context menu do this, as following

hide itemsThe option “Show all members” will revert it, but in some cases is better to use the Class Details for revert it, because we can have others items hidden that we want to keep hidden.

Each shape that hidden some item will show an icon that means it, here are an example

hide symbol

Apply associations

Returning to the Field Engineer Sample and choosing the class JobHistory, Job and Customer we will find that each one has a relationship with each others, let’s highlight it using a  red and orange rectangle, as following

related classes

Let’s see how we can show the association for properties and for collection.

Show as Association

For properties which the data type is another class we can select the property in shape and in context menu should select the option “Show as Association” as following

show as associationShow as a Collection Association
and for properties that are collections/lists we can choose the option “Show as Collection Association” as following

show as collection association

and the result will be something like

associations

The number of arrows will define it is a property or a collections, but using a good name can be enough to see the differences.

Show as property

By selecting in the arrow is possible to revert it, using the option “Show as property”.

Show as property

The final class diagram

After define all arrows for all association and organizing the shapes we will have something as following

final diagram

For this diagram, we can understand that the model has five classes and the MobileServiceContext is defined by these classes. Is clear the relationship between the classes which allow to conclude (for example)

  •  A job know its job histories and each job history refers to a job;
  • A job knows which customer is associated and a customer can have more than one job;

A similar conclusion can be done for Equipment and Equipment Specifications.

Note: is possible to create arrows for the MobileServiceContext’s properties but it only will do some noise and is not important in this case to see these associations.

Each developer should customize the class diagram and there are no fixed rules for it. With this kind of diagram is very simple to understand the model and in some cases found mistakes like wrong names, wrong relationships or even missed features.

Conclusion

In conclusion, we can conclude that the class diagram is a very useful for understand the code made by us or by others, the relationship between the classes and an easy way to find mistakes. In some cases, with class diagram is possible to have a big picture about the application without see one line of code.

 

See also

Resources for client apps that uses the Azure Mobile Services

In the last months, I have been working with Azure Mobile Services, where my focus was  create .Net BackEnd for IOS and Android Developers. For different reason I searched for the right article for each subject or problem and saved it as a curation for share and use later.

Here are the resources focused in each platform

Note: in some cases is need to select if we want a .Net or a JS BackEnd.

and is possible to use the start point Azure Mobile Services for Client Apps which contains all references defined above.

 

Enjoy it! :)

 

Curah! 2014 award – TOP 10 Featured Curators

Last week, was published the article

2014 Curah! Awards + the Week of Curah! Awards (1 Year Celebration!)

And couldn´t be more happy, because I won the Curah! 2014 – TOP 10 Featured Curators badge which represent the award for the curators with most featured curations ( in this case the top 10!).

Here is my new badge
badge

[PT] PGGD25 – 25º Portugal Girl Geek Dinner – Lisboa

Estamos de regresso a Lisboa e contamos novamente com o apoio da Microsoft!

O #PGGD25 vai realizar-se no próximo dia 1 de Dezembro, a partir das 18:30, nas instalações da Microsoft (no Parque Expo). A participação é gratuita!
Agenda:

18:30 Registo / Snacks & Drinks

19:00 Joana Gomes – Marketing para uma audiência técnica

20:00 Sara Silva – Como criar aplicações Windows usando o Windows AppStudio

Nesta sessão a Sara irá apresentar o Windows AppStudio e como podemos criar as nossas próprias aplicações para Windows Phone e Windows 8.1 (Windows Store apps). Será apresentado um exemplo de como integrar a Cortana numa aplicação de Windows Phone (gerada pelo Windows AppStudio) e será exemplificado como poderemos interagir com a Cortana, através do Windows Phone ou até mesmo da Microsoft Band.

21:00 Encerramento

Apoios: Microsoft Portugal

Nota: Homens podem também participar desde que sejam acompanhantes de uma geek girl.

 

Sobre os Girl Geek Dinners…

Os Girl Geek Dinners nasceram em Londres há 7 anos. Este conceito reside em organizar eventos temáticos para mulheres apaixonadas por tecnologia, sejam elas, programadoras, investigadoras, empreendedoras, designers ou simplesmente interessadas por tópicos relacionados com tecnologia.

A ideia por detrás destes jantares é simples: num ambiente relaxado e informal proporcionar um ambiente para networking e ao mesmo tempo ouvir uma ou duas apresentações dedicadas a um tema tecnológico ou de negócio. Mais do que isso é também o espaço ideal para dar a conhecer o que se anda a fazer no mundo da tecnologia e new media em Portugal.

Website | Facebook | Twitter | hashtag oficial: #PGGD25

Tem dúvidas sobre #PGGD25 – 25º Portugal Girl Geek Dinner – Lisboa?Contacte Portugal Girl Geek Dinners

Survey about Android development in Visual Studio

The Visual Studio team would like to thank you for helping us understand more about Android development and debugging.   We want to hear about the tools and technologies you are using (as either a hobbyist or fulltime) for Android development.  We appreciate your time helping us shed some light on this area.

The information you provide is entirely voluntary.  By filling out and returning this survey, you agree that we can use, disclose, reproduce, or otherwise distribute your feedback at the aggregated level. Your personal information will remain confidential. Please check http://privacy.microsoft.com/en-us/default.aspx for Microsoft Privacy Statements.

 

If you have any questions about participating, please feel free to contact vsdr@microsoft.com.

 continue…

Some news released during the Connet() event

Today started the first day of the Connect(); Microsoft Visual Studio vNext & Azure, and was released some article that we should read!
Here are

[C#] File exporter for IEnumerable of T

Scope

This article has the goal to show a solution for have a file exporter based in a list of items but not matter which type.

Introduction

Sometime ago was published the sample Export To CSV for Windows Store apps, this solution is generic, is dynamic because uses reflection and It allow to export a list of items to a csv file. In Windows Store apps uses Windows Runtime and reflection is a bit different from reflection in WPF, Asp.Net, …

In this sample ww will create the sample for a common .Net project.

Description

For help in the sample, let’s create a specific class Person.

    /// 
    /// Define the Person.
    /// 
    public class Person
    {
        /// 
        /// Gets or sets the name.
        /// 
        /// The name.
        public string Name { get; set; }

        /// 
        /// Gets or sets the age.
        /// 
        /// The age.
        public int Age { get; set; }

        /// 
        /// Gets or sets the birthday.
        /// 
        /// The birthday.
        public DateTime Birthday { get; set; }

        /// 
        /// Gets or sets the country.
        /// 
        /// The country.
        public string Country { get; set; }
    }

in class diagram we will have

person
After it, we will create the Export class that will have a generic method, that uses a generic type T. Something like as following

 

    /// 
    /// Define the Export File.
    /// 
    public static class Export
    {
        /// 
        /// Exporters the list of items that can include the specified include header line.
        /// 
        /// <typeparam name="T">The generic type.
        ///If set totrue [include header line].
        ///The separator.
        ///The items.
        /// The content file.
        public static string Exporter(bool includeHeaderLine, string separator, IEnumerable items) where T : class
        {
            var sb = new StringBuilder();

            // Get properties using reflection. 
            var properties = typeof(T).GetProperties();

            if (includeHeaderLine)
            {
                // add header line
                foreach (var property in properties)
                {
                    sb.Append(property.Name).Append(separator);
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            // add value for each property. 
            foreach (T item in items)
            {
                foreach (var property in properties)
                {
                    sb.Append(MakeValueFriendly(property.GetValue(item, null))).Append(separator);
                }
                sb.Remove(sb.Length - 1, 1).AppendLine();
            }

            return sb.ToString();
        }

        /// 
        /// Makes the value friendly.
        /// 
        ///The value.
        /// The string converted.
        private static string MakeValueFriendly(object value)
        {
            if (value == null)
            {
                return string.Empty;
            }

            if (value is DateTime)
            {
                if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
                {
                    return ((DateTime)value).ToString("yyyy-MM-dd");
                }
                return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            var output = value.ToString();

            if (output.Contains(",") || output.Contains("\""))
            {
                output = '"' + output.Replace("\"", "\"\"") + '"';
            }

            return output;
        } 
    }

The method Exporter will allow to include a header with the properties name and allow to define the separador between each field value. It is very interesting because I can use the ListSeparator ( , or  ; ), |, + or other we define.

The method MakeValueFriendly is only useful for format specific type like DateTime.

Now we can create a list of person and write it to a file, let’s see how!

    /// 
    /// Define the Program.
    /// 
    public class Program
    {
        /// 
        /// Defines the entry point of the application.
        /// 
        /// args">The arguments.
        static void Main(string[] args)
        {
            var people = GetPeople();
            var basePath = Directory.GetCurrentDirectory();

            var fullPath = Path.Combine(basePath, "mycsvfile_includeHeader.csv");

            // to cvs file
            File.WriteAllText(fullPath, Export.Exporter(true, System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator, people));

            fullPath = Path.Combine(basePath, "myfile_includeHeader.txt");

            // to a txt file
            File.WriteAllText(fullPath, Export.Exporter(true, "+", people));


            fullPath = Path.Combine(basePath, "mycsvfile.csv");

            // to cvs file
            File.WriteAllText(fullPath, Export.Exporter(true, System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator, people));

            fullPath = Path.Combine(basePath, "myfile.txt");

            // to a txt file
            File.WriteAllText(fullPath, Export.Exporter(true, "|", people));
        }

        /// 
        /// Gets the people.
        /// 
        /// The IEnumerable.
        private static IEnumerable GetPeople()
        {
            return new List
            {
                new Person { Name = "Mary", Age = 22, Birthday = new DateTime(1992, 03, 24), Country = "Ireland" },
                new Person { Name = "Peter", Age = 10, Birthday = new DateTime(2004, 01, 05), Country = "Portugal" },
                new Person { Name = "Anne", Age = 50, Birthday = new DateTime(1964, 11, 03), Country = "Spain" }
            };
        }
    }

In the sample provided, we get the people and then wrote it in a CSV file and a TXT file, where we selected the both cases (with header and without).

The ouput

Running the console application we will get the output

folder

The CSV file with header

The CSV file without header

The txt file with header

The CSV file without header

Source Code

The source code can be found in MSDN Samples.

[Telerik] AutoCompleteBox for Universal apps

Scope

This article has the goal to show how to use the AutoCompleteBox for Universal Apps, from Telerik.

Introduction

Some time ago Telerik published the UI For Windows Universal as a Beta version, which can be download in Telerik WebSite.

telerik

For now is only available the following controls:

In this article we will focus in the AutoCompleteBox. Let’s see how we can use it!

Description

Before download and install UI For Windows Universal, we should create a Blank Universal App, then we need to add the reference for this. The following image show how to add it:
add reference

and thensdk extension

Now we can start use the Telerik controls, but before we can move MainWindow.xaml and App.xaml for the shared project for reuse the code.

Note: In this article we will use MVVMLight, see more about here.

In MainWindow we can define the UI  as following

<Page
    x:Class="MyTelerikSamples.AutoCompleteBoxSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:input="using:Telerik.Universal.UI.Xaml.Controls.Input"
    mc:Ignorable="d"
    DataContext="{Binding Main, Source={StaticResource Locator}}"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="{StaticResource HeaderWidth}"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="{StaticResource HeaderHeigth}"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" Style="{StaticResource HeaderTextBlockStyle}" Grid.ColumnSpan="2">RadAutoCompleteBox Sample</TextBlock>
        <StackPanel Margin="20,10,0,0" Orientation="Vertical"  Grid.Row="1" Grid.Column="1">
            <TextBlock  FontSize="20">Insert some text:</TextBlock>
            <input:RadAutoCompleteBox Margin="0,20,0,0"
                     FilterMode="Contains" IsTextMatchHighlightEnabled="True"
                     Text="{Binding Value, Mode=TwoWay}" 
                     FilterComparisonMode="CurrentCultureIgnoreCase"
                     ItemsSource="{Binding Suggestions}" AutosuggestFirstItem="False"
                     Width="200" HorizontalAlignment="Left">
                <input:RadAutoCompleteBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"
                               input:RadAutoCompleteBox.IsTextMatchHighlightEnabled="True">
                          <input:RadAutoCompleteBox.TextMatchHighlightStyle>
                              <input:HighlightStyle Foreground="DeepPink" FontSize="21"/>
                          </input:RadAutoCompleteBox.TextMatchHighlightStyle>
                        </TextBlock>
                    </DataTemplate>
                </input:RadAutoCompleteBox.ItemTemplate>
            </input:RadAutoCompleteBox>
        </StackPanel>
    </Grid>
</Page>

In AutoCompleteBox we defined a binding for the Text, which define the text string we will write in the control and we defined the ItemsSource which are the suggestion we will provide to the control, with this each time we start to write a word the control will try to find available words that match with the user input.

The DataTemplate was defined for allow to highlight the matched chars when we insert the text, in this case will be highlight by Pink color.

The MainViewModel can be defined as following

 public class MainViewModel : ViewModelBase
    {
        private string _value;

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>
        /// The value.
        /// </value>
        public string Value
        {
            get { return _value; }
            set { Set(() => Value, ref _value, value); }
        }

        /// <summary>
        /// Gets the suggestions.
        /// </summary>
        /// <value>The suggestions.</value>
        public IEnumerable<string> Suggestions
        {
            get
            {
                return new List<string>
                {
                     "Apple",
                     "Babaco",
                     "Bacupari",
                     "Bacuri",
                     "Black cherry",
                     "Pineapples",
                     "Orange",
                     "Tomato",
                };
            }
        }
    }

After it we can run the app for test if the behavior do what we want, but before we should change the style for the selected item, because it will show the default colors and for the highlight was choosen Pink. For it, create a dictionary for add the resource we want to override

    
    <SolidColorBrush x:Key="TelerikAutoCompleteBoxSelectorSelectedItemBackgroundBrush" Color="DeepPink"/>
    <SolidColorBrush x:Key="TelerikAutoCompleteBoxFocusedForegroundBrush" Color="White"/>

then in App.xaml add the resources and the themes, as following

<Application
    x:Class="MyTelerikSamples.AutoCompleteBoxSample.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewModel="using:MyTelerikSamples.AutoCompleteBoxSample.ViewModel"
    xmlns:controls="using:Telerik.Universal.UI.Xaml.Controls">
    <Application.Resources>
        <ResourceDictionary>
            <viewModel:ViewModelLocator x:Key="Locator"/>
            <controls:UserThemeResources x:Key="ThemeResource" 
                                         DarkResourcesPath="ms-appx:///Styles/TelerikResources.xaml"
                                         LightResourcesPath="ms-appx:///Styles/TelerikResources.xaml"/>
            <ResourceDictionary.ThemeDictionaries>
                <ResourceDictionary x:Key="Default">
                    <ResourceDictionary.MergedDictionaries>
                        <!-- your namespace is "Telerik.Universal.UI.Xaml.Input" -->
                        <ResourceDictionary Source="ms-appx:///Telerik.Universal.UI.Xaml.Input/Themes/ThemeResourcesDark.xaml"/>
                        <ResourceDictionary Source="{CustomResource DarkResourcesPath}"/>
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
                <ResourceDictionary x:Key="Light">
                    <ResourceDictionary.MergedDictionaries>
                        <ResourceDictionary Source="ms-appx:///Telerik.Universal.UI.Xaml.Input/Themes/ThemeResourcesLight.xaml"/>
                        <ResourceDictionary Source="{CustomResource LightResourcesPath}"/>
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
            </ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Style/Definition.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Running the app

When we run the app, we will get

sample

sample

sample

Source Code

The source code is available in github.

See Also

Telerik UI for Windows 8 XAML Documentation – Telerik Named Brushes

Telerik UI for Windows 8 XAML Documentation – Resolving Telerik named resources

Next stop Seatle…. I am going to Microsoft MVP Global Summit 2014

seatle

Next week will be Microsoft MVP Global Summit 2014 and for the 2nd time I will be there!

I will stay in Bellevue from Friday to Tuesday then I will move to Seatle for 2 days as a tourist :)

Want to know more about this event? See the following article

MVP Global Summit Home Page
What is MVP Global Summit?

[Survey] Windows Phone and Windows Store Dev Experience – 2014

As we continue to improve the Windows developer experience, the Windows Apps teams need your help.

5-10 minutes of your time can greatly help the team better understand how the WPDev community is using the Windows and Windows Phone platforms and tools. Your answers and insights will help determine what developer resources are as we continuously improve the SDK(s) and how we support the community’s needs. Additionally, the team can (and will) share top-level results from your survey responses back out to the community.

This survey is designed to take 8 minutes – depending on how much deep feedback you care to share, your mileage may vary.

Windows Developer Survey Privacy Statement (last updated: November-14-2011)
Microsoft is committed to protecting your privacy. Your responses to this survey will not be linked to any contact information previously collected by Microsoft. Your answers will be reported in aggregate with those of other respondents. This survey collects information about your response such as the Internet Protocol (IP) address through which you access the Internet and the date and time you access the survey. This information is used to help improve the survey, analyze trends, and administer the survey. Please note that this privacy statement applies only to this survey. It does not apply to other online or offline Microsoft sites, surveys, products or services.

Please contact cliff.simpkins@microsoft.com if you have any questions concerning collection and use of your personal information.