Switch config files

If you ever find yourself changing configuration settings you might want to try this. Copy – paste the code into console app, not going into detail should be simple enough.

Capture
private static KeyValueConfigurationCollection GetAppSettingsFromPath(string path)
        { 
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = path };
            Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            if ((newConfiguration.AppSettings == null) || (newConfiguration.AppSettings.Settings == null))
                return null;

            return newConfiguration.AppSettings.Settings; ;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(System.Environment.MachineName);

            var pathToConfigFile = Path.Combine(Environment.CurrentDirectory, "Configs");
            var fullPath = Path.Combine(pathToConfigFile, System.Environment.MachineName + ".config");

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appsettings = config.AppSettings;

            Console.WriteLine("Original Value: " + config.AppSettings.Settings["Connection"].Value.ToString());

            if ((appsettings != null) && (appsettings.Settings != null))
            {
                appsettings.Settings.Clear();
                foreach (KeyValueConfigurationElement keyValueConfigurationElement in GetAppSettingsFromPath(fullPath))
                {
                    appsettings.Settings.Add(keyValueConfigurationElement);
                }
                config.Save(ConfigurationSaveMode.Full);
                ConfigurationManager.RefreshSection("appSettings");
            }

            Configuration config_new = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Console.WriteLine("New Value: " + config_new.AppSettings.Settings["Connection"].Value.ToString());

            Console.ReadLine();
        }

End User training – MOOC.org

End User training

One of the key factors in a successful business solution is the training of the end-user.
The topic of training has been around for thousands of years and many companies has pinned it down to an art form, but in practice I still find that many companies get it wrong. I think one issue with modern day training is, there’s no exams after training and end-users end up using the solutions without being qualified.
Back to basic, I think companies taking a more classic and formal approach will succeed in training. Training must be concluded with an exam and all user should get a certification or some other type of informal (or formal) qualification. This will allow them to use the system (software)

