Sina Iravanian

I blog about software development

How to Reduce the Pain of Working With TFS Using Git TFS

| Comments

Git TFS is a program that extends git commands to talk to a TFS remote repository (instead of a git repository). It creates a real git repository and replays the TFS history on top of it. It can be treated as a real git repository except for when it comes to cloning and syncing. In spite of that it still makes a programmer’s life much easier.

The best starting point is the project’s ReadMe file on GitHub. Here’s a brief overview of basic commands I needed to use.

To install via chocolatey, run:

1
choco install gittfs

Make sure to add gittfs.exe to path. Chocolatey installed mine in “C:\Tools\Gittfs”.

Cloning from TFS is a bit different from that of Git:

1
git tfs clone http://url-to-tfs:8080/tfs/DefaultCollection $/ProjectName

It will create an empty git repository and then replays the TFS repository on top preserving all the history. If the TFS repository is too big there are some switches available to the git tfs clone command that allows you to quickly clone the latest or a specific revision from the history. For more information, see the documentation for quick-clone.

After cloning, it has created a real git repository to which you can make as many local commits as you like. To push your local commits (or check-in in TFS terminology) you need to run the following command:

1
git tfs rcheckin

The rcheckin command will preserve all outstanding local commits and checks them in one by one to the remote TFS repository. Note that git push doesn’t work here as there’s no standard git remote being tracked.

There are other alternatives to rcheckin, such as git tfs checkin -m "message" which squashes your local commits into one using the specified message, or git tfs checkintool which opens up the TFS tools checkin window to perform the check-in. My preference is rcheckin because it keeps me mindful of my local commits, and abstracts TFS away better than others.

To update local repository with remote changes made in TFS default branch, you can pull and rebase, which is my preference:

1
git tfs pull --rebase

Pretty much like git, it pulls down outstanding remote commits and then replays local commits on top of it avoiding the need for an extra merge commit. Alternatively you can also pull and merge:

1
git tfs pull

which may end up creating a merge commit on top of your local changes (unless it can fast-forward). Have a look at documentations for git tfs pull to learn more about pulling from branches other than default.

As you can see when it comes to cloning and syncing, the commands are different from those of standard git. However the fact that you can easily modify the files you need to modify, have a much better diff status of what has been changed before every commit, and possibility of using your git client and tools that you like are what makes life easier with Git TFS.

Mock Entity Framework DbSet With NSubstitute

| Comments

The source code for this post is on GitHub.

When it comes to mocking a DbSet to test various read and write operations things may get a little bit tricky. Mocking a DbSet for a write operation (Add, Update, or Remove) is quite straightforward. But testing a synchronous read operation requires mocking the whole IQueryable interface. Even more trickier than that is testing an asynchronous read operation which requires mocking an IDbAsyncQueryProvider interface. Here is a very good article that demonstrates how to work around these difficulties using Moq. This blog post shows how to achieve the same thing using NSubstitute.

Mocking a DbSet for a write operation is quite straightforward:

1
2
3
4
5
6
7
8
9
10
11
var mockSet = Substitute.For<DbSet<Person>>();
var mockContext = Substitute.For<IPeopleDbContext>();
mockContext.People.Returns(mockSet);
var service = new PeopleService(mockContext);

// Act
service.AddPersonAsync(new Person { FirstName = "John", LastName = "Doe" });

// Assert
mockSet.Received(1).Add(Arg.Any<Person>());
mockContext.Received(1).SaveChangesAsync();

As seen above mocking the DbSet is as easy as one single call to Substitute.For<DbSet<T>>().

However mocking a DbSet for a synchronous read operation needs a little bit more work. It needs to mock the whole IQueryable interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var data = new List<Person>
{
    new Person { Id = 1, FirstName = "BBB" },
    new Person { Id = 2, FirstName = "ZZZ" },
    new Person { Id = 3, FirstName = "AAA" },
}.AsQueryable();

