Archive for the ‘Development’ Category.

Aspx CheckBoxList Alternative that allows for the OnCheckedChanged event

My team had to edit an older apsx website and add a list of CheckBoxes, which are actually html <input type="checkbox"/> tags.  We assumed that CheckBoxList would be perfect for our task. We assumed wrong.

I wrote desktop apps for years and now that I am writing web apps, I am using MVC and Razor, so I missed the aspx days. However, having to work on legacy aspx applications is catching me up.

My use case for list of CheckBoxes

Really, my use case is simple. There are icons that should show up for some products. We wanted to store a map between products and the icons in the database. On the product page, we want a list of the icons with a checkbox by each list item. This would allow the person who creates new products to select which icons to show on a product download page.

  1. Get a list of option from a database and display that list as html checkboxes.
  2. Checking a checkbox should add a row to a database table.
  3. Unchecking a checkbox should remove that row from a database table.

CheckBoxList Fails

So what I needed was an OnClick event which is actually called OnCheckedChanged in an asp:Checkbox. Well, it turns out that the CheckBoxList control doesn’t support the OnCheckedChanged event per CheckBox. The CheckBoxList doesn’t have any type of OnClick method. Instead, there is an OnSelectedIndexChanged event. But OnSelectedIndexChanged doesn’t even tell you which CheckBox was clicked. If a CheckBox is checked, then in the OnSelectedIndexChanged event, the SelectedItem equals the clicked item, however, if the CheckBox is unchecked, the SelectedItem was a completely different CheckBox that is checked.

So to me, this made the CheckBoxList control not usable. So I set out to replicate a CheckBoxList in a way that supports OnCheckedChanged.

Repeater with CheckBox for ItemTemplate

I ended up using the Repeater control with an ItemTemplate containing a CheckBox. Using this method worked pretty much flawlessly. It leaves me to wonder, why was CheckBoxList created in the first place if a Repeater with a CheckBox in the template works perfectly well.

Here is my code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxListExample._Default" %>

<%@ Import Namespace="CheckBoxListExample" %>
<%@ Import Namespace="CheckBoxListExample.Models" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <asp:CheckBox ID="cb1" runat="server" AutoPostBack="true" OnCheckedChanged="RepeaterCheckBoxChanged"
                    Text="<%# ((CheckBoxViewModel)Container.DataItem).Name %>"
                    Checked="<%# ((CheckBoxViewModel)Container.DataItem).IsChecked %>" />
            </ItemTemplate>
        </asp:Repeater>
    </div>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using CheckBoxListExample.Models;

namespace CheckBoxListExample
{
    public partial class _Default : Page
    {
        private List<CheckBoxViewModel> _ViewModels;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var _ViewModels = new List<CheckBoxViewModel>
                {
                    new CheckBoxViewModel {Name = "Test1", IsChecked = true},
                    new CheckBoxViewModel {Name = "Test2"},
                    new CheckBoxViewModel {Name = "Test3"}
                };
                Repeater1.DataSource = _ViewModels;
                Repeater1.DataBind();
            }
        }

        protected void RepeaterCheckBoxChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;
            if (cb == null) return;
            if (cb.Checked)
            {
                // Insert
            }
            else
            {
                // Delete
            }
        }
    }
}
namespace CheckBoxListExample.Models
{
    public class CheckBoxViewModel
    {
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }
}

Why to use string.format() over concatenation (Real world experience)

So today I was working on reverse engineering some old code. I will strip this down and remove proprietary info but still let you see the bug. This is a post for newbies but experienced coders might get a laugh out of this as well.

Here is the error code:

var contract = CustomerId + ProductGroupId + EndDate.ToString("yy-MM");

Now, imagine these values:

CustomerId = 12345
ProductId = 4
Date = 8/7/2014

A new developer would assume that this would return the following:

12345415-08

They would be wrong. See, CustomerId and ProductGroupId are integers. So they don’t concatenate as strings, they add as integers. The real value is this:

1234915-08

12345 + 4 = 12349. This is math, not string concatenation.

How would a developer resolve this bug? There are two solutions:

  • Use ToString() and concatenation (DO NOT USE!)
  • Use string.Concat() (USE FOR SIMPLE CONCATENATION OR PERFORMANCE!)
  • Use string.Format() (USE FOR CONCATENATION WITH FORMATTING!)

Here is the another interesting fact. I know exactly when this bug was introduced into the system. This code was written by the developer using the first solution. The developer had originally added .ToString() to the end of these objects. The developer didn’t write buggy code. He wrote code that worked.

The code used to look like this:

var contract = CustomerId.ToString() + ProductGroupId.ToString() + EndDate.ToString("yy-MM");

So what happened? If a developer didn’t break this code, who did?

I’ll tell you what happened and who did it. Resharper.

Today, developers aren’t the only ones messing with our code. We use tools that are pretty awesome to do masses of code automation for us. One of these tools is Resharper. Well, Resharper detected the ToString() methods as “Redundant Code.” Oh, in this case, it wasn’t redundant code.

The only reason I found this bug is because I was rewriting this piece of code and had to reconstruct a ContractId and I began reverse engineering this code. I noticed that the first part of the ContractId was the CustomerId up until a few months ago. After that, it seemed to be slightly off. I was able to check source from back then and see the difference and see why this bug started. Sure enough, when resharper cleaned up my redundant code, it removed the ToString() methods.

However, while this is a Resharper bug, let’s not jump so fast to blaming Resharper. I’ll submit a bug to them, but are they really at fault? I say not completely. Why? Because the developer chose to use ToString() and concatenation instead of string.Format(). This was the wrong choice. Always use string.format(). This has been preached by many, but just as many don’t listen.

What would have happened if the developer had followed the best practice to use string.Format() or string.Concat?

var contract = string.Concat(CustomerId, ProductGroupId, EndDate.ToString("yy-MM"));

or

