Image Image Image Image Image
Scroll to Top

To Top

Clean Code Developer

22

Okt
2015

Keine Kommentare

inAngularJS
Clean Code Developer

vonJohannes Hoppe

Neues Video: JavaScript Unit- und Oberflächentests mit Karma & Protractor

On 22, Okt 2015 | Keine Kommentare | inAngularJS, Clean Code Developer | vonJohannes Hoppe

thumbnail_dwx15_karma_protractor

Dieser Vortrag wurde am 15.06.2015 bei der Developer Week 2015 aufgenommen.

Sauberer Code und Test Driven Development (TDD) sind die Grundlage für eine gute Architektur. Durch automatisierte Tests lässt sich sicherstellen, dass die Software fehlerfrei funktioniert und die fachlichen Spezifikationen erfüllt sind. In diesem Vortrag wird der Test-Runner Karmavorgestellt, mit welchem Unit-Test für JavaScript Anwendungen erstellt werden können. Zum Einsatz wird das BDD-Framework Jasmine kommen. Oberflächentests sind eine gute Ergänzung zu Unit-Tests, denn mit ihnen lässt sich die Anwendung aus der Sicht des Anwenders überprüfen. Hierfür wird Protractor beleuchtet, welcher auf Basis von Selenium End-To-End-Tests von JavaScript-Anwendungen und speziell von AngularJS-Anwendungen ermöglicht.

Weiterlesen…

xCutting – AOP bei der .NET User Group Niederrhein – Video, Slides & Download

Johannes Hoppe spricht von seiner Sicht über Clean-Code und die Grenzen von objektorientierter Programmierung bei der .NET User Group Niederrhein. Anhand praktischer Bespiele zeigt er, wie man mit dem AOP-Framework Postsharp elegante Modularisierungsansätze erhält. Der Vortrag richtet sich an interessierte Einsteiger in das Thema Aspektorientierte Programmierung (AOP) mit .NET.

Alle relevanten Code-Fragmente sind weiter unten aufgelistet!

  1. ActionResult Edit
  2. MyConvertExeption
  3. LogTimeAspect
  4. SimpleCacheBaseAspect


Hier sind alle Code-Fragmente aus dem Video:

ActionResult Edit

[HandleError(ExceptionType = typeof(MyException))]
[AcceptVerbs(HttpVerbs.Post)]
[MyConvertExeption]
public ActionResult Edit(Note noteToEdit, int[] newCategories)
{
    NoteWithCategories changedNote = this.WebNoteService.Update(noteToEdit, newCategories);
    return View(changedNote);
}


MyConvertExeption

using PostSharp.Aspects;
 
[Serializable]
public class MyConvertExeption : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        throw new MyException("Fehler", args.Exception);
    }
}

LogTimeAspect

namespace PostsharpAspects.Logging
{
    using System;
    using System.Diagnostics;
    using System.Reflection;
 
    using NLog;
 
    using PostSharp.Aspects;
    using PostSharp.Aspects.Dependencies;
 
    [Serializable]
    [ProvideAspectRole(StandardRoles.PerformanceInstrumentation)]
    [AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, StandardRoles.Caching)]
    [AspectRoleDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, StandardRoles.ExceptionHandling)]
    [AspectRoleDependency(AspectDependencyAction.Commute, StandardRoles.PerformanceInstrumentation)]
    public class LogTimeAspect : OnMethodBoundaryAspect
    {
        private const int SlowTotalMilliseconds = 250;
 
        private static readonly Logger Logger = LogManager.GetLogger("LogTimeAspect");
        private static readonly Stopwatch Stopwatch = new Stopwatch();
        private string instanceName;
 
        static LogTimeAspect()
        {
            Stopwatch.Start();
        }
 
        /// <summary>
        /// Method executed at build time.
        /// </summary>
        public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
        {
            this.instanceName = method.DeclaringType.FullName + "." + method.Name;
        }
 
        /// <summary>
        /// Saves the time method start
        /// </summary>
        [DebuggerStepThrough]
        public override void OnEntry(MethodExecutionArgs args)
        {
            args.MethodExecutionTag = Stopwatch.ElapsedTicks;
        }
 
        /// <summary>
        /// Stops the time on method end
        /// </summary>
        [DebuggerStepThrough]
        public override void OnExit(MethodExecutionArgs args)
        {
            long timeInTicks = Stopwatch.ElapsedTicks - (long)args.MethodExecutionTag;
            double totalMilliseconds = TimeSpan.FromTicks(timeInTicks).TotalMilliseconds;
 
            if (totalMilliseconds > SlowTotalMilliseconds)
            {
                Logger.Trace(String.Format("{0}ms\t- {1}", totalMilliseconds, this.instanceName));
            }
 
            base.OnExit(args);
        }
    }
}