I think MOOC (http://mooc.org/) is one of many innovations out there that can assist in this process.

Ask yourself; can your personal assistant drive the forklift in the warehouse? Yes, BUT she or he needs to get trained and qualified. Why is “driving” software any different?

http://mooc.org/

logo-mooc-temporary

Sketching

I think theirs allot of value in using pen and paper, Lately I spent more time in my sketch books then on my laptop. From making notes to sketching big complex systems and UI designs. Its a easy way to visually show something to someone in a format that is easy to change and re-do without getting caught up in the tool.

One tool I do like, for its simplicity and eas of use is Balsamiq. Go take a look http://www.balsamiq.com.

IMG_20131008_104920

IMG_20131008_104840

IMG_20131008_105033

IMG_20131008_104954

Download Standalone Visual Studio Updates

Lately most downloads for updates are web-installers, meaning you download a file that will download the required files and install the update. The problem comes when you want to share the update in a team of people or when you need to re-install, you need to download the files again seeing that you don’t have the standalone files. Some updates come with the option to download the standalone package, but not all updates give you that option. Heres a workaround for the visual studio 2012 updates, maybe you can do the same with previous version of visual studio or even other Microsoft products.

The latest VS 2012 Update 4 RC.
Download the web-installer version of the file. http://www.microsoft.com/en-us/download/details.aspx?id=40263
Open command prompt and change your directory to the path of where the file is allocated.
Run VS2012.4.exe /layout

Capture

Once you run the command it should ask you for a location to download the files.

Identity, Domain Entities – NHibernate Implementation

If you don’t get the blog entry name, STOP reading.
This is an example of a DomainEntity base class, implemented with NHibernate.

The contract, yes we are OO developers so we start with the interface class.

  
public interface IEntity
    {
        long ID { get; set; }
        Guid Guid { get; set; }
    }

The Base Implementation:

    public class EntityBase : IEntity
    {
        /// 
        /// Database Primary key 
        /// 
        public virtual long ID { get; set; }

        /// 
        /// Identifier
        /// 
        public virtual Guid Identifier { get; set; }
    }

Ok, at this stage you are properly wondering why I have an ID of long and an Identifier as a GUID.The purpose of the ID is purely database related, this is the primary key, use for indexing. The identifier is the unique identifier for the record. This is handy when you move or recreate the database, you can drop all ID’s and keep the record identifier.

The following class are used by all Entity related mapping classes.

  public static class BaseMap
      where T : IEntity
    {
        public static void MapID(ClassMap classMap)
        {
            classMap.Id(x => x.ID);
            classMap.Map(x => x.Guid).Not.Nullable();
        }
    }

This is a simple Contact Entity using the Entity as its base class.

public class Contact : EntityBase
    {
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual string Mobile { get; set; }
        public virtual string PrivateTelephone { get; set; }
        public virtual string BusinessTelephone { get; set; }
        public virtual string Fax { get; set; }
        public virtual string EMail { get; set; }
    }

Lastly your NHibernate map class. Note the use of the static basemap class.

public class ContactMapping : ClassMap
    {
        public ContactMapping()
        {
            BaseMap.MapID(this);
            Map(x => x.FirstName).CustomSqlType("nvarchar(50)");
            Map(x => x.LastName).CustomSqlType("nvarchar(50)");
            Map(x => x.Mobile).CustomSqlType("nvarchar(22)");
            Map(x => x.PrivateTelephone).CustomSqlType("nvarchar(22)");
            Map(x => x.BusinessTelephone).CustomSqlType("nvarchar(22)");
            Map(x => x.Fax).CustomSqlType("nvarchar(22)");
            Map(x => x.EMail).CustomSqlType("nvarchar(50)");
        }
    }

Easy, ok I know I did not explain allot or go into too much detail, but if your confused you need to start from scratch. I recommend the following as starting points, followed by books on the topics and years of practice. Lastly good luck and enjoy the journey to the holy land of coding paradise.
Links:
http://en.wikipedia.org/wiki/Design_Patterns
http://en.wikipedia.org/wiki/Domain-driven_design

C# pattern – deleting historical data

The pattern (guideline) I want to share are based on NHibernate, but you can obviously use any ORM or no ORM as long as you have a base class that handles your CRUD methods.

Scenario, most business applications handles allot of history or transactions. This prevents you from deleting data. The way to overcome the problem is to have some kind of property to flag records that’s “deleted”. This pattern will help you to ensure the logic is followed and not have to re-use logic all over the application.

public interface IActivatable
    {
        bool isActive { get; set; }
    }

All classes that needs to adhere to the logic need to implement the interface.

public class Location : IActivatable
    {
        public virtual string Name { get; set; }
        // IActivatable
        public virtual bool isActive { get; set; }
    }

Lastly your base class or repository will have one method taking care of the delete.

This is where the method will check the class and decide if it should delete it or just update the flag.

public virtual void Delete(object Entity)
        {
            try
            {
                OpenSession();
                this.Session.BeginTransaction();

                if (Entity is IActivatable)
                {
                    //flag isActive
                    ((IActivatable)Entity).isActive = false;
                    this.Session.SaveOrUpdate(Entity);
                }
                else
                {
                    this.Session.Delete(Entity);
                }
                this.Session.Transaction.Commit();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally { CloseSession(); }
        }

When you use this approach, you can then always filter data by the property isActive to ensure you don’t return “deleted” records, but still have the history belonging to the data.

You can always use the same approach to your get methods to automatically filter based on the class.

The same pattern can be used for similar scenarios where you want to enforce certain logic on a higher level. Think about a scenario where you want to audit records/data, this can be accomplished the same way but by checking the type on the save method and ensuring you populate the audit user and date properties of the record before committing the save. I think this is a common pattern and will be searching the net to see if someone has given it a name.

TDD

This is a copied and paste email that was going around between myself and cradle developers
on the topic of TDD. Read it bottom up.
my advice stop reading books or searching for tools, test is simple and very easy.
heres my 101:

  • create new project and reference all the necessary projects
  • create solution you specify VS test
  • create a class within project per area you wan to test.
  • give test meaningful name, work very neat
  • do select statements to get to data that will be used to test
    • example
    • do select to get a location to test against (top(1) of valid location)
    • get first valid trackingentity
    • ect.
  • call the methods you want to test
  • test the result

some tips:

  • use try catch in test, if exception use a fail assert instead of a exception
  • check your select statement result. if on the specific database you cannot find say valid location, check if null in code if so, use Assert.Inconclusive, meaning your test cannot run instead of fail.

Brian if its a custom project you can hard code some of the values that will never change.
Start by creating solution and adding what you busy with in, then create your skeleton around it, base class for test to
do generic things.

its the best feeling if you know your tests are solid, you run and you see result 28 tests passed (remember for granite i’m running same test against 5 clients db), its instant acknowledgement
that your code is solid you can go out tonight get pissed and forget about your code at home its solid, add more tests more acknowledgement,
its the only way for me moving forward else I’ll freak out, how can you be in control of all the code we’ve done without this.

the next phase in my plan is to use a tool that can tell me what my code coverage is, it tells you this code is
covered by a test and this code not. so at least you know in a more less percentage what part of application is covered.

again make sure your test are meaningful and generic else you wasting time, my first attempt was frustrating because it feels
like you have to maintain your tests and it becomes more work

heres my code


On 10/19/2012 11:01 AM, Brian Henning wrote:

HI Dude
I serously neeed to get into HDD any recommended sites or reading ?
Updates and testing changes and new requirements is driving me batty
Regards
Brian
On Fri, Oct 19, 2012 at 1:23 AM, Francois Taljaard <francoist@cradle.co.za> wrote:

o ja last thought.

it forces you to structure and design code,
at this stage its very difficult to test ui, so you start as close as possible to
your UI, the webservice or some façade class that you have.
the reason for that is to test through all layers of code not only the business logic.
now i ask you picture a function lets say create/takeon label, what class will you test
and if you test that class will it cover firstly all business logic and logic behind it with
the exclusion of your UI gears code. do you have any “if”/”loop”/’switch” statements
in your UI code thats actually business logic. Ettie if you think that “if” in your code
is not business logic then you making a big mistake:-) there might be
a enterprise pattern that deals with it very elegantly.

food for thought, have a good weekend Cow Boys

On 10/19/2012 9:56 AM, Francois Taljaard wrote:

hi, just want to share something about TDD

busy writing test for my code, first thing your test should drive your design
believe me it makes designing code very structured and to the point, with very little bugs or confusing.
I’m busy catching up on tests, i started with writing generic test this means the values I’m passing on
is actually “select” from the database instead of hard coded values. (if done that way you dont have to maintain your test
it will execute against any database)
that was first step, got one or
two done per domainModel. import note, if your result comes back, validate every transcation/value of the result every time.
meaning if I’m doing move I validate the entities state (new location), then I validate each value in the transaction
created (entity id, from-to location, ect.).
I’ve already found small bugs I would have never picked up with normal tests or customer feedback.
third step in process (very important) refactor tests, meaning, create base class for commons (connection to db, validate user method, ect)
then structure code, each test class must have a transaction entity (declare private), each class must have method
called validate transaction, this makes a worlds difference, once you setup the skeleton adding tests become very simple with
the insurance that the test is actually validating everything.

moving forward, is a hard habit to adapt, but if a call comes in for a bug found, I look at the test that should validate,
if i dont find a test I create one to have the same result and then I fix code. same goes for new function start with the test
ask yourself if the test covers the function if yes continue to make the test pass.

last thought, its like going to gym we know we should there might be individual in this world that
will tell you gyming is wrong, but its a clear known out there. same goes for tests, the people that still argue
the fact that tests is not necessary is few and cow-boys.
but getting into the habit of gyming is one of the hardest things ever.