var contract = string.Format("{0}{1}{2}", CustomerId, ProductGroupId, EndDate.ToString("yy-MM");

The bug would never had occurred. With either string.Concat() or string.Format(). In those uses, the ToString() methods really would be redundant. With or without them, the code acts the same.

But surely avoiding a Resharper bug isn’t the only reason to use string.Concat or string.Format()? Of course there are more reasons. This error was due to the ambiguous + operator. Using string.Format() or string.Concat() eliminates such ambiguities. Also, with string.Format(), the developer’s intentions are much more clear. The format decided upon is explicitly included. When I type “{0}{1}{2}”, there is no question about what the intended format is. This is why I chose string.Format() for this piece of code. It is self-documenting and unambiguous.

Conclusion

Best practices are best  practices for a reason. Use them. Using string.Format() is always preferable to string concatenation.

P.S. This old project also could have alerted us to this error if anyone would have bothered to write a Unit Test. But this code was buried deep in a method that itself was hundreds of lines long. Following the 100/10 rule and testing would have alerted us when Resharper introduced this error.

How to add a progress bar to your blog

Some authors want to add progress bars to their blog. However, most authors are not web designers or developers. So they don’t know how to do this. Well, there is a secret in the html development world. The secret is that “Everything is easy once you know how to do it.” Yes, it is actually pretty easy to add a progress bar. I just added a progress bar to my blog.

Creating a Progress Bar on your Blog

Step 1. Create an HTML Widget for your side bar.

Using your blogging engine (WordPress or Blogger or whatever) create an html widget. In WordPress you would use a Text widget.

Step 2. Paste in the following html code

1st draft of Book 2
<div id="progressbar" style="background-color:black;border-radius:6px;padding:3px;">
    <div style="background-color:#dd6013;width:30%;height:10px;border-radius:4px;"></div>
</div>

It will look like this:

1st draft of Book 2

[Read More . . .]

Select Option Web Control with Knockout.js and MVVM

<!-- Step 1 - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
        $(document).ready(function(){
 
 
            <!-- Step 4 - Create a data model -->
            var SelectableListDataModel = function () {
                // Private
                var _self = this;

                // Public
                _self.labels = new Array(); // Should have same count as values
                _self.values = new Array(); // Should have same count as Labels
                _self.defaultValue = 0;
                _self.canSelectMethod = function () { return true; },
                _self.push = function (label, value) {
                    _self.labels.push(label);
                    _self.values.push(value);
                };
            };
 
            <!-- Step 5 - Add an OptionViewModel -->
            var OptionViewModel = function(parent, label, value, canSelectMethod) {
                // private
                var _self = this;
                var _parent = parent;

                // public
                _self.id = ko.observable();
                _self.class = ko.observable();
                _self.label = label ? ko.observable(label) : ko.observable();
                _self.value = value ? ko.observable(value) : ko.observable();
                _self.isSelected = ko.computed(function () {
                    return (_parent && _parent.selectedValue) ? _parent.selectedValue() == _self.value() : false;
                }, _self);
                _self.canSelect = canSelectMethod ? ko.computed(canSelectMethod) : ko.computed(function () { return true; });
            };

            <!-- Step 6 - Add an SelectViewModel -->
            var SelectViewModel = function (selectableListDataModel) {
                // private
                var _self = this;
                var _defaultDataModel = new SelectableListDataModel();
                var _dataModel = selectableListDataModel ? selectableListDataModel : _defaultDataModel;

                // Public
                _self.canSelect = (_dataModel.canSelectMethod)? ko.computed(_dataModel.canSelectMethod) : ko.computed(_defaultDataModel.canSelectMethod);
                _self.list = ko.observableArray();
                _self.selectedValue = _dataModel.defaultValue ? ko.observable(_dataModel.defaultValue) : ko.observable();
                
                if (_dataModel.labels && _dataModel.values) {
                    for (var i = 0; i < _dataModel.labels.length; i++) {
                        _self.list.push(new OptionViewModel(_self, _dataModel.labels[i], _dataModel.values[i], _self.canSelect));
                    }
                }
                
                _self.selectedIndex = ko.computed(function () {
                    var index = 0;
                    var foundIndex = -1;
                    ko.utils.arrayForEach(_self.list(), function (item) {
                        if (_self.selectedValue() == item.value()) {
                            foundIndex = index;
                        }
                        index++;
                    });
                    return foundIndex;
                }, _self);

                _self.selectedText = ko.computed(function () {
               _self.selectedText = ko.computed(function () {
                    var index = _self.selectedIndex();
                    return (_self.list()[index]) ? _self.list()[index].label() : "";
                }, _self);
                }, _self);
                
                _self.clear = function (value) {
                    _self.selectedValue(value ? value : "");
                };
            }
 
            <!-- Step 7 - Create ViewModel for whatever you need -->
            function SurveyAnswerViewModel() {
                var self = this;
                 
                <!-- Step 8 - Create an observable list instance -->
                self.dataModel = new SelectableListDataModel();
                self.dataModel.labels = new Array("Good", "Average", "Poor");
                self.dataModel.values = new Array(10,5,1);
                self.dataModel.selectedValue = 10;
                
                <!-- Step 9 - Create a SelectViewModel instance -->
                self.selectGroup1 = new SelectViewModel(self.dataModel);                       
                 
                <!-- Step 10 - Create a computed value to require a selection before submitting -->
                self.canClick = ko.computed( function() {
                    return self.selectGroup1.selectedValue() != "";
                }, self);
                
                <!-- Step 11 - Make some button methods for this example -->
                self.submitClick = function(){
                    // Do something here
                }
                
                self.resetClick = function(){
                    self.selectGroup1.clear();
                }
            }
            
            <!-- Step 12 - Create a computed value to require a selection before submitting -->   
            ko.applyBindings(new SurveyAnswerViewModel());
        });
    </script>
</head>
<body>
    <!-- Step 13 - Create a drop down select item -->
    <select data-bind="options: selectGroup1.list, optionsText: 'label', optionsValue: 'value', value: selectGroup1.selectedValue"></select>
    <br />
    
    <!-- Step 14 - Add html elements to see other properties -->
    <p data-bind="text: 'Index: ' +  selectGroup1.selectedIndex()"></p>
    <p data-bind="text: 'Value: ' +  selectGroup1.selectedValue()"></p>
    <p data-bind="text: 'Text: ' +  selectGroup1.selectedText()"></p>
     
    <!-- Step 15 - Add a button and bind its to methods -->
    <button type="submit" id="btnSubmit" data-bind="enable: canClick, click: submitClick">Submit</button>
    <button type="reset" id="btnReset" data-bind="enable: canClick, click: resetClick">Reset</button>
 
</body>
</html>

RadioButton web control with Knockout.js and MVVM

Here is an example of a RadioButton control using Knockout and MVVM. Hope this helps anyone looking.

<!-- Step 1 - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
        $(document).ready(function(){
 
            <!-- Step 4 - Add a RadioButtonModel -->
            var RadioButtonModel = function(parent, inText, inValue, inGroupName, canClickMethod) {
                    // Private
                    var _self = this;
                    var _canClickMethod = (canClickMethod) ? canClickMethod : function() { return true; };
                    var _parent = parent;

                    // Public
                    this.text = ko.observable(inText);
                    this.value = ko.observable(inValue);
                    this.group = ko.observable(inGroupName);
                    this.class = ko.observable();
                    this.isSelected = ko.computed(function() {
                        return (_parent && _parent.selectedValue) ? _parent.selectedValue() == _self.value() : false;
                    }, _self);
                    _self.canClick = ko.computed(function() { return _canClickMethod(); });
                };
                
                
            <!-- Step 5 - Add a RadioButtonViewModel -->
            var RadioButtonViewModel = function (rbLabels, rbValues, group, defaultValue) {
                // Private
                var _self = this;
                var _rbLables = rbLabels;
                var _rbValues = rbValues;
                var _group = group;
                var _defaultValue = defaultValue;                

                // Public
                _self.selectedValue = ko.observable(_defaultValue);
                
                _self.list = ko.observableArray();
                for (var i = 0; i < _rbLables.length; i++) {
                    _self.list.push(new RadioButtonModel(_self, _rbLables[i], _rbValues[i], _group));
                }

                _self.selectedIndex = ko.computed(function () {
                    var i = 0;
                    var foundIndex = -1;
                    ko.utils.arrayForEach(_self.list(), function (item) {
                        if (_self.selectedValue() == item.value()) {
                            foundIndex = i;
                        }
                        i++;
                    });
                    return foundIndex;
                }, _self);

                _self.selectedText = ko.computed(function () {
                    return (_self.list()[_self.selectedIndex()]) ? _self.list()[_self.selectedIndex()].text() : "";
                }, _self);
                
                _self.clear = function(value){
                    _self.selectedValue(value ? value : "");
                }
                
            }
 
            <!-- Step 6 - Create ViewModel for whatever you need -->
            function SurveyAnswerViewModel() {
                var self = this;
                 
                <!-- Step 7 - Create an observable list instance -->
                self.rbGroup1 = new RadioButtonViewModel(new Array("Good", "Average", "Poor"), new Array(10,5,1), "Group1", 10);                           
                 
                <!-- Step 8 - Create a computed value to require a selection before submitting -->
                self.canClick = ko.computed( function() {
                    return self.rbGroup1.selectedValue() != "";
                }, self);
                
                <!-- Step 9 - Make some button methods for this example -->
                self.submitClick = function(){
                    // Do something here
                }
                
                self.resetClick = function(){
                    self.rbGroup1.clear();
                }                 
            }
            
            <!-- Step 10 - Create a computed value to require a selection before submitting -->   
            ko.applyBindings(new SurveyAnswerViewModel());
        });
    </script>
</head>
<body>
    <!-- Step 11 - Create a div containing the html for one radio button and bind to foreach: list -->
    <div data-bind="foreach: rbGroup1.list">
        <div>
            <input type="radio" data-bind="attr: {name: group}, value: value, checked: $root.rbGroup1.selectedValue, checkedValue: value" />
            <span data-bind="text: $index() + '. ' + text()"></span>
            <span data-bind="text: 'Is selected: ' + isSelected()"></span>
        </div>
    </div>
    <br />
    
    <!-- Step 12 - Add html elements to see other properties -->
    <p data-bind="text: rbGroup1.selectedValue"></p>
    <p data-bind="text: rbGroup1.selectedText"></p>
     
    <!-- Step 13 - Add a button and bind its to methods -->
    <button type="submit" id="btnSubmit" data-bind="enable: canClick, click: submitClick">Submit</button>
    <button type="reset" id="btnReset" data-bind="enable: canClick, click: resetClick">Reset</button>
 
</body>
</html>

Using slideToggle with Knockout’s MVVM

I recommend you use the third option: Option 3 – Boolean binding using a custom binding handler called slideToggle

See it live here: http://plnkr.co/edit/1YGchAyjkNSjYzmXFfK2

<!-- Step 1a - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript">
        $(document).ready(function(){
         
            <!-- Step 4 - Create a ViewModel -->           
            function viewModel() {
                _self = this;
                _self.showHideChild = function(viewModel, event) {
                    $(event.currentTarget).children('div').slideToggle()
                };
                _self.showHideNextSibling = function(viewModel, event) {
                    var siblings = $(event.currentTarget).siblings('div');
                    for (var i=0;i<siblings.length;i++) {
                        if (siblings[i].previousElementSibling == event.currentTarget ) {
                            $(siblings[i]).slideToggle();
                        }
                    }                 
                };
                _self.isVisible = ko.observable(false);
                _self.showHide = function() {
                    _self.isVisible(!_self.isVisible());
                }
            };
           
            ko.bindingHandlers.slideToggle = {
                init: function (element, valueAccessor) {
                    var value = valueAccessor();
                    $(element).toggle(ko.utils.unwrapObservable(value));
                },
                update: function (element, valueAccessor) {
                    var value = valueAccessor();
                    var isVisible = element.offsetWidth > 0 && element.offsetHeight > 0;
                    if (ko.utils.unwrapObservable(value) != isVisible) {
                        $(element).slideToggle();
                    }
                }
            };
           
            <!-- Step 5 -  Activates knockout.js bindings -->
          ko.applyBindings(new viewModel());
        });
    </script>
</head>
<!-- Step 4 - Create a HTML Elements with bindings -->
<body style="">
    <div>
        Option 1 - Child div
        <div id="child1" data-bind="click: showHideChild" style="border:2px solid;">
        Click me
            <div id="child2" style="display: none;">
              Now you see me!
            </div>
        </div>
        
        Option 2 - Siblings div
        <div id="sib1" style="border:2px solid;">
            <div id="sib2" data-bind="click: showHideNextSibling" >
            Click me
            </div>
            <div id="sib3" style="display: none;">
            Now you see me!
            </div>
            <div id="sib4">
            You should always see me.
            </div>
        </div>
        Option 3 - Boolean binding using a custom binding handler called slideToggle 
        <div id="bool1" style="border:2px solid;">
            <div id="bool2" data-bind="click: showHide" >
            Click me
            </div>
            <div id="bool3" data-bind="slideToggle: isVisible">
            Now you see me!
            </div>
        </div>
    </div>
</body>
</html>

The 10/100 Principle – Following this one development rule will improve your code

There is a simple guideline that every developer can follow that will make their code easier to manage and easier to test, or essentially, make your code S.O.L.I.D. (You should be familiar with S.O.L.I.D. principles of software engineering. If not, look it up now.)

The 10/100 Principle

Question: What is the 10/100 principle?

The 10/100 Principle is liked training wheels for writing code that follows S.O.L.I.D. principles.

Answer: It is a simple rule that developers should follow to keep their code concise and clean. It involves keeping in mind two warning signs for bad code.

  • Warning #1 – If a method reaches 10 lines, you need to stop and consider refactoring the method.
  • Warning #2 – If a class reaches 100 lines (comments and brackets included) you should stop and consider refactoring.
  • Warning #3 – If an interface reaches 10 combined methods and properties, you need to stop and consider refactoring the interface to be multiple interfaces.

Like me, you have probably heard both rules before. I see the rule to keep methods short written over and over again in other blogs and other software engineer’s guidelines. But I rarely see this touted as the #1 most important rule that all developers should learn first.

Why should developers learn the 10/100 principle first?

Because it is the single most effective rule to improve code that any developer can learn in less than a minute. No other rule can be learned in other a minute and improve a developers code as much.

It is hard to know how to write S.O.L.I.D. code, especially as a new developer. However, just like when learning to ride a bike, you start with training wheels, in order to write solid code, you should start with the 10/100 Principle. It is your training wheels for solid code.

I gave this rule to a first year developer (not college educated) and after following this rule, he wrote “proof of concept” code. As many more experienced engineers know, proof of concept code sometimes becomes release code. It is usually a horrible tragedy when this happens. The code is usually rough and untestable and filled with scripting or linear processing. However, in this case, that issue didn’t occur. All the classes were under 100 lines (most considerably under 100 lines). All the method were easily testable and under 10 lines. Sure there were a few that needed to be broken up. The code wasn’t perfect. But the most important and amazing thing about his code were the design patterns he used without even knowing them. He used the proxy and bridge patterns. He used the builder pattern. He used a rudimentary version of the Factory Pattern. He had small and easily manageable singletons. I even found the chain of responsibility pattern in his code. He also had a number of “Extension methods” since he was using C# which further increased the testability and the readability of his code.

When a developer asks me if they should study design guidelines and learn the many design patterns common to the industry I say, “Yes, of course study them.” However, if a developer follows the rules above, they will naturally find themselves using many of these patterns without even knowing them. It is the perfect rule to keep your code inline until you are an expert.

Why does the 10/100 principle work?

Look at the first year developer’s experience mentioned above. His code wasn’t perfect, but just the effort he took to keep the classes under 100 lines the methods under 10 lines forced him to create other objects that made more sense for the task at hand. These other objects naturally fell into the realm of well-known design patterns. It works because all the classes are kept small.

The 10/100 principle helps with the Keep it super simple (KISS) rule.

The 10/100 principle helps with the Single Responsibility Principle (SRP),  though it doesn’t guarantee the SRP, it helps users naturally stay close to that rule. Sure they may have C# class do two things instead of one because two things fit in the 100 lines allowed for a class. However, how many times have you touched someone else’s code and found a class doing a dozen things in a class that is more than 500 or 1000 lines. To fix this code you have to redesign and break this class into a dozen or more other objects. I think you would be more than happy to only have a class doing two things. Sure you need to break it still, but you only need to break it in half, which is much easier.

Summing Lines in a Method

If you call MethodA from MethodB, and MethodB is not abstractable (isn’t a method on an abstraction or interface), then the methods add together.

Look at the following class.

public class SomethingDoer
{

private readonly ISomeDependency _someDependency;

public Example(ISomeDependency someDependency)
{
_someDependency = someDependency;
}

private DoSomething1()
{
DoSomething2();
DoSomething3();
_someDependency.DependencyWork();
}

private DoSomething2()
{
// ... 8 lines of code
}

private DoSomething3()
{
// ... 9 lines of code
}
}

How many lines is DoSomething1()? Is it 3?

No. this is a 20 line method.

How? Since it calls methods that are not abstracted, those lines sum together. DoSomething2() which is 8 lines, and DoSomething3() which is 9 lines, makes 17 lines, plus its own three lines.

3 + 8 + 9 = 20

Why? When you go to test this, can you mock or fake DoSomething2() or DoSomething3()? No, you can’t. You have to include them in Unit Tests because if the code calls DoSomething1(), the code is also calling DoSomething2() and DoSomething3(). This isn’t just a test thing. Tests just reveal the truth. The code is breaking the single responsibility principle. DoSomething1() is not performing a single responsibility. If the method is doing the correct responsibility, then the multiple responsibilities might be at the class level. You probably need to break this class up into 3 classes, and the other two methods would be abstracted into sub classes.

It is a guideline that can be broken

The 10/100 principle is a guideline. When a class reaches 100 lines you stop and think. When a method reaches 10 lines, you stop and think. However, thinking is the most important part. Should this method take 10 lines? Maybe it should. Should this class be longer than 100 lines? Maybe it should.

There are always exceptions

  • Generated code – it is as big as the generator makes it.
  • Interface implementation –  You may have to implement an interface (such as IList) and when you are done, your class is already over 100 lines and you haven’t even added any methods other than the interface’s methods. Well, some might argue that the developers of your interface could have used a smaller interface (the I in S.O.L.I.D.) but there is usually nothing you can do about that, as IList is not your code. This class isn’t going to be able to follow that 10/100 principle. That is OK.
  • Unit Tests – I don’t always follow the 10/100 Principle, however, keeping your unit tests testing one thing is still important, and you will find your unit tests natural stay close to this rule when testing code that follows this rule.
  • Algorithm – Sometimes implementing an algorithm in one method will result in a method much more than 10 lines. You could break it up, but maybe that has performance issues.

Keep studying

Remember the 10/100 principle takes less than one minute to learn. It is the single most effective rule a developer can learn in 1 minute to improve their code. It is not the end.

Sure, this rule is always good to follow, even for senior developers, however, this rule doesn’t solve everything. It doesn’t teach interface-based design and good decoupling. It doesn’t make developers follow the open/closed principle or the substitution principle. However, it usually prevents code from becoming spaghetti code. The 10/100 principle keeps the blocks small and easily to work with and easy to fix. So when you see the code and you have to revamp it to include dependency injection and decouple it, you will have a much easier time.

Senior Developers Benefit too

There are two reasons senior developers should follow this rule.

  1. They have never really been taught to write solid code and still need to learn
  2. They are more skilled and have more tools to help follow the 10/100 Principle.

Never Learned to write solid code

It isn’t always a developers fault that they didn’t have great leads. Often they are led astray by their first teams. Or they are thrown to the wolves without a team.

Adopting the 10/100 pattern for all new code is easy for a senior dev to do to immediately change their mindset to write solid code.

More tools in your toolbox

Senior engineers should make larger efforts to the follow the 10/100 Principle because the can. New developers aren’t going to have any idea about more complex development tools. One such example of this is Aspect Oriented Programming (AOP) to handle cross-cutting concerns. New developers will accept that some instance where the 10/100 principle is broken that maybe a senior developer shouldn’t accept. Senior developers should have heard of cross-cutting concerns and should have at least heard of AOP. Often when a method is probably kept in scope, but still reaches over 10 lines, it may be using a try/catch block.

Check out this code found in a single method. The stub code alone is 35 lines. With the missing log, the method was over 50 lines. Is this acceptable just because it is doing a try/catch block?

public StreamReader TryReadFile(string path)
{
    try
    {
        return File.OpenText(path);
    }
    catch (UnauthorizedAccessException ane)
    {
        // handle exception
    }
    catch (ArgumentNullException ane)
    {
        // handle exception
    }
    catch (ArgumentException ane)
    {
        // handle exception
    }
    catch (PathTooLongException ane)
    {
        // handle exception
    }
    catch (DirectoryNotFoundException ane)
    {
        // handle exception
    }
    catch (FileNotFoundException ane)
    {
        // handle exception
    }
    catch (NotSupportedException ane)
    {
        // handle exception
    }
}

Well, if you don’t accept this as OK, (well, the cyclomatic complexity is high why would you accept this as OK?) and you seek out how to resolve this, you are going to run across AOP solutions. With AOP, this method could look like this:

[HandeFileReadExceptionsAspect]
public void TryReadFile(string path)
{
    File.OpenText(path);
}

The HandeFileReadExceptionsAspect is now a separate class that is reusable for every instance where you read a file. You now have common code handling the File.Read exceptions and your method that was 50 lines is now 5 lines. Your HandeFileReadExceptionsAspect class will most likely be under 100 lines. So your codes is now cleaner, more decoupled, easier to read, easier to use, and follows the 10/100 Principle.

Conclusion

I preach the 10/100 principle to all developers, new and old. I am not sure that anyone else calls it the 10/100 principle. If you call it something else, let me know.

HTML Search using MVVM with knockout.js

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <script type="text/javascript" >
        $(function(){
         
            // custom binding handler so pressing enter in a textbox is the same
            // as clicking the button.
            ko.bindingHandlers.enterKey = {
                init: function(element, valueAccessor, allBindings, vm) {
                    ko.utils.registerEventHandler(element, "keyup", function(event) {
                        if (event.keyCode === 13) {
                            ko.utils.triggerEvent(element, "change");
                            valueAccessor().call(vm, vm);
                        }                        
                        return true;
                    });
                }         
            };
         
            var fakeSearch = function(args, callback) {
                var data = args;
                callback(data);
                return args;
            };

            var ButtonViewModel = function(text, searchMethod, canSearchMethod) {
                var _self = this;
                _self._canSearchMethod = canSearchMethod;
                _self.text = ko.observable(text);
                _self.onClick = searchMethod;
                _self.canClick = ko.computed(_self._canSearchMethod);                
            };

            var SearchParametersViewModel = {
                'SearchTerm': ko.observable(''),
                'SearchOption': ko.observable(''), // Not used in example
                'StartDate': ko.observable(''),    // Not used in example
                'EndDate': ko.observable('')       // Not used in example
            };

            var SearchViewModel = function(searchMethod, searchArgs) {
                // private properties
                var _self = this;
                _self._searchMethod = searchMethod;
                _self._searchArgs = searchArgs;
                _self._canSearch = function() {
                    return _self.searchParameters.SearchTerm() != null && _self.searchParameters.SearchTerm() != '';
                };

                // public properties
                _self.searchParameters = SearchParametersViewModel;

                _self.results = ko.observable('');
                
                _self.searchCallBack = function (data) {
                    _self.results(JSON.stringify(data));
                };

                _self.searchButton = new ButtonViewModel("Search", 
                function () {
                    _self._searchMethod(_self._searchArgs, _self.searchCallBack);
                }, _self._canSearch);
                
            };
           
          ko.applyBindings(new SearchViewModel(fakeSearch, {a: "1", b: "2"}));
        });
    </script>
</head>
<body>
    <input data-bind="value: searchParameters.SearchTerm, valueUpdate: 'afterkeydown', enterKey: searchButton.onClick" />
    <button type="button" id="btnSearch" data-bind="text: searchButton.text, enable: searchButton.canClick, click: searchButton.onClick"></button>
    <p data-bind="text: results"></p>
</body>
</html>

Removing the namespace from the ConnectionString name in the web.config

So we are working on moving a legacy web site to MVC4.  Yes, it is my first time doing this.  I encountered an annoying issue that I thought worth blogging about.

Ok, so I have a DLL that is pretty much nothing more than a TableAdapter. (Yes, I wish this legacy project was using Entity Framework, but alas, it is not). I have a config file and the connectionstring name has a the mode horrible namespace.

  <connectionStrings>
    <add name="Company.Division.Feature.DataAccessLayer.MyConnectionString" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUser;Password=MyPasswd" providerName="System.Data.SqlClient" />
    <add name="MyConnectionString" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUser;Password=MyPasswd" providerName="System.Data.SqlClient" />
  </connectionStrings>

Seriously: Company.Division.Feature.DataAccessLayer.MyConnectionString.

Yes, the same connection string is listed twice, once with the namespace and once without.

Why? Well, because all throughout the code, the original authors make call this:

ConfigurationManager.ConnectionStrings["WavelinkLMConnectionString"].ConnectionString

I would like to get rid of one of these configuration settings. Obviously to me, it makes sense to get rid of the long one.

So why doesn’t my TableAdapter library project use the shorter table adapter. Well, I figured that out. Because it is in the Settings file and the Settings file looks for the value using the namespace.

Look at this Settings.Designer.cs file

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Company.Division.Feature.DataAccessLayer.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUser;Password=MyPasswd")]
        public string MyConnectionString{
            get {
                return ((string)(this["MyConnectionString"]));
            }
        }
    }
}