// create a mock DbSet exposing both DbSet and IQueryable interfaces for setup
var mockSet = Substitute.For<DbSet<Person>, IQueryable<Person>>();

// setup all IQueryable methods using what you have from "data"
((IQueryable<Person>)mockSet).Provider.Returns(data.Provider);
((IQueryable<Person>)mockSet).Expression.Returns(data.Expression);
((IQueryable<Person>)mockSet).ElementType.Returns(data.ElementType);
((IQueryable<Person>)mockSet).GetEnumerator().Returns(data.GetEnumerator());

// do the wiring between DbContext and DbSet
var mockContext = Substitute.For<IPeopleDbContext>();
mockContext.People.Returns(mockSet);
var service = new PeopleService(mockContext);

// Act
var people = service.GetAllPeople();

// Assert
Assert.That(people.Length, Is.EqualTo(3));
Assert.That(people[0].FirstName, Is.EqualTo("BBB"));
Assert.That(people[1].FirstName, Is.EqualTo("ZZZ"));
Assert.That(people[2].FirstName, Is.EqualTo("AAA"));

Mocking a DbSet for an asynchronous read operation requires much more work and a bunch of extra classes. This article lists the required extra classes. To name add TestDbAsyncEnumerable, TestDbAsyncEnumerator, and TestDbAsyncQueryProvider classes to your test project. This is how you’d be able to mock DbSet for asynchronous read operations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var data = new List<Person>
{
    new Person { Id = 1, FirstName = "BBB" },
    new Person { Id = 2, FirstName = "ZZZ" },
    new Person { Id = 3, FirstName = "AAA" },
}.AsQueryable();

// create a mock DbSet exposing both DbSet, IQueryable, and IDbAsyncEnumerable interfaces for setup
var mockSet = Substitute.For<DbSet<Person>, IQueryable<Person>, IDbAsyncEnumerable<Person>>();

// setup all IQueryable and IDbAsyncEnumerable methods using what you have from "data"
// the setup below is a bit different from the test above
((IDbAsyncEnumerable<Person>)mockSet).GetAsyncEnumerator()
    .Returns(new TestDbAsyncEnumerator<Person>(data.GetEnumerator()));
((IQueryable<Person>)mockSet).Provider.Returns(new TestDbAsyncQueryProvider<Person>(data.Provider));
((IQueryable<Person>)mockSet).Expression.Returns(data.Expression);
((IQueryable<Person>)mockSet).ElementType.Returns(data.ElementType);
((IQueryable<Person>)mockSet).GetEnumerator().Returns(data.GetEnumerator());

// do the wiring between DbContext and DbSet
var mockContext = Substitute.For<IPeopleDbContext>();
mockContext.People.Returns(mockSet);
var service = new PeopleService(mockContext);

// Act
var people = await service.GetAllPeopleAsync();

// Assert
Assert.That(people.Length, Is.EqualTo(3));

The amount of code per unit test seems a little bit too much. So I created a utility method that creates the mock DbSet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static class NSubstituteUtils
{
    public static DbSet<T> CreateMockDbSet<T>(IEnumerable<T> data = null)
        where T: class
    {
        var mockSet = Substitute.For<DbSet<T>, IQueryable<T>, IDbAsyncEnumerable<T>>();

        if (data != null)
        {
            var queryable = data.AsQueryable();

            // setup all IQueryable and IDbAsyncEnumerable methods using what you have from "data"
            // the setup below is a bit different from the test above
            ((IDbAsyncEnumerable<T>) mockSet).GetAsyncEnumerator()
                .Returns(new TestDbAsyncEnumerator<T>(queryable.GetEnumerator()));
            ((IQueryable<T>) mockSet).Provider.Returns(new TestDbAsyncQueryProvider<T>(queryable.Provider));
            ((IQueryable<T>) mockSet).Expression.Returns(queryable.Expression);
            ((IQueryable<T>) mockSet).ElementType.Returns(queryable.ElementType);
            ((IQueryable<T>) mockSet).GetEnumerator().Returns(queryable.GetEnumerator());
        }

        return mockSet;
    }
}

