Sunday, January 1, 2017

Dependency Injection

Dependency Injection

Advantages of Dependency Injection:
  • ·         Reduces class coupling
  • ·         Increases code reusing
  • ·         Improves code maintainability
  • ·         Improves application testing


Popular DI containers?

Castle Windsor

·         Based on the Castle MicroKernel.
·         Well documented and used by many.
·         Understands Decorator
·         Typed factories
·         Commercial support available

Spring.NET

·         INTERCEPTION
·         Comprehensive documentation
·         Commercial support available

Autofac

·         Easy to learn API
·         second-generation DI Container
·         Commercial support available

Unity

·         INTERCEPTION
·         Good documentation
·         Consistent API

Ninject

·         Easy to learn API
·         Second-generation DI Container

Implementation of Dependency Injection Pattern in C#

Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.

Constructor Injection


public interface IService
    {
        void Serve();
    }

    public class Service : IService
    {
        public void Serve()
        {
            Console.WriteLine("Service Called");
        }
    }

    public class Client
    {
        private IService _service;

        public Client(IService service)
        {
            _service = service;
        }

        public void Start()
        {
            _service.Serve();
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Client client = new Client(new Service());
            client.Start();
        }
    }

Property injection


public interface IService
    {
        void Serve();
    }

    public class Service : IService
    {
        public void Serve()
        {
            Console.WriteLine("Service Called");
        }
    }

    public class Client
    {
        private IService _service;

        public IService Service
        {
            set
            {
                _service = value;
            }
        }

        public void Start()
        {
            _service.Serve();
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Client client = new Client();
            client.Service = new Service();
            client.Start();
        }
    }

Method injection

public interface IService
    {
        void Serve();
    }

    public class Service : IService
    {
        public void Serve()
        {
            Console.WriteLine("Service Called");
        }
    }

    public class Client
    {
        private IService _service;

        public void Start(IService service)
        {
            _service = service;
            _service.Serve();
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Client client = new Client();
            client.Start(new Service());
        }
    }



Wednesday, December 14, 2016

Running Code Analysis and StyleCop on build

If you are programming in .Net best choice is to follow .Net coding standard which MS uses internally. This coding standard is documented in a book Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries and later also on MSDN. Event better news is there are 2 tools that implement this standard:
  • StyleCop - checks source code files
  • Code Analysis (ex FxCop, now integrated in VS) - checks compiled code
Below are detailed steps on how to configure these tools so they run on solution build.

Solution StyleCop configuration

In order to define Style Cop for project first solution must have StyleCop rule settings and StyleCop executable files.

Below are the rules I disable from default rule set in StyleCop:
  • Documentation rules
    • SA 1600 – Elements must be documented
    • SA 1633 – File must have header
    • SA 1634 – File header must show copyright
    • SA 1635 – File header must have copyright text
    • SA 1637 – File header must contain file name
    • SA 1638 – File Header file name documentation must match file name
    • SA 1640 – File header must have valid Company text
  • Ordering rules
    • SA 1200 - Using directives must be placed within namespace
  • Spacing rules
    • SA 1027 – Tabs must not be used

Solution Code Analysis configuration

Add Code analysis rule set and dictionary to solution root.
I use recommended rule set is “Microsoft All Rules” without rules:
  • CA2210 Assemblies should have valid strong names (Design)
  • CA1062: Validate arguments of public methods (Design)
  • CA1303: Do not pass literals as localized parameters (Globalization)
  • CA2233: Operations should not overflow (Usage)
  • CA2204: Literals should be spelled correctly (Naming) – useful but it doesn’t work correctly.
See more about Code Analysis Dictionary.

Project manual configuration

To integrate Code Analysis Dictionary and StyleCop in build, unload and edit project and add following tags. Note that paths might be different depending on Solution configuration.
<ItemGroup>
    <CodeAnalysisDictionary Include="$(SolutionDir)\CodeAnalysisDictionary.xml" />
</ItemGroup>

<Import Project="$(SolutionDir)\ExternalDlls\StyleCop 4.7\StyleCop.targets" />

Project build configuration

Configure compiler warning level on Project properties to 4 (most strict).
Check XML documentation files (unless it’s a test project and not documentation is needed because tests are self-documented).

Project Code Analysis configuration