OK, so every single TableAdapter requires this value, so I can’t remove it. I could change it but then everytime the settings regenerated this file, I would have to recreate teh change. Not a good idea.

Hooray for partial classes! To fix this, I removed this setting and put it in a separate partial class. In fact, I learned that in the Settings UI, you can click View Code and it will create this file for you. But for me it created in the project root and not under the Properties solution folder, so I had to move it under Properties myself.

using System.Configuration;
using System.Diagnostics;

namespace Company.Division.Feature.DataAccessLayer.Properties
{
    internal sealed partial class Settings
    {
        [ApplicationScopedSetting]
        [DebuggerNonUserCode]
        [SpecialSetting(SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUser;Password=MyPasswd")]
        public string MyConnectionString
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
                    this["MyConnectionString"] = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                return (string)this["MyConnectionString"];
            }
        }
    }
}

As you can see, I just check if the value is set in the config file without the namespace. If it is, I set the setting to that value.

And that is it! I now can make my config have a single connection string and I don’t have to include the namespace!

  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUser;Password=MyPasswd" providerName="System.Data.SqlClient" />
  </connectionStrings>

How a software developer can learn communication?

Here is how a software developer can learn to communicate with their coworkers and avoid being extrovert.

How a software engineer can learn to improve communication

Above is an image so you can pin it.

