Wednesday, April 26, 2017

Use of AoP in Cross Cutting Aspect of Error Handling



Cross Cutting Concerns are global concerns that span across methods, classes, applications—and can be concerns widely affecting a whole company or industry.  Think of patient records or a financial history, and things always needed in those industries and how it affects each method of code! There are all kinds of required security for each step and any errors need to be carefully logged.  In other words, integral parts of an application that have to be performed across the layers.  Examples are Logging, Exception/Error Handling, Data Validation, Business Rules, Caching, Security, Communication, and others. 

Aspect Oriented Programming (AOP) = program it once in its own section, and apply it as needed throughout the application.  You should only add something to this section if it is to be reused often.  If it is only a couple of times, try to implement it directly in your code to cut down on abstracting away too much.  On the good, and bad, side.. anything implemented here with a bug is easily fixed in one place, but can wreck havoc globally.

Java supports AOP, whereas C# only partially supports it (hence PostSharp and other 3rd party extensions).  An application with strong architecture tends to have separate layers so different concerns don’t interact more than necessary, which is better for maintainability and for changes over time.  AOP separates general code form code that is globally reusable code present throughout the layers; this is addressing the crosscutting concern. 
So now our code, for example could be separated into:
  • ·       Presentation layer
  • ·       Domain logic layer
  • ·       Data storage layer
  • ·       General globally needed stuff layer (like Exceptions and Logging!)

You can standardize exception handling using AOP and reduce the amount of code written for exception handling.  Most commonly in .NET, you will see post-processing (PostSharp) and code interception (dependency injection). As a sample for how to use AoP to address the cross cutting aspect of Error handling, we will talk about PostSharp.

Using PostSharp for post-processing, you can handle all of the exceptions in one system though a single function. Using PostSharp, you add an attribute [ExceptionAspect] to a method and PostSharp will wrap the method in a try/catch block for you.  This cuts down on code added and allows you to reuse the same try/catch logic over and over again easily.  You can customize your exception handling logic with PostSharp  Please see here for detailed instructions on how to download and implement PostSharp: https://michaelllucas.wordpress.com/2014/11/05/exception-handling-using-postsharp-c/

Sample scenario: You have a win forms project with an in-memory data store.  You search for a name that isn’t in the list and get an error that is cryptic and shows too much sensitive info. 

Below is a normal try/catch:



Below is a custom exception wrapper using PostSharp (this is our Aspect class):

You can handle the issue in the data layer by creating the Database Exception Wrapper and customizing the logic for showing a useful and non-sensitive message.

Below is a try catch using PostSharp:

Notice the attribute at the top using the [DatabaseExceptionWrapper], now the entire function that was wrapped before is considered wrapped in the custom try catch wrapper just made.
“The way OnExceptionAspect works is by wrapping the method in a try/catch block and catching exceptions of type Exception. But there will be cases when you want to handle a specific type of error.” You can specify in the aspect class (in our case the DatabaseExceptionWrapper class) what type of error you want to catch so you aren’t catching all general errors. 

Below it specifies to only catch the InvalidOperationException.

*Note screenshots and sample are from: http://www.postsharp.net/blog/post/Day-1-e28093-OnExceptionAspect (I just distilled it down to summarize it here).