Exploiting this, the unit test code would become shorter and more readable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var data = new List<Person>
{
    new Person { Id = 1, FirstName = "BBB" },
    new Person { Id = 2, FirstName = "ZZZ" },
    new Person { Id = 3, FirstName = "AAA" },
};

var mockSet = NSubstituteUtils.CreateMockDbSet(data);
var mockContext = Substitute.For<IPeopleDbContext>();
mockContext.People.Returns(mockSet);
var service = new PeopleService(mockContext);

// Act
var secondPerson = await service.GetPersonAsync(2);

// Assert
Assert.That(secondPerson.Id, Is.EqualTo(2));

The source code for this post is accessible from here.

PowerShell: The Switch Data-type

| Comments

The switch data type is used to control whether a switch (as in arguments or options passed to a function or command) is provided for the function/command or not. Suppose that there is a function called Switch-Demo that can accept -Force and -Quiet switches. These switches just work as toggles. What we care about them is whether they exist or not. There are no pieces of data accompanying them. The PowerShell switch data-type suits this purpose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Switch-Demo {
    param(
        [switch]$Force,
        [switch]$Quiet
    )

    if($Force.IsPresent) {
        Write-Host "Forcefully doing the task"
    } else {
        Write-Host "Force is NOT present"
    }

    if($Quiet.IsPresent) {
        Write-Host "Quietly doing the task"
    } else {
        Write-Host "Quiet is NOT present"
    }
}

# invocation:
Switch-Demo -Quiet

In the invocation of the above example, the Quiet switch is present while the Force switch is not.

As shown above, the .IsPresent property of the switch variable can be used to check whether the particular switch has been passed to the function/command.

Default values for the parameters of type switch can be specified by Boolean values. To make a switch present by default the [switch]::Present constant can also be used, which is equivalent to $true. As of now I’m not aware of any [switch]:: constants that is equivalent to $false. Example:

1
2
3
4
5
6
7
8
9
function Switch-Demo {
    param(
        [switch]$Force=[switch]::Present,
        [switch]$Quiet=$false,
        [switch]$WhatIf=$true
    )

    # ...
}

This means that the invoker does not need to specify -Force switch (it is by default considered to be provided). What if the invoker doesn’t like the -Force switch to be present? To override that the invoker can specify Boolean constants as values for the switch:

1
Switch-Demo -Force:$false

I personally don’t find this way of overriding switch values quite intuitive. I’d rather name switch variables in a way that their default value is $false, or when not possible provide another switch with a negative name compared to the other one that overrides its functionality. Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function Switch-Demo {
    param(
        [switch]$Quiet=[switch]::Present,
        [switch]$Verbose
    )

    # Override the values
    if($Verbose.IsPresent){
        $Quiet = $false;
    }

    # Check the values
    if($Quiet.IsPresent){
        Write-Host "Quietly doing the job."
    } else {
        Write-Host "Verbosely doing the job."
    }
}

# invocations:
Switch-Demo -Quiet
Switch-Demo -Verbose

Handy Extensions for INotifyPropertyChanged

| Comments

I recently created a library that contains some handy extensions for INotifyPropertyChanged interface (aka INPC). To start using the library, add the following to the top of your C# code:

1
using NotifyPropertyChangedExtensions;