Below is code so you can copy it.

namespace Communication
{
    public class Improve
    {
        public void ImproveCommunication(bool INeedToTalkToAPersonAboutWork, bool IKnowAboutThisPersonOrTheirFamily)
        {
            if (INeedToTalkToAPersonAboutWork)
            {
                Knowledge newKnowledgeAboutPerson;
                if (IKnowAboutThisPersonOrTheirFamily)
                {
                    DoCommentOnSomethingIAlreadyKnowAboutThisPersonOrTheirFamily();
                    newKnowledgeAboutPerson = Listen();
                }
                else
                {
                    AskFindOutQuestion();
                    newKnowledgeAboutPerson = Listen();
                }

                StoreInMemoryDatabase(newKnowledgeAboutPerson);

            }
            TalkToPersonAboutWork();
        }

        public void DoCommentOnSomethingIAlreadyKnowAboutThisPersonOrTheirFamily()
        {
        }

        public void AskFindOutQuestion()
        {
        }

        public Knowledge Listen()
        {
            return new Knowledge();
        }

        public void StoreInMemoryDatabase(Knowledge newKnowledge)
        {
        }

        public void TalkToPersonAboutWork()
        {
        }
    }

    public class Knowledge
    {
    }
}

Log4Net Example

One of my pet peeves of third party libraries is that they are often not intuitive. I have always held off on using Log4Net because it was not intuitive to use. Well, it is just such a well-known and often-used library that it is impossible to be a C# developer without being familiar with this library.