Potential cons of PostSharp:  Increased build times. May need to exclude from local build.  Most say advantages outweigh increased build time (http://stackoverflow.com/questions/417163/anyone-with-postsharp-experience-in-production).

References:

Extra reading:


Xamarin Test Cloud Best Practices



Do’s:
  • Get test cases from QA. One great reason for Test Cloud is to be able to complete a base set of smoke tests or comprehensive testing so that QA can do exploratory testing for new issues / rare cases.  
  • Take a lot of screenshots using ‘app.Screenshot()’ and use a very descriptive name / sentence to describe the step occurring. The only views you will see on Test Cloud will be these screenshots.
  • Name your elements the same between iOS and Android, otherwise you will have a lot of nasty if/else statements in your code.
  • Repeat code as much as possible. If you have 10 tests for buying an item.. take a separate reusable method that logs you in, and call this method many times. The make another method that will add something to your cart, and call this method many times. In case the ‘login’ button name changes, you do not want to be changing your hardcoded app.Tap(“element_name”) in 50 locations, you want to have to only change this is one place if possible.
  • Naming conventions: Try to keep really good naming conventions like large_button_text_on_button or icon_close so that it is easy to identify or even identifiable without going through REPL.  The less time you have to search for elements in REPL, the quicker it will be to complete development.
    • *Make sure you do have a label of some kind to hook onto. If there is no class/id/other name, add one!!! Otherwise you end up doing a hackish thing where you hook something onto the 5th element on the page that is a button or something, and it’s not pretty.
  • Tests can run on average 30 s – 6 minutes or so depending on the app. Try to break down your test scenarios into smaller pieces—as everything is hardcoded, the longer the test the higher probability it can break with any new changes / updates to the app.
  • If you are debugging your app, add app.Repl(); right before it breaks so you can debug and figure out what is going on.
  • Get really good at app.Query();, you will probably use these a lot to find elements.
  • Try to automate when a build goes out, so does a script to test cloud to run smoke/full sets of tests.

Do Not’s:
  • Map anything to x/y coordinates. This changes a lot based on the device you use.
  • For whatever element you choose to wire your test cloud to.. make sure you do not name multiple things on the page the same thing whether it’s a class/id, etc..

Notes:
  • There is an option for a live recording of your phones on Test Cloud. It is a setting when you submit your tests to the cloud to run. You can choose to send a subset of tests or all of the tests.  Subsets are defined using an attribute above the test name. You can add more than one category to a test, for ex. If it is part of a smoke test, part of a login screen test, etc.
  • You probably are not going to get 100% of tests working all the time, phones on Test Cloud will
  • It seems safe to run about 6-10ish types of varied devices per run to conserve hours to get a good idea of if your app is working across most devices.  You can run more if you are not concerned about saving on hours.  
  • You can plug in a physical device also to your computer and run test cloud on that. Make sure you enable debugging on your device. This is a good way to test on iOS if you are only using a Windows computer.
  • You are probably going to have to use some platform specific if statements, for ex. Typing text into an input may not work with .Tap() and you need .Enter(). Make sure you always inject the platform into your classes using DI everywhere.  It happens, sometimes things just don’t work in both platforms the same.
    • if (platform == Platform.Android) {}
    • if (platform == Platform.iOS) {} 

Pain points:
  • If your naming convention is bad or non-existent, consider going through the app to fix this.  It will save you time to re-name elements in a clean way as opposed to trying to hookup Test Cloud to poorly named pieces.  Especially if iOS/Android are different, try to keep these aligned. You can eat a lot of development time if the names are bad, different between iOS/Android, and if elements are hard to find.
  • Remember everything is completely specific to the flow. If you do a UI test to login, add an item, and hit checkout.. and someone adds a new page in for a promotion before you checkout.. it will break your tests. If an element is removed or changed, the tests will break.  There is some upkeep/maintenance to consider, though it should be quick changes.


Monday, February 6, 2017

C# Study Guide: Expanded (~70 pages)


C# and Stuff Study Guide!

I made a study guide for keeping up to date, for students / beginners, and for those who want a guide to brush up on topics for interviews. As a long time med student.. I like to know there is somewhat of a limitation to "everything" you need to know as a foundation in order to be ready for almost any job. I tried to make this guide exactly that. Of course, you will need additional skills / libraries.. but this is the basic core and I would assume if you knew all (*by know, I mean understand AND be able to implement AND explain well during an interview) of this you could get a job and succeed. This is most up to date as of February 2017.. as tech goes, things will change slightly over time and new things will be added that will not be on this sheet. I made a similar post before when this guide was around 20-30 pages and it has since grown.

Keep in mind: I am a C# web developer. I included heavy C# (~60% of the guide), design patterns / lower level JIT compiler / garbage collection / boxing / unboxing type info (~20% of the guide). I have JavaScript and SQL info on here (~10% of the guide). I have random general stuff you just should know which is the last bit. I did not cover algorithms, data structures, or C++.. I honestly haven't needed it for a web development career. I did not cover Java, WPF, desktop/mobile application type things.

One more note: Interviews vary A LOT. This guide would have been immensely helpful for my first 4 jobs. If I had known all of this, I would have aced them all with maybe one or two things missed.. if that. This guide was not the least bit helpful for my current position at Microsoft which aimed thinking questions that you cannot find online that were tailored to my experience and my resume. You should always know everything on your resume, be able to explain it, and be able to explain why a technology was used (versus a competing one plus why it suits your companies needs well). You should also be able to answer any questions about how to implement new features into your working environment, understand why/how things are done now, and how they could be done better.

My approximately all-inclusive study guide is hosted on my Google Docs (it's a .docx file) because it is too large to share on a blog post:
C# and Stuff Study Guide!

Favorite (no-tricks all logic) puzzles

None of these are puzzles I made up, these are puzzles that are relatively well known and easily found on the Internet. I don't like puzzles with gotcha tricks-- such as har har I gotcha, you read the question too fast. These are some solid logic puzzles.

  1. Water bucket 3L, 5L
    You have a 3 and a 5 litre water container, each container has no markings except for that which gives you it's total volume. You also have a running tap. You must use the containers and the tap in such away as to exactly measure out 4 litres of water. How is this done? Can you generalise the form of your answer?
    Answer Here

  2. Chicken fox corn
    A man has to get a fox, a chicken, and a sack of corn across a river. He has a rowboat, and it can only carry him and one other thing. If the fox and the chicken are left together, the fox will eat the chicken. If the chicken and the corn are left together, the chicken will eat the corn. How does the man do it?
    Answer Here

  3. Light bulb puzzle
    Suppose that you are standing in a hallway next to 3 light switches, which are all off. There is another room down the hallway, where there are 3 incandescent light bulbs – each light bulb is operated by one of the switches in the hallway. Because the light bulbs are in another room, you can not see them since you are standing in the hallway. How would you figure out which switch operates which light bulb, if you can only go the room with the light bulbs one time, and only one time?
    Answer Here

  4. Light bulb puzzle
    You have two ropes and a lighter. Each rope has the following property: If you light one end of the rope, it will take one hour to burn to the other end. They don't necessarily burn at a uniform rate. How can you measure a period of 45 minutes?
    Answer Here

  5. Light bulb puzzle
    You have two ropes and a lighter. Each rope has the following property: If you light one end of the rope, it will take one hour to burn to the other end. They don't necessarily burn at a uniform rate. How can you measure a period of 45 minutes?
    Answer Here

  6. Counterfeit coin weighingThere are eight identical-looking coins; one of these coins is counterfeit and is known to be lighter than the genuine coins. What is the minimum number of weighings needed to identify the fake coin with a two-pan balance scale without weights?
    Answer Here

  7. Prisoners hats puzzle According to the story, four prisoners are arrested for a crime, but the jail is full and the jailer has nowhere to put them. He eventually comes up with the solution of giving them a puzzle so if they succeed they can go free but if they fail they are executed. The jailer seats three of the men into a line. The fourth man is put behind a screen (or in a separate room). He gives all four men party hats. The jailer explains that there are two black hats and two white hats, that each prisoner is wearing one of the hats, and that each of the prisoners see only the hats in front of him but neither on himself nor behind him. The fourth man behind the screen can't see or be seen by any other prisoner. No communication among the prisoners is allowed. If any prisoner can figure out what color hat he has on his own head with 100% certainty (without guessing) and tell the jailer, all four prisoners go free. If any prisoner suggests an incorrect answer, all four prisoners are executed. The puzzle is to find how the prisoners can escape, regardless of how the jailer distributes the hats.
    Answer Here

  8. Bridge crossing efficiency puzzle Adam, Bob, Clair and Dave are out walking: They come to rickety old wooden bridge. The bridge is weak and only able to carry the weight of two of them at a time. Because they are in a rush and the light is fading they must cross in the minimum time possible and must carry a torch (flashlight,) on each crossing. They only have one torch and it can't be thrown. Because of their different fitness levels and some minor injuries they can all cross at different speeds. Adam can cross in 1 minute, Bob in 2 minutes, Clair in 5 minutes and Dave in 10 minutes. Adam, the brains of the group thinks for a moment and declares that the crossing can be completed in 17 minutes. There is no trick. How is this done?
    Answer Here

  9. Dragon and Knight puzzle Lets consider a dragon and knight live on an island. That island has seven poisoned wells, which is numbered 1 to 7. If you drink from a well, you can only save yourself by drinking from a higher numbered well. The Well whose is number 7 is located at the top of a high that mountain, so only the dragon can reach it. One day they decide that the island isn't big enough for the two of them, and they have a duel. Each of them brings a glass of water to the duel, they exchange glasses, and drink. After the duel, the knight lives and the dragon dies. Why did the knight live? Why did the dragon die?
    Answer Here

  10. Quarters puzzle There are twenty-six coins lying on a table in a totally dark room. Ten are heads and sixteen are tails. In the dark you cannot feel or see if a coin is heads up or tails up but you may move them or turn any of them over. Separate the coins into two groups so that each group has the same number of coins heads up as the other group. (No tricks are involved.)
    Answer Here

Unit Tests Moq: Verify Number Times Called

The format for the number of times a moq method is called:

// Arrange
someSystem.Setup(x => x.MyMethod(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask);              

//Act             
IList newAlerts = em.ReplaceAlerts(alerts, mockedSystem.Object);              

// Assert
someSystem.Verify(x => x.MyMethod(It.IsAny(), It.IsAny()), Times.Once);

Tuesday, November 29, 2016

Mocking Unit Tests: HttpClient and 2+ parameters

If you have an HTTP Client unit test, you can try the option of making a Wrapper interface in your solution like this here: http://stackoverflow.com/questions/10693955/stubbing-or-mocking-asp-net-web-api-httpclient. As for two parameters in the unit test, you can do the following..

Guid id = Guid.NewGuid();

string baseUri = ConfigurationManager.AppSettings["BaseUrl"] + @"/"
 + ConfigurationManager.AppSettings["ApiVersion"] + @"/";

Dto responseDto = new Dto();

httpClient.Setup(x => x.PostAsync(new Uri(baseUri + "AdditionalUrlHere/Stuff"), It.IsAny()))
                .Callback((uri, dto) => responseDto = dto)
                .ReturnsAsync(id);

Monday, October 24, 2016

Mocking Unit Tests: Get value out of a mocked method

Let's say you have a Save method, and you are unit testing it, and you want to get the "entity" that is getting passed in as a parameter to use in your test.

public voidSave(T entity)
    {
         // Save my stuff
    }


You can do this in your unit test:

FloppyDisk floppyDiskBeingSaved = null;

oldSkoolRepo.Setup(r => r.Save(It.IsAny())).Callback(en =>
{floppyDiskBeingSaved = en;}).Returns(() => Task.FromResult(floppyDiskBeingSaved));

Assert.AreEqual(stuff, floppyDiskBeingSaved);