SimpleCacheBaseAspect

namespace PostsharpAspects.Caching
{
    using System;
    using System.Reflection;
    using System.Text;
 
    using PostSharp.Aspects;
 
    using PostsharpAspects.Caching.CacheImplementation;
 
    [Serializable]
    public class SimpleCacheBaseAspect : OnMethodBoundaryAspect
    {
        protected ICache Cache { get; set; }
 
        public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
        {
            string prefix = method.DeclaringType.ToString();
            this.Cache = new Cache(prefix);
        }
 
        public override void OnEntry(MethodExecutionArgs args)
        {
            string cacheKey = GenerateCacheKey(args);
            object value = this.Cache.Get(cacheKey);
 
            if (value == null)
            {
                args.MethodExecutionTag = cacheKey;
                return;
            }
 
            args.ReturnValue = value;
            args.FlowBehavior = FlowBehavior.Return;
        }
 
        public override void OnSuccess(MethodExecutionArgs args)
        {
            string cacheKey = (string)args.MethodExecutionTag;
            this.Cache.Insert(cacheKey, args.ReturnValue);
        }
 
        protected static string GenerateCacheKey(MethodExecutionArgs args)
        {
            StringBuilder stringBuilder = new StringBuilder();
 
            for (int i = 0; i < args.Arguments.Count; i++)
            {
                if (i > 0)
                {
                    stringBuilder.Append("|");
                }
 
                stringBuilder.AppendFormat(
                    "{0}_{1}",
                    args.Method.GetParameters()[i].Name,
                    args.Arguments.GetArgument(i) ?? "null");
            }
 
            return stringBuilder.ToString();
        }
    }
}

Tags | ,

New Home for the ADO.NET Unit Testable Repository Generator

I created a project page for the
ADO.NET Unit Testable Repository Generator at
http://repositorygenerator.codeplex.com/.

You want to contribute?

Then welcome to the party! 😎
I would be happy to see your patches, your feedback or maybe even some more documentation! :roll:

Here are all resources that were published so far:

Let us welcome Rohan Cragg as the first contributor to the project!
(he found a bug where broken code was generated)

@All people who keep this project active:
Thank you very much!


Tags | , , , , , ,

Unity Application Block: Event Broker with ASP.NET MVC

For my colleagues at work I evaluated the Simple Event Broker from the Patterns and Practices team. In my opinion this extension is a very valuable piece of software!

To learn more about the Event Broker, you should read:

I made a small sample solution, based on my “WebNoteMvc” project.

The scenario is easy: I want my repositories (or services) to be loosely coupled. In my database foreign references are used. So before I delete data from one repository other repositories should get a notice. The related repositories are now forced to delete their own related data from the DB to keep the data integrity.

Tags |

Update: ADO.NET Unit Testable Repository Generator v0.5

I released version 0.5 of the
ADO.NET Unit Testable Repository Generator„.
In a short time the download counter reached 900. W00t! :mrgreen:

This encouraged me to bring up an improved version. It now simplifies Unit Tests by implementing “Equals”. Additionally, the dependency to Microsoft Unity is now optional.

All resources were updated:

Thank you!

Tags | , , , , , ,

Walkthrough: ADO.NET Unit Testable Repository Generator

This walkthrough is going to show you the usage of my new T4 template called „ADO.NET Unit Testable Repository Generator“.

Table of contents:

My demo implements a small repository to manage simple text-snippeds in the database. I will start with an empty ASP.NET MVC 2 project. Any other type would work, too.


Tags | , , , , , ,

ADO.NET Unit Testable Repository Generator

At work we are going to do a big refactoring on a ASP.NET MVC project. I learned a lot of this project. One hard lesson was: the code base is as good is the guidance of the senior coders. If you know the power of the Entity Framework, then you also know the countless possibilities to write wicked code. But I’m present at the office only for days a week. That’s why I’m planning to write some articles in the next time.

Tags | , , , , , ,