You don’t always get what you want from a 3rd party library. I want a simple way to put a single line in code and be done. For example, a line of code that says: “Give me a log in the same directory as my exe file and name it the same as my .exe file with the .log extension appended. ILog log = Log4Net.SimpleFileLogger(Assembly.GetExecutingAssembly().Location + “.log”);

Step 1 – Create a new project

  1. Create a new Console Application project in Visual Studio. I named mine Log4Net.Example.
  2. Right-click on the Solution and choose Manage NuGET Packages for Solution.
  3. Click Online and search for Log4Net.
  4. Click Install and install the project for your poject.
  5. Close NuGET Package Manager.

Step 2 – Logging to the console window

  1. Add references to log4Net and log4Net.Config.
    (Note: I don’t know why they have the first character in log4Net namespace lowercase. That goes against most C# coding guidelines. Perhaps this is because it is a port of a java logger?)
  2. Add a member variable or property for your log.
  3. Add a line of log.
// Step 1 - Add references to log4Net and Log
using log4net;
using log4net.Config;

namespace Log4Net.Example
{
    class Program
    {
        // Step 1 - Create a variable to hold your log
        static ILog Log = LogManager.GetLogger("MyApp.log");

        static void Main(string[] args)
        {
            // Step 2 - Run this method. Why? Because the documentation says so. I know, this is NOT INTUITIVE.
            BasicConfigurator.Configure();

            // Step 3 - Log to the console
            Log.Debug("Hello, log!");
        }
    }
}

Step 3 – Log to a file

  1. Add references to log4Net assemblies and other needed assemblies.
  2. Create a variable to hold your log.
  3. Create and configure a FileAppender object.
  4. Configure log4Net to use the FileAppender.
  5. Add a line to log to the file.
// Step 1 - Add references to log4Net assemblies and other needed assemblies
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using System.Reflection;
using System.Text;

namespace Log4Net.Example
{
    class Program
    {
        // Step 2 - Create a variable to hold your log
        static ILog Log = LogManager.GetLogger(Assembly.GetExecutingAssembly().Location + ".log");

        private static void Main()
        {
            // Step 3 - Create and configure a FileAppender object
            var appender = new FileAppender()
            {
                Layout = new SimpleLayout(),
                File = Assembly.GetExecutingAssembly().Location + ".log",
                Encoding = Encoding.UTF8,
                AppendToFile = true,
                LockingModel = new FileAppender.MinimalLock()
            };
            appender.ActivateOptions();

            // Step 4 - Configure log4Net to use the FileAppender
            BasicConfigurator.Configure(appender);

            // Step 5 - Log to the file
            Log.Debug("Hello, log!");
        }
    }
}

Step 4 – Improving the log file

So the easiest way to improve the log is to add date and timestamps to each entry and the log level. This can be done by switching from a SimpleLayout to a PatternLayout as shown:

// Step 1 - Add references to log4Net assemblies and other needed assemblies
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using System.Reflection;
using System.Text;

namespace Log4Net.Example
{
    class Program
    {
        // Step 2 - Create a variable to hold your log
        static ILog Log = LogManager.GetLogger(Assembly.GetExecutingAssembly().Location + ".log");

        private static void Main()
        {
            // Step 3 - Create and configure a FileAppender object
            var appender = new FileAppender()
            {
                Layout = new PatternLayout("%date (%p) %message%newline"),
                File = Assembly.GetExecutingAssembly().Location + ".log",
                Encoding = Encoding.UTF8,
                AppendToFile = true,
                LockingModel = new FileAppender.MinimalLock()
            };
            appender.ActivateOptions();

            // Step 4 - Configure log4Net to use the FileAppender
            BasicConfigurator.Configure(appender);

            // Step 5 - Log to the file
            Log.Debug("Hello, log!");
        }
    }
}

Thank you MacInCloud for my “A” in my iOS course

I was provided service for this post. I was in no other way compensated. All opinions are my own.

As many of you know, I am getting a Masters of Computer Science from Utah State University. I am taking classes remotely in the evenings. When it came time to take a course in iOS development, I had some problems I needed to resolve.

  1. I don’t own an computer with an Apple Operating System.
  2. You can only compile code for iOS on OS X.

macincloud_homeSo I started considering investing in a Mac laptop, but it was too pricey of an option.  Sure as I am already well into my career as a Senior Software Engineer, I could afford it, but just because I have money doesn’t mean I want to waste it. I already have a nice Lenovo T530 from work. I have an older Lenovo T61p that I own (mostly a paperweight since I never use it). I have a nice HP desktop, and my wife has a nice HP laptop. What would I do with another computer?

I looked at a Mac mini and even it was too pricey, so I started looking at used ones. But no matter what I purchased, it was too much money for something that, as a Senior .NET Developer, I likely wouldn’t use once the class was over.

Then I found MacInCloud. MacInCloud is exactly what it sounds like. A Mac in the cloud. I could remote desktop to this Mac and write and compile my iOS apps for my class. With academic plans starting at $16 a month, I couldn’t pass it up.

Well, I used MacInCloud exclusively throughout my iOS course and I am happy to say I got an A. I want to personally thank this company for existing. Some members of my class did pay for the service. I probably should have gotten some feedback from some of them, but they were on-campus and I am a remote student so I didn’t make the effort.

MacInCloud Pros

  1. Everything I need was already on the box: Xcode, iOS emulator. If I had purchased my own Mac, I would have spend a few hours setting it up, including installing the development tools. But with MacInCloud, those tools were already there.
  2. The remote control was for the most part quite fast.
  3. I used Dropbox and stored my files in a Dropbox folder, so everything I wrote automatically synced to my personal machine.
  4. MacInCloud was the cheapest solution by a long ways. In fact, with the price of a nice Mac laptop, I could pay for MacInCloud’s service for close to two years.

MacInCloud Cons

  1. Well, it is in the cloud, so it has the same con that everything in the cloud has. When my internet was down, I couldn’t use it. My cable modem needed to be reset a few times and one day Comcast’s service was really bad (less that .5 Mb down one day).
  2. I couldn’t get the remote control screen to autofit to the size of my local screen.
  3.  The refresh of the screen wasn’t perfect through remote control. Sometimes I had to move a window to get the contents to refresh.

Would I recommend MacInCloud?

Yes. The con’s didn’t prevent me from getting an A in my iOS course. I would recommend it to anybody.

About 18 months ago, my company had a Mac training and didn’t have enough Macs. This service probably existed and if my company had known about it, we probably would have bought a dozen developers a month or two of service.

iOS – Simple trick to allow typing string instead of NSString

So it drives me crazy to type string in C#, then try to type NSString in objective-c. This is a simple fix and for a while, I didn’t think about it, then it hit me: typedef.

I opened the -Prefix.pch file and added the following line:

typedef NSString string

Yes, it was that easy. Now I can type string instead of NSString.

Objective-c for iOS Cheat Sheet

This Objective-c for iOS Cheat Sheet is written for my midterm for my Masters of Computer Science course on iOS Mobile Development. The class didn’t fill up like I thought it should. Perhaps that has to do with the fact that the class name was misspelled as ISO Mobile Development. Oops.

Creating an objective-c class

  1. All objects should inherit NSObject which is found in Foundation.h.
  2. Objects should be created in the following two files.
#import <Foundation/Foundation.h>
@interface MyObject : NSObject
@end
#import "MyObject.h"
@implementation MyObject
@end

Adding a local variable to an objective-c class

A variable is added to the .h file that is only used by the code in the .m file.

#import <Foundation/Foundation.h>
@interface Person : NSObject
{
    string name;
}
@end
#import "Person.h"
@end

Adding a property to an objective-c class

A property is a short cut for a variable wrapped in a getter and setter.

  1. Add an @property line in the .h file as shown below.
  2. Add an @synthesize line for the property in the .m file as shown below.
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property string name;
@end
#import "Person.h"
@implementation Person 
@synthesize name;
@end

Adding a method to an objective-c class

Here is an example of two methods:

  1. a method without a parameter
  2. a method with two parameters.

In many other languages, these methods signatures would look as follows:

double getPI();
double add(double x, double y);

In ojbective-c, the methods look like this:

#import <Foundation/Foundation.h>
@interface calc: NSObject
-(double)getPI;
-(double)multiply:(double) x and: (double) y;
@end
#import "calc.h"
@implementation calc
-(double)getPI
{
    return 3.14159265359;
}

-(double)multiply:(double) x and: (double) y
{
    return x * y;
}
@end

Now you call the methods different than other languages, too.

double pi = [myCalc getPI];
[myCalc add:1 and: pi;

Overriding the getter for the description property

Add the following method to your .m file. Inheriting NSObject already provides the method signature so nothing needs to be added to the .h file.

-(NSString *)description
{
    return @"Your custom description here";
}

Using NSString stringWithFormat

In many languages you can write a string with tokens inside it and just replace the token. You can do this in objective-c as well.

// cart.items is an integer
return [NSString stringWithFormat:@"You have @d items in your cart.", cart.items];
// cart.total is a double and since it is money, you only want to show
// two characters
return [NSString stringWithFormat:@"Total: %.2f", cart.Total];

Any object that is not a primitive, such as NSString, uses %@.

// account.username is an NSString
return [NSString stringWithFormat:@"Welcome %@", account.username];

Adding a UI Element (Label, TextBox, Button)

  1. You use the UI editor to add an the elements to the UI.
  2. Then you create a variable for each element.
  3. Then you link the field to the element in the xib.
#import <Foundation/Foundation.h>
@interface PersonViewController: UIViewController
{
    IBOutlet UILabel *nameLabel;
    IBOutlet UITextField *nameTextField;
    IBOutlet UIButton *submitNameButton;
}
@end
#import "PersonViewController.h"
@implementation PersonViewController
@end

Notice nothing is in the .m file. Of course, you could add these variables as properties and then you would an @synthesize call for these variables in the .m file.

Adding an event for clicking a button

This is pretty much the same as adding a method to an objective-c class. The only difference is you attach this method to a button in the xib.
Note: The button variable doesn’t really matter, it can by a property or just a member.

#import <Foundation/Foundation.h>
@interface PersonViewController: UIViewController
@property (nonatomic) IBOutlet UIButton *submitNameButton;
-(IBAction)buttonPressed:(id)sender;
@end
#import "PersonViewController.h"
@implementation PersonViewController
-(IBAction)buttonPressed:(id)sender
{
    // Button code here
}
@end

Wrap a ViewController in a UINavigationController

In AppDelegate.m, change the default application method to look as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   
    ViewController *viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController: viewController];
    self.window.rootViewController = navCtrl;
    
    [self.window makeKeyAndVisible];
    return YES;
}

