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.


PC-BSD 10 now available

PC-BSD 10.0-RELEASE is now available for download!

10.0-RELEASE notable features

  • Includes FreeBSD 10.0-RELEASE
  • Updated KMS / AMD driver support
  • ISO file is a hybrid USB file, and can be “dd“ed to a USB media.
  • New text-based installer
  • Able to select between GRUB/BSD loaders during installation
  • New desktops! Gnome 3, Mate (Replaces Gnome2) and Cinnamon

Read More . . .


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.


How to query a SQL database in C# using TableAdapters

Visual Studio has some great features to help you access the database and create objects for your database. You could manually create a connection string and manually create objects that represent the data in your database described here: How to query a SQL database in C#?. This article can show you how Visual Studio can do this for you.

So how is it done? By adding a Data Source.

Imagine you have a simple database for authentication with these tables:

User
- Id INT AUTOINCREMENT
- UserName VARCHAR(100)
- Password VARCHAR(MAX)
- Salt VARCHAR(MAX)

Person
- Id INT AUTOINCREMENT
- FirstName VARCHAR(255)
- LastName VARCHAR(255)
- Birthdate DATETIME
- UserId int FK to User.Id

Now imagine that you want to query these tables and use the data in your application.

Step 1 – Create a Visual Studio Project

  1. In visual studio create a new C# Console Application project.
  2. Once you have the project created, click on Project | Add New Data Source.
  3. Select Database and click Next.
  4. Select DataSet and click Next.
  5. Click New Connection and follow the wizard to connect to your database.
  6. Make sure that Yes, save the connection as is checked and give your saved connection a name and click Next.
  7. Click the checkbox next to Tables and click Finish.

This adds the following files to your project (the names might be slightly different on yours):

  • AuthDataSet.xsd
  • AuthDataSet.Designer.cs
  • AuthDataSet.xsc
  • AuthDataSet.xss

This code will add table adapters to your project. This basically does a lot of work for you and can save you a lot of potential development time.

Step 2 – Query a SQL Database using the Table Adapter

Now you can get the data from either of your tables with one line of code:

using System;
using System.Data;
using TableAdapterExample.AuthDataSetTableAdapters;