Configure project Debug configuration to use Code Analysis rules in Solution root. Do the same for the Release configuration. Only difference is that in debug mode Code Analysis should not be run because it slows down the build. We keep CA running in Release to get error report from continues integration and to allow easily turning CA on by altering solution mode from Debug to Release.

Saturday, December 10, 2016

c# image control (web app)


  • zoom(+/-)
  • auto play
  • prev
  • next
  • original size
  • fit to size
  • rotate(left/right)
  • flip horizontal
  • flip vertical
  • invert color

Tuesday, November 29, 2016

Structured Code Reviews and Code Quality

The practices:
  • Introducing a continuous delivery pipeline – All systems have gated builds (We use TFS here) so every check in gets built, the tests executed and MSI’s generated. If the build fails for any reason, i.e. compiler error or failing test then the code fails to check in.
  • Enforcing Unit Testing Discipline – All developers now routinely write unit tests for their code. This was an uphill battle, but we are very close to winning that one. We monitor build over time reports in TFS which give a color coded clue to test coverage. We encourage developers to be around 70-75% covered on new code and code they are maintaining.
  • Use of standard Visual Studio Code Metrics – We encourage developers to keep an eye on certain metrics like Cyclomatic Code Complexity and Maintainability indexes. This gives a good high level indicator of any code smells brewing. These metrics are aimed at helping the developer to keep their code readable by reducing complexity.
  • Static Code Analysis – All new code and a lot of legacy systems have static code analysis rules enforced on local and TFS server builds. For new projects we have a custom rule set that is a subset of the ‘Microsoft All Rules’ set. This caused a lot of heated debate in the teams when we started enforcing this, but once people got used to the rules, they just got used to working with it. For old legacy systems we start off applying the ‘Microsoft Minimum Rule’ and then work our way up from there.
  • Code Productivity Tools – We make all our developers use a code productivity tool. We settled on CodeRush as it has a lot of extra tools for guiding less experienced developers, but tools like ReSharper and Telerik Just Code are just as good. The things I like about these tools are the visual on screen feedback they give you. You can enable a colored bar at the side of the code window that informs you of any code issues. These issues are driven from a rule set, so if you get the team into the mind set of getting rid of the color blips whilst they are working (the tool even does most of the work for you) then you are on the road to better code. Generally the refactoring helpers provided by these tools are better than those provided in Visual Studio too.
I won’t pretend that we now churn out systems so beautiful that angels will weep tears of joy, but by enforcing these points we are driving up the code quality standards and the difference have been very noticeable.
I have also started using these tools to guide code reviews. Code reviews used to just be a bunch of developers sitting around the projector picking holes in code. These code reviews were not very effective. Instead I propose the following process for running a code review:
  • Get the code out of source control fresh.
    • Does it build? Yes then continue, No then stop the code review.
  • Run the unit tests.
    • Do they run and all pass? Yes then continue, No then stop the code review.
  •  Check the unit test code coverage.
    • Is the coverage around >60%? Yes then continue, No then stop the code review unless there is a good excuse for the coverage that the review team are happy with.
  •  Check the code metrics (Cyclomatic Complexity and Maintainability Index)
    • Are the metrics within agreed boundaries? Yes then continue, No then stop the code review.
  •  Run the static code analysis against the agreed rule set?
    • Are there any warnings / errors? Yes then stop the code review, No then continue.
  • Once you get to this point, the development practices have been followed and you can proceed to review the actual code.

Unit Test Coverage, Code Metrics, and Static Code Analysis







The basic process was as follows:
  • Get the code out of source control fresh.
    • Does it build? Yes then continue, No then stop the code review.
  • Run the unit tests.
    • Do they run and all pass? Yes then continue, No then stop the code review.
  •  Check the unit test code coverage.
    • Is the coverage around >60%? Yes then continue, No then stop the code review unless there is a good excuse for the coverage that the review team are happy with.
  •  Check the code metrics (Cyclomatic Complexity and Maintainability Index)
    • Are the metrics within agreed boundaries? Yes then continue, No then stop the code review.
  •  Run the static code analysis against the agreed rule set?
    • Are there any warnings / errors? Yes then stop the code review, No then continue.
  • Once you get to this point, the development practices have been followed and you can proceed to review the actual code.