Add Buttons to the top bar (UIBar)

        // Setright bar button
        UIBarButtonItem * rightBarButton = [[UIBarButtonItem alloc]initWithTitle:@"Summary" style:UIBarButtonItemStyleBordered target:self action:@selector(summaryButton:)];
        self.navigationItem.rightBarButtonItem = rightBarButton;
        
        // Set left bar button
        UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithTitle:@"Map" style:UIBarButtonItemStyleBordered target:self action:@selector(mapButton:)];
        self.navigationItem.leftBarButtonItem = leftBarButton;

Launch a ViewController

If you have a UIViewController called MapViewController, you can launch it as follows.

    MapViewController *mapVC = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    [[self navigationController] pushViewController:mapVC animated:YES];

Launch a ViewController and pass it data using a property

This passes a property called database into the SummaryViewController.

    SummaryViewController *summaryVC = [[SummaryViewController alloc] initWithNibName:@"SummaryViewController" bundle:nil];
    summaryVC.database = self.database;
    [[self navigationController] pushViewController:summaryVC animated:YES];

Other ways to pass it a property include:

  1. Using a custom init method such as initWithDatabase.
  2. Using a segue.

Get current date and time as string

NSString* currentTimeAsString()
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"d MMM YYYY, h:mm a"];
    NSString *dateString = [dateFormat stringFromDate:date];
    return dateString;
}

