Thursday, May 4, 2017

Practical Git Commands Kickstart




Git command line is extremely useful for managing your resources – it is the only way to utilize all Git commands possible as most GUI’s only have a set of available commands.  Although many guides exist to explain Git command line, many are brief introductions or extremely comprehensive.  I will share a practical guide of commands I needed to use to get through my day, no more, no less as part of a kick start to get you going with Git.  I will list commands by group in tables and will give an explanation below each table in italics for why/when you need these commands if you are new to Git.



Project/Directory Setup Commands
Use/Explanation
git init
New repository from current directory
git init <directory>
New repository to a specific directory
git clone /path/to/repository
Connecting to an existing local repository
git clone username@host:/path/to/repository
Connecting to an existing remote repository
You need initialize a local file directory to be a Git repository for a new project (your local file directory will be associated with a certain online repository).  Initializing will create a .git folder in the directory and this is where Git will record different versions of the project and the .git folder will contain all of the metadata and changes to the project (rest of the project will not be altered while you are working). 



Adding/Staging/Unstaging Files Commands
Use/Explanation
git add filename.txt
Stages a specific file to commit
git add -A
Stages all
git add .
Stages new and modified, without deleted. *This add command is most commonly used
git add -u
Stages modified and deleted, without new
git add *
Stages all files in current directory except files whose name begin with a dot. Wildcard interpreted as part of git.
git reset -- filename.txt
Unstages a file by name, the changes are still there that you made but it will not be committed until you add it back
git reset
Unstages all files (again changes are still there and now nothing is committed until you add it in)
git status
Checking file status (see which files are staged/unstaged for the commit)
Staging and unstaging do not affect the changes of the files or delete and files, they are for adding/removing files to track for a commit or stash.  You push your commits to make a change.  In Git, you stage(add) the files you want to commit and unstage (reset) files you do not want to commit. Note ‘--’ in a command specifies we are talking about a file, not a branch (in case some file names are the same as a branch name).



Commit/Reset Commands
Use/Explanation
git commit -m “Your message here to describe what you are committing to your branch.”
Commit changes with a message
git checkout <file>
Abandon/Undo changes to one file
git reset --hard HEAD~1

Removing the most recent one commit (HEAD~1 means the commit before the head)
git log
Find a commit id
git reset --hard <sha1-commit-id>
Removing a very specific commit id
git reset --hard
Removing all commits/changes and reset back to original branch pulled
Committing is not permanent, do not be afraid to commit. You don’t have to push your commit. You can roll back this commit easily if you want to erase all of it and go back to the original code in the branch. You must commit or stash everything before you can change branches, pull new commits in, etc (see final table for stashing info). 



Push/Pull Commands
Use/Explanation
git push
Pushing changes from current branch to the same current branch
git push originally-cloned-branch new-branch
Pushing changes from an originally cloned branch to a new branch
git fetch
Fetching commits and remote branch changes, does not put new changes into your code until you pull though
git pull
Pulls all the latest commits to your current branch from the server
You must run a git fetch to see new commits or any new branches added to your repository. Git pull does a git fetch + git merge. You can git fetch anytime to update remote tracking branches or see any latest commits from others. If you already pushed a commit and need to revert it, you can do a force push to get rid of it but honestly it is safer for you to create a new branch and fix your changes as others are working in the same code (pushing is a little permanent, make sure you test everything out before you push your changes to the server where other developers will see your work).



Switching/Creating Branches
Use/Explanation
git checkout -b my-new-branch-name

Create a new branch based on your current branch, and switch to the new branch. Note the -b means that you need to create a new branch
git checkout -b new-branch existing-branch
Create a new branch based on a specific branch
git checkout existing-branch-name
Switching to another existing branch
Make sure you commit or stash your changes before trying to change branches.  Note: you are able to swap between different branches with one code same base—all of the changes that appear are applied based on the contents of the .git folder on top of the original files. 



Merging Branches Commands
Use/Explanation
git merge branchname
Merges branchname into your current branch. Make sure to pull latest into both your current branch and the branch to merge in
git reset --merge .
Abandon a merge with merge conflicts, goes back to state you were in before you attempted to merge. Can use this command if Git v1.6.1+
git reset --hard HEAD
If Git version is less than 1.6.1 then use this to abandon a merge
You merge one branch into another one, for example if you are working in a feature branch and want to put your work into develop.. or if you want to merge stable develop changes into QA.  Careful with merge conflicts and to test after fixing all of them before committing and finally pushing to the server.



Dealing with Stashes Commands
Use/Explanation
git stash
Stash all tracked files without a message/description to index 0
git stash save “my description here”
Stash all tracked files that have not yet been committed
git stash save -u “my description here”
Stash all files that have not yet been committed including untracked files
git stash pop
-or-
git stash apply
All changes to stashed files will be applied to the current workspace (unstashing). You can reapply to same branch or apply changes to a new branch. By default gets stash@{0}. Important: git stash pop throws away the stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse.
git stash pop stash@{2}
-or-
git stash apply stash@{2}
Specifies which index to apply/unstash to your current workspace
git stash list
List the current stashes, you can see the index of each one to delete a certain one
git stash clear
Clear/Delete all the current stashes
git stash drop stash@{0}
Replace {0} with the index of the stash you want to drop

Use git add/reset to determine which files you want to stash. You can stash changes as a “save-state” so you can do work in another branch, all changes will be saved in your local Git repo and nothing from the stash will go to the server.   You can easily unstash your changes onto the same or another branch.  You can apply one stash to multiple other branches.  Sometimes you may make a feature branch and make a lot of foundational domain changes.. then suddenly you realize another developer needs your changes to work.  You can stash your changes and unstash them on top of the other branch so you are both working in the same branch with shared foundational code. New git stashes by default are always created to stash@{0}, and older ones’ will have the index pushed to higher index numbers.


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);