How to easily raise INPC in a refactor friendly way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyClass : INotifyPropertyChanged
{
    private int _number;

    public int Number
    {
        get { return _number; }
        set
        {
            if(_number != value)
            {
                _number = value;
                this.RaisePropertyChanged(() => Number);
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

How to easily handle (listen to) INPC in a refactor friendly way

1
2
3
4
5
6
MyClass myObject = ...;

myObject.HandleOnPropertyChanged(src => src.Number, sender =>
    {
        Console.WriteLine("Number changed to {0}", sender.Number);
    });

How to do one-way binding from a class that implements INPC

1
2
3
4
5
6
7
var source = new MyClass();
var target = new TargetClass();

source.BindProperty(src => src.Number, target, t => t.Num);

source.Number = 10;
Console.WriteLine(target.Num); // 10

You can negate a boolean property while binding it. I use it a lot and find it very handy.

1
2
3
4
source.BindProperty(src => src.IsActive, target, t => !t.IsDeleted);

source.IsActive = false;
Console.WriteLine(target.IsDeleted); // True

You can bind primitive data-types in source class to Nullable primitive data-types in the target class, and vice versa.

1
source.BindProperty(src => src.Number, target, t => t.NullableNumber);

What happens if source is null, and the target is not Nullable?

The default behavior is to update target with default value of that type:

1
2
3
4
5
target.Number = 10;
source.BindProperty(src => src.NullableNumber, target, t => t.Number);

source.NullableNumber = null;
Console.WriteLine(target.Number); // 0

You can also choose not to update target if source becomes null:

1
2
3
4
5
6
target.Number = 10;
source.BindProperty(src => src.NullableNumber, target, t => t.Number,
    BindPropertyOptions.DontUpdateWhenSourceIsNullAndTargetIsNotNullable);

source.NullableNumber = null;
Console.WriteLine(target.Number); // still 10

How to find more information about this library?

At the moment the best way to find out how this library works is by reading the unit tests or at least their titles.

INPC-Extensions is now hosted in GitHub and is licensed under MIT.

Syntax Highlighter for Windows Forms Rich Text Box

| Comments

Years ago I created a tool called Code4Public to convert source code into HTML called. I was using this tool to put nice code snippets in the blog I used to maintain at that time. The tool is able to get the code, apply syntax highlighting to it based on the syntax of the language selected, and then create HTML based on the theme selected (e.g., MSDN theme). I didn’t assign more time on making the tool better and better, as better ways of doing the same task were emerging, and also other by-products of the tool were becoming more interesting at the time; e.g., YAXLib was a little by-product of Code4Public used to store settings, themes and language syntaxes in XML files.

This post is to introduce yet another by-product of Code4Public: WinFormsSyntaxHighlighter. This library enables syntax highlighting on a RichTextBox based on patterns that the developer defines.

The syntax highlighter hooks into RichTextBox events in the constructor.

1
var syntaxHighlighter = new SyntaxHighlighter(theRichTextBox);

That’s it. Now I need to define patterns and colors. For example I want to see for, foreach, int and var in blue:

1
2
3
4
// 1st set of keywords; I'd like to see them in Blue
syntaxHighlighter.AddPattern(
    new PatternDefinition("for", "foreach", "int", "var"),
    new SyntaxStyle(Color.Blue));

I can also define whether I want to see a pattern in bold or italics. For example I want to see public, partial, class, and void in bold navy but not italics. I want the match these words case-insensitively, so that PuBlIc will be shown in navy blue as well. Note that this is an imaginary syntax for demonstration purposes only:

1
2
3
4
// 2nd set of keywords; I'd like to see them in bold Navy, and they must be case insensitive
syntaxHighlighter.AddPattern(
    new CaseInsensitivePatternDefinition("public", "partial", "class", "void"),
    new SyntaxStyle(Color.Navy, bold: true, italic: false));

I can also define the patterns directly with regular expression:

1
2
3
4
// numbers; I'd like to see them in purple
syntaxHighlighter.AddPattern(
    new PatternDefinition(@"\d+\.\d+|\d+"),
    new SyntaxStyle(Color.Purple));

Since the input string is partitioned by the patterns defined in the order of their definition, they must be added in the proper order. E.g., I want to see numbers in purple, but not those numbers inside a comment or inside a string. So the pattern definition for a comment block must be added first, then the pattern for string literal, and at last the pattern for numbers. The following is a more complete example from the beginning to the end.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var syntaxHighlighter = new SyntaxHighlighter(theRichTextBox);

// That's it. Now tell me how you'd like to see what...

// multi-line comments; I'd like to see them in dark-sea-green and italic
syntaxHighlighter.AddPattern(
    new PatternDefinition(new Regex(@"/\*(.|[\r\n])*?\*/",
        RegexOptions.Multiline | RegexOptions.Compiled)),
    new SyntaxStyle(Color.DarkSeaGreen, bold: false, italic: true));

// singlie-line comments; I'd like to see them in Green and italic
syntaxHighlighter.AddPattern(
    new PatternDefinition(new Regex(@"//.*?$",
        RegexOptions.Multiline | RegexOptions.Compiled)),
    new SyntaxStyle(Color.Green, bold: false, italic: true));

// double quote strings; I'd like to see them in Red
syntaxHighlighter.AddPattern(
    new PatternDefinition(@"\""([^""]|\""\"")+\"""),
    new SyntaxStyle(Color.Red));

// single quote strings; I'd like to see them in Salmon 
syntaxHighlighter.AddPattern(
    new PatternDefinition(@"\'([^']|\'\')+\'"),
    new SyntaxStyle(Color.Salmon));

// 1st set of keywords; I'd like to see them in Blue
syntaxHighlighter.AddPattern(
    new PatternDefinition("for", "foreach", "int", "var"),
    new SyntaxStyle(Color.Blue));

// 2nd set of keywords; I'd like to see them in bold Navy, and they must be case insensitive
syntaxHighlighter.AddPattern(
    new CaseInsensitivePatternDefinition("public", "partial", "class", "void"),
    new SyntaxStyle(Color.Navy, true, false));

// numbers; I'd like to see them in purple
syntaxHighlighter.AddPattern(
    new PatternDefinition(@"\d+\.\d+|\d+"),
    new SyntaxStyle(Color.Purple));

// operators; I'd like to see them in Brown
syntaxHighlighter.AddPattern(
    new PatternDefinition("+", "-", ">", "<", "&", "|"),
    new SyntaxStyle(Color.Brown));

Please also note that, nobody can model a whole language like C# or Java with regular expressions, because these languages are not regular. So this tool is by no means a complete and error-free way of modeling languages. Use this just for simple key-word matching or pattern matching and coloring them as you like; but don’t expect too much.

WinFormsSyntaxHighlighter is hosted in GitHub and is licensed under MIT.

The Pains of Upgrading Android Studio

| Comments

I could gracefully install and test earlier versions of Android Studio before they adopted Gradle for their build system. After doing the upgrade I could no longer build a single project with weird error messages relating to Gradle. I searched the web, and found some workarounds in stackoverflow, e.g., manually installing Gradle, updating environment variables and so and so. None of them were helpful for me, although they seemed to be solving the issue for many (who have voted for the answers). I had to do the following steps instead:

  1. Downloaded the latest version of SDK which is bundled with Eclipse. Although many answers suggested to upgrade the SDK to the latest version through SDK Manager, and I did so; it did not solve my problem. So I downloaded a fresh copy of latest SDK bundled with eclipse, and then updated Android Studio settings to refer to this new SDK. This trick solved the build problem.
  2. When running the emulator I got a very descriptive error message (#NOT) that says: PANIC: could not open Nexus, in which Nexus is the name of my emulator. For this problem what I found on stackoverflow was quite helpful, for example see this thread. The trick is to create an environment variable called ANDROID_SDK_HOME and set it to the path of the folder containing .android folder. If you don’t know where is your .android folder, AVD Manager will give you the path in its main screen right above the list of existing virtual devices. For my case it was in D:\Documents. After setting the environment variable I had to restart both AVD Manager and Android Studio.

Moved My Blog to Octopress

| Comments

I’ve moved my blog from Wordpress to my homepage domain. It makes use of Octopress, which is based on Jekyll, and is a static site generator. The blog is hosted on GitHub pages, and is open source.

The great benefit of this stack of tools is that I can easily create and edit my posts in Markdown, re-generate the blog through command line, and make use of Rake (Ruby’s make tools) to perform various tasks ranging from post creation to deployment to GitHub pages. It’s awesome.

How to Make More Refactoring Friendly Data-bindings With C# 5

| Comments

Imagine that we want to create a Person business object for whose properties we desire a two-way data binding. The source-to-target data-binding can be triggered by implementing INotifyPropertyChanged interface, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public double Age
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged("Age");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

See how the setters pass the property name in a string. This is not nice, because whenever we change the property name through refactoring tools, the string value remains untouched and we have to manually change them as well (if we are lucky enough to get notified before run-time). Anyway we had to tolerate them for years…

C# 5 comes with a nice feature, which is addition of two attributes [CallerFilePath] and [CallerMemberName] in the System.Runtime.CompilerServices namespace. If you decorate an optional string parameter of a method with one of these attributes, then the value of that parameter will be replaced with the caller’s file name or the caller’s member name at runtime, if no explicit value is passed for the optional parameter. They come very handy in logging scenarios, but we can use the latter for making our data-binding code nicer. This is how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Person : INotifyPropertyChanged
{
    private string _name;
    private double _age;

    public string Name
    {
        get
        {
            return _name;
        }

        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }

    public double Age
    {
        get
        {
            return _age;
        }

        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Now that string constants are removed from the setters we can more freely refactor our code. After being spoiled by automatic properties, this is still a very verbose way of defining properties; however it is much better than before.

Different Ways of Generating New GUIDs

| Comments

In C# Code

1
var newGuid = Guid.NewGuid();

In Visual Studio

Go to: Tools > Create GUID

In SQL Server Management Studio

Execute either of the following queries:

1
SELECT NEWID()

or

1
PRINT NEWID()

None of the above

Go to newguid.com, and refresh the page as many times as you want.

An Example for C# Dynamic in Action

| Comments

Recently I was involved with enabling validation for a Windows Forms form containing several pages shown through a tree view. There were one user control defined for each page, therefore whenever a node in tree-view got activated, an instance of that user-control were shown. The user-controls did not have a common user-defined parent base-class or interface. The author of the existing code had defined a Save method in each control separately which performed updating data with values entered in the forms.

First, I changed all void Save() methods to bool Save(), and performed the validation stuff in each control separately. Then in the parent form, I created an array of Controls, so that I could loop through them, and call their Save method. But wait, Save is not inherited from any base-class or interface, so there’s no polymorphism at hand. How can I call them through references of type Control?

Well honestly, the best solution would be adding a new interface to the project, say ISavableControl or something, add the Save method to it, and let the controls implement that interface. But I wanted to make a quick fix to the problem without adding new files and types to the code. Here C#’s dynamic comes into action.

Using dynamic keyword, one postpones binding methods, properties, and fields to run-time. In our scenario we know that the user-controls each have a method called Save, which is not derived from a parent. Without dynamic, I would need to have a reference explicitly from each user control’s type, and I would have to call them one by one, as in:

1
2
3
4
5
6
bool succeeded = false;
succeeded = userControl1.Save();
succeeded = succeeded || userControl2.Save();
succeeded = succeeded || userControl3.Save();
// ...
succeeded = succeeded || userControln.Save();

However using dynamic keyword, life gets a lot easier:

1
2
3
4
5
6
7
8
9
10
// objects are not inherited from a base class or interface,
// therefore we cannot call Save using polymorphism
bool succeeded = false;
foreach(var ctrl in controlsArray)
{
    dynamic dynCtrl = ctrl;
    succeeded = succeeded || dynCtrl.Save();
}

// do something with the value of succeeded

Take care that binding the Save methods to controls happen at runtime. Therefore if a control does not implement a Save method, or if another one misspells Save, as say Svae, you will get no hints at compile time. So, try to avoid this style of coding, unless you have good reasons for doing so.