Using a UITabBarController

Change the application method in the AppDelegate.m file.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    UIViewController *mileageView = [[MileageViewController alloc] init];
    UIViewController *mapView = [[MapViewController alloc] init];
    
    NSArray *controllers = [NSArray arrayWithObjects:mileageView, mapView, nil];
    [tabBarController setViewControllers:controllers];
    
    self.window.rootViewController = tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

Add image to TabBarItem

In the ViewController that is added as part of an array to the TabBarItem, override the iniWithNibName method as follows:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        UITabBarItem *tbi = [self tabBarItem];
        tbi.Title = @"Contacts";
        tbi.Image = [UIImage imageNamed:@"Contact-image.png"];
    }
    return self;
}

Map

Change the map view type.
-(IBAction) changeMap
{
    if (mapView.mapType == MKMapTypeStandard)
    {
        mapView.mapType = MKMapTypeSatellite;
    }
    else
    {
        mapView.mapType = MKMapTypeStandard;
    }
}

Update the user location on a map.

-(void)mapView:(MKMapView *)map didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region;
    coord = userLocation.coordinate;
    // Start
    region = MKCoordinateRegionMakeWithDistance(coord, START_LATITUDE_SIZE, START_LONGITUDE_SIZE);
    
    [mapView setRegion:region animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

TextBox resignFirstResponder

How to sort an NSArray

http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayHint

Categories (iOS version of Extension Methods in C#)

If an object is missing a method you think it should just have, such as NSDate returning the date in a specified format, you can simply create that method as follows and then use it anywhere you import the .h file.

#import <Foundation/Foundation.h>
@interface NSDate (DateExtender)
-(NSString *)getDateWithFormat:(NSString *)format;
@end
#import "DateExtender.h"
@implementation NSDate (DateExtender)
-(NSString *)getDateWithFormat:(NSString *)format
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:format];
    return [dateFormat stringFromDate:self];
}
@end