Unit Test Coverage
Whilst you are developing your software you should be writing tests to exercise that code. Whether you practice test driven development and write your tests first or write tests after the fact, you need a decent level of test coverage. This gives you a level of confidence that the code you are writing does what you expect it too. Also, it gives you a safety blanket when you need to refactor your code. If you make a change in one area, does it break something somewhere else? Unit tests should give you that answer.
The screen shot below, shows the Test Explorer view in Visual Studio 2012. From this view you can run all of your unit tests. As of Visual Studio 2012 Update 1, you can group you tests based on pass outcome, length of execution and project. Think of this view as your project health dashboard. If you have a good level of coverage and they are all green, then you can carry on developing. If you have any red tests then you need to work out why and fix them. Don’t let this view lead you into a false sense of security though. You still need to write tests to a decent level of coverage and ensure you are testing the right things.
Visual Studio 2012 - Test Explorer
Visual Studio 2012 – Test Explorer
You can check your test coverage very easily in Visual Studio. First you can click the little drop down ‘Run’ menu in the Test Explorer, or you can open the ‘Test’ menu in Visual Studio, and then open up the ‘Analyse Test Coverage’ and select ‘All Tests’. This will give you a view similar to below.
Visual Studio 2012 - Code Coverage
Visual Studio 2012 – Code Coverage
In the screen shot above you can see that the project overall has a coverage of 73%. This is a good number. It really is not worth chasing 100% as you end up testing things that just don’t need to be tests, but 60 – 70% is a much more realistic goal. In the example above you can see each assembly in the project where you can drill down into more detail to look at class and method coverage. The key metric here is the ‘Covered % Blocks’ column on the right. It makes sense to routinely check this view so you can keep an eye on your overall coverage. If anything creeps below 60%, then you can take a look. Sometimes you may feel that the area in question doesn’t need extra tests, but you can only make that call when you see the stats in front of your eyes. Purists will argue you need to cover every last inch of code in tests, but we live in the real world and need to be more pragmatic about it.
If you do have any area of code where test coverage has slipped, then Visual Studio makes it very easy to find these areas.
Visual Studio 2012 - Code Coverage Button
Visual Studio 2012 – Code Coverage Button
In the code coverage window, click the highlighted button above (Show Code Coverage Coloring), and then double click on a method that has low coverage, you will be taken to the source code file and any uncovered blocks will be highlighted in red. In the example below, there are 3 items that are uncovered. The first and third examples are where an exception is being thrown based on a null argument check; I would add tests in for those. The middle example just has a public property returning a string. In my view there is no point adding a test for this as you are just testing that the language works at that point.
Visual Studio 2012 - Uncovered Code
Visual Studio 2012 – Uncovered Code
Code Metrics
Unit test coverage is only one part of determining the health of your code base. You can have high test coverage and still have code that is tangled, hard to read and maintain. Visual Studio provides tools to help you, at a glance, look for smells with the structure of your code. To access this view, open the ‘Analyse’ menu in visual studio and select ‘Calculate Code Metrics for Solution’. This will give you a view like below.
Visual Studio 2012 - Code Metrics
Visual Studio 2012 – Code Metrics

Maintainability Index
Cyclomatic Complexity
Class Coupling
Depth of Inheritance
Green
> 60
< 10
< 20
< 5
Yellow
40 - 60
10 - 15