namespace TableAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Query the database (select * from Person) into a DataTable
            AuthDataSet.PersonDataTable table = new PersonTableAdapter().GetData();

            // Print out the table as proof.
            PrintDataTable(table);
        }

        /// How to print a DataTable
        private static void PrintDataTable(AuthDataSet.PersonDataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn col in table.Columns)
                {
                    Console.Write(row[col].ToString().Trim() + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

Hope that helps you.


ASP.NET, JavaScript, and HTML Element ID attributes

Today I had to fix some legacy code. It is ASP.NET code and it has both ASP.NET elements and ASP.NET Controls. The plan was to replace a large portion of code behind with JavaScript. The ASP.NET code needed to be a UserControl that could appear twice on the same page. This created some problems:

  1. ASP.NET creates some html controls but changes the id and the name attributes. While it is possible to run the web page and see what the attributes will be changed to and then use those strings statically in JavaScript, the JavaScript could easily break with slight changes to the ASP.NET code. This is not scalable or maintainable.
  2. ASP.NET does NOT rename the the id or the name attributes for normal HTML tags. First, that is a consistency issue. Second it is an issue using the same control multiple times. Third, if you want to get the value of a form element, doing so uses the name attribute and so each form element needs a separate name.

So lets explain the is problem with a real world scenario.

Lets say you have the following requirements:

  1. Create a UserControl, called PersonControl, that accepts person’s basic info: First name, Last name, and Birthdate.
  2. The form also has a button and it should only be enabled if all three fields are populated.
  3. The Birthdate should use JQuery’s DateTimePicker.
  4. The First name and Last name should be ASP.NET text boxes.

Now imagine the site already exists and you have to add this requirement:

  1. A web page should exist that has multiple PersonControls showing: for example: Employee, Emergency Contact.

The problem with ASP.NET, JavaScript, and HTML Element ID attributes

So let’s build this project using a single control and static id and name attributes and see how it works. Later we will see what we need to do to get this working with multiple PersonControls.

  1. Open Visual Studio and create a new ASP.NET Empty Web Application.
  2. Add JQuery and JQuery-UI. Do this as follows:
    1. Right-click on the project and choose Manage NuGet Packages.
    2. In the Manage NuGet Packages window, on the left, click Online.
    3. On the right, in the search field, type JQuery.
    4. Install JQuery and JQuery UI.
  3. Create new Web Form called PersonForm.
  4. Add the following into your PersonForm.aspx file:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PersonForm.aspx.cs" Inherits="AspAndJavaScriptExample.PersonForm" %>
    
    <%@ Register Src="~/PersonControl.ascx" TagPrefix="uc1" TagName="PersonControl" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>ASP.NET, JavaScript, and HTML id Attributes</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <h2>Employee</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
            </div>
            <%--<div>
                <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
            </div>--%>
        </form>
    </body>
    </html>
    
  5. Create a new Web User Control called PersonControl.
  6. Add the following into your PersonControl.ascx file:
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PersonControl.ascx.cs" Inherits="AspAndJavaScriptExample.PersonControl" %>
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PersonControl.ascx.cs" Inherits="AspAndJavaScriptExample.PersonControl" %>
    <link href="Content/themes/base/minified/jquery.ui.datepicker.min.css" rel="stylesheet" />
    <script src="scripts/jquery-2.0.0.min.js"></script>
    <script src="scripts/jquery-ui-1.10.3.min.js"></script>
    <script src="scripts/ButtonManager.js"></script>
    <script>
        $(function () {
            $(".datepicker").datepicker();
        });
    </script>
    
    <div style="border: solid; padding: 2px">
        First name:
        <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
        Last name:
        <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br />
        Birthdate:
        <input type="text" name="BirthDate" id="BirthDate" class="datepicker" /><br />
        <asp:Button ID="SubmitPerson" runat="server" Text="Submit" OnClick="SubmitPerson_Click" />
    </div>
    
  7. Add the following button SubmitPerson_Click method into your PersonControl.ascx file:
            protected void SubmitPerson_Click(object sender, EventArgs e)
            {   // Put break point here            
                var firstName = FirstName.Text;
                var laststName = LastName.Text;
                var birthdate = Request.Form["Birthdate"];
            }
    
  8. Now add this ButtonManager.js file.
    jQuery(document).ready(function () { 
        $("#PersonControlEmployee_FirstName").bind("propertychange keyup input paste", setButtonState);
        $("#PersonControlEmployee_LastName").bind("propertychange keyup input paste", setButtonState);
        $("#BirthDate").change(setButtonState);
        setButtonState();
    });
    
    var setButtonState = function () {
        if (!areValuesPopulated())
            $("#PersonControlEmployee_SubmitPerson").attr("disabled", "disabled");
        else
            $("#PersonControlEmployee_SubmitPerson").removeAttr("disabled");
    }
    
    var areValuesPopulated = function () {
        return $("#PersonControlEmployee_FirstName").val() != ""
             && $("#PersonControlEmployee_LastName").val() != ""
             && $("#BirthDate").datepicker().val() != "";
    }
    
  9. Now run the project and look at the source code of the html. It looks as follows:
    
    
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>
    	ASP.NET, JavaScript, and HTML id Attributes
    </title></head>
    <body>
        <form method="post" action="PersonForm.aspx" id="form1">
    <div class="aspNetHidden">
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="nkizDAjcAtd96A9EOpli0xdG3n6zTXVaM/5t2fmcAI5+LPQ6OzzIV2wUpisxoUTMFxIKkUwKDY4Xk36/NouRsiE81gq5z3Ch/tz3DlxJW9g=" />
    </div>
    
    <div class="aspNetHidden">
    
    	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="XCB0fxwKvdqEXpUBaICUtf6EzkAvBeahq0bywZekyukCuzvGVagqOnVHUWFHF2Cycd2xkg/UhNh/B3qNqabkBI+Flj52GkM3p6SF5eL/M4SnnfwmFBjWVOaTZ+IlwMvkR1bGuMxomyeJJ5HaU1FXWSYDYHVtgM9tdsVi31EireM=" />
    </div>
            <div>
                <h2>Employee</h2>
                
    <link href="Content/themes/base/minified/jquery.ui.datepicker.min.css" rel="stylesheet" />
    <script src="scripts/jquery-2.0.0.min.js"></script>
    <script src="scripts/jquery-ui-1.10.3.min.js"></script>
    <script src="scripts/ButtonManager.js"></script>
    <script>
        $(function () {
            $(".datepicker").datepicker();
        });
    </script>
    
    <div style="border: solid; padding: 2px">
        First name:
        <input name="PersonControlEmployee$FirstName" type="text" id="PersonControlEmployee_FirstName" /><br />
        Last name:
        <input name="PersonControlEmployee$LastName" type="text" id="PersonControlEmployee_LastName" /><br />
        Birthdate:
        <input type="text" name="BirthDate" id="BirthDate" class="datepicker" /><br />
        <input type="submit" name="PersonControlEmployee$SubmitPerson" value="Submit" id="PersonControlEmployee_SubmitPerson" />
    </div>
    
            </div>
            
        </form>
    </body>
    </html>
    

Problems

  1. Notice the id and name attributes on the tags. The ASP.NET controls have been altered by ASP.NET with a prefix. This is not the problem. This is good. If the control is used multiple times, then this keeps the id and name attributes unique and they are supposed to be unique. However, the problem is, if the id is changed in this line . . .
    <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
    

    . . . then id and name attributes in the child control will change. Since we are using those values statically in the ManageButton.js, any such change also breaks in the javascript. Also, we aren’t using a master page, but if you decided to add a master page, that add an additional prefix, which would create different id and name attributes, again causing the javascript to break. In fact, any such nesting change will change the id and name attributes breaking the javascript.

  2. The control that is not an ASP.NET control, the JQuery datepicker control, did not have the same modifications made to the Birthdate. So this tag won’t work if the control is used multiple times.

Do you want to see the problem?

Update your form in PersonForm.aspx to include multiple controls.

    <form id="form1" runat="server">
        <div>
            <h2>Employee</h2>
            <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
        </div>
        <div>
            <h2>Emergency Contact</h2>
            <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
        </div>
    </form>

Now give it try. See the problems? Ok. So now you have a simulation of the problematic code that I faced today.

Solution to ASP.NET, JavaScript, and HTML Element ID attributes

So we are going to fix this in parts. We are going to use a variable in the ASP.NET control called ClientID, that is basically the prefix used.

  1. Fix html elements to use the same prefix as the ASP.NET controls
  2. Fix the javascript to receive the ClientID as a parameter
  3. Fix the datepicker attributes

    First, let’s fix the ASP.NET and HTML so that all the id and name attributes are consistently changed.

    Change the datepicker line and add some code so it will have the same prefix as ASP.NET created html controls.

    <input type="text" name="<%=ClientID%>$BirthDate" id="<%=ClientID%>_BirthDate" class="datepicker" /><br />
    

    Pass the prefix into the JavaScript

    1. In the PersonControl.ascx file, add a little snippet of JavaScript code to pass the ClientID into the JavaScript files.
      <script>
          $(function () {
              $(".datepicker").datepicker();
          });
          jQuery(document).ready(function () {
              startManagingButton("<%=ClientID%>");
          });
      </script>
      
    2. Now update your JavaScript file to use that ClientID as the prefix. Notice, this is used in the events. I created a simple buildId method that I use throughout now.
      var startManagingButton = function (inIdPrefix) {
          $(buildId(inIdPrefix, "_FirstName")).bind("propertychange keyup input paste", inIdPrefix, setButtonState);
          $(buildId(inIdPrefix, "_LastName")).bind("propertychange keyup input paste", inIdPrefix, setButtonState);
          $(buildId(inIdPrefix, "_BirthDate")).change(inIdPrefix, setButtonState);
          setButtonState(inIdPrefix);
      }
      
      var setButtonState = function (inIdPrefix) {
          if (inIdPrefix.data)
              inIdPrefix = inIdPrefix.data;
          
          if ($(buildId(inIdPrefix, "_FirstName")).val() == "" || $(buildId(inIdPrefix, "_LastName")).val() == "" || $(buildId(inIdPrefix, "_BirthDate")).val() == "")
              $(buildId(inIdPrefix, "_SubmitPerson")).attr("disabled", "disabled");
          else
              $(buildId(inIdPrefix, "_SubmitPerson")).removeAttr("disabled");
      };
      
      var buildId = function (inIdPrefix, idSuffix) {
          return "#" + inIdPrefix + idSuffix;
      };
      

      Now no matter how you update or move this web page, the Id values always work.

    Use the ClientID in ASP.NET SubmitPerson_Click method

    Update the code to look as follows:

        protected void SubmitPerson_Click(object sender, EventArgs e)
        {   // Put break point here            
            var firstName = FirstName.Text;
            var laststName = LastName.Text;
            var birthdate = Request.Form[ClientID + "$Birthdate"];
        }
    

    Using the PersonControl multiple times

    Now everything should be working and you should be able to include as many instances of your control in your web page as you want.

    Update your form in PersonForm.aspx to include many of these controls.

        <form id="form1" runat="server">
            <div>
                <h2>Employee</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmployee" />
            </div>
            <div>
                <h2>Spouse</h2>
                <uc1:PersonControl runat="server" ID="PersonControlSpouse" />
            </div>
            <div>
                <h2>Emergency Contact</h2>
                <uc1:PersonControl runat="server" ID="PersonControlEmergencyContact" />
            </div>
        </form>
    

    Now give it try. All instances of the PersonControl are now working. The dynamic id and name attributes are not a problem as we are handling them; in fact, they are part of the ultimate solution to make the control reusable.

    Conclusion

    ASP.NET, JavaScript, and HTML Element ID attributes can all be used to work together to make a nice cohesive application.

    If you have a better solution, please post a comment and let me know.

    Downloads

    Here is the project in both states:

    AspAndJavaScriptExample-problematic.zip

    AspAndJavaScriptExample-working.zip

    Bugs

    Now the only bug I can find is on clicking submit the JQuery datepicker field is cleared. I’ll try to fix that and post the solution in another post.


How to create an excel spreadsheet with C#?

I needed to create an Excel spread sheet in C# and I didn’t want to reinvent the wheel.

I found this awesome project: https://closedxml.codeplex.com

I already had a DataTable that I wanted to export in ASP.NET to an Excel file and download. I created an extension method for the DataTable.

    public static class CloseXMLHelper
    {
        public static XLWorkbook ToExcel(this DataTable inDataTable)
        {
            var wb = new XLWorkbook();
            var dataTable = inDataTable;

            // Add a DataTable as a worksheet
            wb.Worksheets.Add(dataTable);
            return wb;
        }
    }

Then I just followed the documentation on the project for allowing a user to download the excel file. I already had the myDataTable variable in the below snippet. If you are wondering how to create a DataTable from a database, see this post: How to query a SQL database in C#?

    var httpResponse = Response;
    httpResponse.Clear();
    httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    httpResponse.AddHeader("content-disposition", "attachment;filename=\"HelloWorld.xlsx\"");

    // Flush the workbook to the Response.OutputStream
    using (var memoryStream = new MemoryStream())
    {
        dataset.Tables[0].ToExcel().SaveAs(memoryStream);
        memoryStream.WriteTo(httpResponse.OutputStream);
        memoryStream.Close();
    }

    httpResponse.End();

It doesn’t get much more simple than this.