Notice the class name is the same as the object you wish to extend: NSDate.
Notice there is a group name in paranthesis.

UITable

NSTimer

see Notice project.

Use a plist

see car project.

How to write your first C# Unit Test with Visual Studio?

Visual Studio makes Unit Testing easy by bundling a Unit Test framework into it.

Imagine you have a string extension method as shown below and you wanted to unit test it.

using System;

namespace ConsoleApplication1
{
    public static class StringExtensions
    {
        public static bool IsPrimaryColor(this string inString)
        {
            string[] primaryColors = { "Red", "Yellow", "Blue" };
            foreach (var color in primaryColors)
            {
                if (inString.Equals(color, StringComparison.CurrentCultureIgnoreCase))
                    return true;
            }
            return false;
        }
    }
}

Creating a Unit Test project to test this method is very easy.

Step 1 – Create a C# Unit Test Project

  1. In Visual Studio (assuming you already have a project open), click on the Solution and choose Add new project.
  2. Select Templates | Visual C# | Test from the menu on the left.
  3. Select Unit Test Project.
  4. Enter a name for the project.
    Note: Use a good name convention, such as naming the test project the same as the project it tests but with “Tests” at the end.  For example if you have a project called MyProject you would name your test project MyProjectTests. No, it isn’t rocket science. We like to keep it simple.
  5. Click OK.

Step 2 – Give your Unit Test project a reference to the project to test

  1. Right-click on References under the newly created Unit Test project and choose Add reference.
  2. Select Solution from the right.
  3. Add the project you plan to test as a reference.

Step 3 – Create your C# test class and first test method

  1. A test class was already created by default called UnitTest1.cs. Feel free to rename it to an appropriate name.
    Note: Use a good name convention, such as naming the test class the same as the class it tests but with “Tests” at the end.  For example if you have an object called MyObject you would name your test project MyObjectTests.
  2. Add a using statement to reference the namespace of the class you plan to test.
  3. Rename the first Test method. You can’t miss it. It has the [TestMethod] attribute.
    Note: Use a good name convention, such as naming the test method so clearly that you know what it is testing just by the name. For example, StringExtensionIsBlueAPrimaryColorTest().
  4. Add code to make your first test. It is recommended you create your method using the Arrange, Act, Assert pattern.
  5. Add additional test methods as needed.
    using ConsoleApplication1;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace StringExtensionTests
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void StringExtensionIsBlueAPrimaryColorTest()
            {
                // Arrange
                string color = "Blue";
    
                // Act
                bool actual = color.IsPrimaryColor();
    
                // Assert
                const bool expected = true;
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            public void StringExtensionIsRedAPrimaryColorTest()
            {
                // Arrange
                string color = "Red";
    
                // Act
                bool actual = color.IsPrimaryColor();
    
                // Assert
                const bool expected = true;
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            public void StringExtensionIsYellowAPrimaryColorTest()
            {
                // Arrange
                string color = "Yellow";
    
                // Act
                bool actual = color.IsPrimaryColor();
    
                // Assert
                const bool expected = true;
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            public void StringExtensionIsBlackAPrimaryColorTest()
            {
                // Arrange
                string color = "Black";
    
                // Act
                bool actual = color.IsPrimaryColor();
    
                // Assert
                const bool expected = false;
                Assert.AreEqual(expected, actual);
            }
        }
    }
    

You have now created your first Unit Test. Go ahead and run it. You should be able to run it in Visual Studio starting with VS 2012. If you have an earlier version, you can run tests using other tools.

Thorough Unit Testing

OK. Now let’s think about what tests would be valid that we don’t have? Here are a few:

  • Case insensitive. All the following strings should return true: Red, red, rEd.
  • What if the string is blank? Null? Junk characters?

Now you write additional unit tests to test this method.

Note: It is too bad that Visual Studio’s MSTest doesn’t support Row tests. NUnit does support Row tests. With Row tests, the above Unit Test code would involve a single method that passing in multiple string values.