Red
< 40
> 15
> 20
The metrics shown in the columns are:
Maintainablity Index: The Maintainability Index calculates an index value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability. Color coded ratings can be used to quickly identify trouble spots in your code. A green rating is between 20 and 100 and indicates that the code has good maintainability. A yellow rating is between 10 and 19 and indicates that the code is moderately maintainable. A red rating is a rating between 0 and 9 and indicates low maintainability.
Cyclomatic Complexity: Cyclomatic complexity (or conditional complexity) is a software measurement metric that is used to indicate the complexity of a program. It directly measures the number of linearly independent paths through a program’s source code. Cyclomatic complexity may also be applied to individual functions, modules, methods or classes within a program. A higher number is bad. I generally direct my team to keep this value below 7. If the number creeps up higher it means your method is starting to get complex and could do with re-factoring  generally by extracting code into separate, well named methods. This will also increase the readability of your code.
Depth of Inheritance: Depth of inheritance, also called depth of inheritance tree (DIT), is defined as “the maximum length from the node to the root of the tree”. A low number for depth implies less complexity but also the possibility of less code reuse through inheritance. High values for DIT mean the potential for errors is also high, low values reduce the potential for errors. High values for DIT indicate a greater potential for code reuse through inheritance, low values suggest less code reuse though inheritance to leverage. Due to lack of sufficient data, there is no currently accepted standard for DIT values. I find keeping this value below 5 is a good measure.
Class Coupling: Class coupling is a measure of how many classes a single class uses. A high number is bad and a low number is generally good with this metric. Class coupling has been shown to be an accurate predictor of software failure and recent studies have shown that an upper-limit value of 9 is the most efficient.
Lines of Code (LOC): Indicates the approximate number of lines in the code. The count is based on the IL code and is therefore not the exact number of lines in the source code file. A very high count might indicate that a type or method is trying to do too much work and should be split up. It might also indicate that the type or method might be hard to maintain.
Based on the metric descriptions above, you can use the code metrics view to drill down into your code and get a very quick view of areas in your code that start to break these guidelines. You can very quickly start to highlight smells in your code and responds to them sooner rather than later. I routinely stop coding and spend 30 minutes or so going through my code metrics to see if I have gone astray. These metrics will help to keep your code honest.
Static Code Analysis
The final code quality tool I want to discuss is that of static code analysis. This has been around for Visual Studio for quite a while now, and used to be called FXCop, but this is now directly integrated into visual studio. Static code analysis runs a set of rules over your code to look for common pitfalls and problems that arise from day to day development. You can change the rule set to turn on/off rules that are relevant to you. You can also change the sensitivity of the rule. For example do you want it to produce a compiler warning, or actually break the build?
If you have a large code base and are thinking of introducing static code analysis, I recommend starting off setting the ‘Microsoft Managed Minimum Rule set’ and getting all those passing first. If you try to jump straight into the ‘Microsoft All Rules’ rules set you will quickly become swamped and then most likely turn off the code analysis.
Adding code analysis to your solution is easy. It is managed at the project level. Right click on the project in the solution explorer and select ‘Properties’. When the properties window appears, select the ‘Code Analysis’ tab as in the screen shot below.
Visual Studio 2012 - Setting Up Code Analysis
Visual Studio 2012 – Setting Up Code Analysis
First you should select the ‘Enable Code Analysis on Build’ check box. This will make sure the rules are run every time you build your code. This forces you to see the issues with your code every time you build instead of relying on yourself to manually check.
In the drop down box you can select which rule set to use. Generally the rule sets provided by Microsoft are enough to work with. What we found was that some rules were not as relevant to us, so I created a custom rules set. You can see where I selected this above. The rule set is called ‘DFGUK2012’.
You can add your own rule set easily. In your solution, right click and select  ‘Add New Item’. When the dialog box appears, select ‘Code Analysis Rule Set’, as shown below.
Visual Studio 2012 - Adding a Custom Rule Set
Visual Studio 2012 – Adding a Custom Rule Set
Then in your ‘project properties’ rule set drop down box, instead of selecting one of the Microsoft rule sets, select ‘<Browse>’, and then browse to your custom rule set. If you double click on the rule set added to your solution, you will be shown the rule set editor, as shown below.
Visual Studio 2012 - Configuring Code Analysis
Visual Studio 2012 – Configuring Code Analysis
From here you can enable/disable rules to suit your project and team. You can also select whether you want a broken rule to show as a compiler warning or error.

Sunday, November 27, 2016

Visual studio IDE startup issue(More time taken to open IDE)

Issue: 

Visual studio IDE startup issue(More time taken to open IDE).

Visual Studio 2015 extremely slow.



Solution:


1) Go to Tools > Options > Source Control and set Current source control … : None
2) Go to Tools > Options > Environment > Synchronized Settings and remove this option by unchecking the checkbox.
3) Clean the following cache folders and restart Visual Studio:
  • Clean the WebSiteCache folder (might be inC:\Users\%USERNAME%\AppData\Local\Microsoft\WebSiteCache)
  • Clean the Temporary ASP.NET Files folder (might be inC:\Users\%USERNAME%\AppData\Local\Temp\Temporary ASP.NET Files)

Friday, November 25, 2016

Coded UI tests

Unit tests typically work by calling methods in the interface of the code under test. However, if you have developed a user interface, a complete test must include pressing the buttons and verifying that the appropriate windows and content appear. Coded UI tests (CUITs) are automated tests that exercise the user interface. See the MSDN topic Testing the User Interface with Automated Coded UI Tests.
How to create and use coded UI tests
Create a coded UI test
To create a coded UI test, you have to create a Coded UI Test Project. In the New Project dialog, you’ll find it under either Visual Basic\Test or Visual C#\Test. If you already have a Coded UI Test project, add to it a new Coded UI Test.
In the Generate Code dialog, choose Record Actions. Visual Studio is minimized and the Coded UI Test builder appears at the bottom right of your screen.
Choose the Record button, and start the application you want to test.
Recording a coded UI test
Perform a series of actions that you want to test. You can edit them later. You can also use the Target button to create assertions about the states of the UI elements. The Generate Code button turns your sequence of actions into unit test code. This is where you can edit the sequence as much as you like. For example, you can delete anything you did accidentally.
Running coded UI tests
Coded UI tests run along with your other unit tests in exactly the same way. When you check in your source code, you should check in coded UI tests along with other unit tests, and they will run as part of your build verification tests.
Tip: Keep your fingers off the keyboard and mouse while a CUIT is playing. Sitting on your hands helps.
Edit and add assertions
Your actions have been turned into a series of statements. When you run this test, your actions will be replayed in simulation.
What’s missing at this stage is assertions. But you can now add code to test the states of UI elements. You can use the Target button to create proxy objects that represent UI elements that you choose. Then you write code that uses the public methods of those objects to test the element’s state. Extend the basic procedure to use multiple values You can edit the code so that the procedure you recorded will run repeatedly with different input values. In the simplest case, you simply edit the code to insert a loop, and write a series of values into the code.
But you can also link the test to a separate table of values, which you can supply in a spreadsheet, XML file, or database. In a spreadsheet, for example, you provide a table in which each row is a set of data for each iteration of the loop. In each column, you provide values for a particular variable. The first row is a header in which the data names are identified:
Flavor                     Size
Oatmeal                   Small
Herring                    Large
In the Properties of the coded UI test, create a new Data Connection String. The connection string wizard lets you choose your source of data. Within the code, you can then write statements such as
C#
var flavor = TestContext.DataRow[“Flavor”].ToString();
Isolate
As with any unit tests, you can isolate the component or layer that you are testing—in this case, the user interface—by providing a fake business layer. This layer should simply log the calls and be able to change states so that your assertions can verify that the user interface passed the correct calls and displayed the state correctly.
Test first?
You might think this isn’t one of those cases where you can realistically write the tests before you write the code. After all, you have to create the user interface before you can record actions in the Coded UI Test Builder.
This is true to a certain extent, especially if the user interface responds quite dynamically to the state of the business logic. But nevertheless, you’ll often find that you can record some actions on buttons that don’t do much during your recording, and then write some assertions that will only work when the business logic is coupled up.
Coded UI tests: are they unit or system tests?
Coded UI tests are a very effective way of quickly writing a test. Strictly speaking, they are intended for two purposes: testing the UI by itself in isolation (with the business logic faked); and system testing your whole application.
But coded UI tests are such a fast way of creating tests that it’s tempting to stretch their scope a bit. For example, suppose you’re writing a little desktop application—maybe it accesses a database or the web. The business logic is driven directly from the user interface. Clearly, a quick way of creating tests for the business logic is to record coded UI tests for all the main features, while faking out external sources of variation such as the web or the database. And you might decide that your time is better spent doing that than writing the code for the business logic.
Cover your ears for a moment against the screams of the methodology consultants. What’s agonizing them is that if you were to test the business logic by clicking the buttons of the UI, you would be coupling the UI to the business logic and undoing all the good software engineering that kept them separate. If you were to change your UI, they argue, you would lose the unit tests of your business logic.
Furthermore, since coded UI tests can only realistically be created after the application is running, following this approach wouldn’t allow you to follow the test-first strategy, which is very good for focusing your ideas and discussions about what the code should do.
For these reasons, we don’t really recommend using coded UI tests as a substitute for proper unit tests of the business logic. We recommend thinking of the business logic as being driven by an API (that you could drive from another code component), and the UI as just one way of calling the operations of the API. And to write an API, it’s a good idea to start by writing samples of calling sequences, which become some of your test methods.
But it’s your call; if you’re confident that your app is short-lived, small, and insignificant, then coded UI tests can be a great way to write some quick tests.

Encrypt/Decrypt the App.Config

Program.cs using System; using System.Diagnostics; using System.IO; namespace EncryptAppConfig {     internal class Program     {         pr...