MVC & MVVM Android Design Pattern (Android)

Recently, I developed an Android application. The application was developed focusing on simplicity. The application was small thus skipped writing unit tests. I know skipping the unit tests is not a good practice. In past, I was working on backend projects where tons of unit tests exists for API’s. I am new to application development and spent some time to learn about MVC and MVVM design patterns. For next project, the preference is MVVM. At end of this post I will share the reason to choose MVVM. The example code for this post is written for Android application. MVC (Model-View-Controller) Model: Model is data layer. Model call services or database to get data from external systems. View: View is user interface layer. Controller: Controller is triggered first. Controller has reference to Model as well as View. Controller get data from Model and send to View. ...

March 24, 2021 · 5 min · 913 words

Coding blog with colored code snippets(.md posts)

We can make our code snippets more interesting and readable by sharing code with color formatting. To turn on colors, just add language short name 😉 For C# code, add cs after ```. ```cs write your code here ``` Example: static void Main(string[] args) { Logging logger = new Logging(); logger.Log("login success"); }

February 25, 2021 · 1 min · 53 words

Adapter Design Pattern

This design patterns guides to create a wrap around existing class to reuse existing class for a new requirement. Assume, I have two logging classes named WriteLogsToLocalFile and WriteLogsToServer. class WriteLogsToLocalFile { public void Log(string fileName, string message) { //write logs to file } } class WriteLogsToServer { public void Log(string urL, string message, string token) { //call rest API with oAuth // Note: here token is used for oAuth } } static void Main(string[] args) { WriteLogsToLocalFile fileLogs = new WriteLogsToLocalFile(); fileLogs.Log("hello.xml", "login success"); WriteLogsToServer serverLogs = new WriteLogsToServer(); serverLogs.Log("https://server.logs/upload", "login success", "oAuthToken"); } Here user is manually creating objects to write logs separately to local file and server.My requirement is to create a common class for logging, so that client can call common class. The common class should blindly recurse through list of loggers to log message. In below code, a new interface ILog is not compatible with WriteLogsToLocalFile and WriteLogsToServer. We created WriteLogsToServerAdapter and WriteLogsToServerAdapter. Logging is helper class. ...

February 13, 2021 · 2 min · 333 words

Code Review

Code reviews plays an important role to keep code consistent and readable. Code reviews are conducted to maintain quality and simplicity. The bugs should be taken care by automated tests. Code reviews are the best way to learn coding skills from your team members. In this post, I want to share my opinion on how to write code reviews comments. I read a document Google code review. This document is really helpful to write code reviews comments and how to fix, reply on code review comments. The variable name, function name or class name style formatting This type of comments should be taken care by compile time code validation. For example, Android has checkstyle. Rename class or variable names When we are suggesting someone to rename something in our code, maybe we can express or thoughts by: why to change name? what are the suggested names? ...

February 9, 2021 · 1 min · 182 words

Composite Design Pattern

The Composite Design pattern is structural design pattern. This design pattern is used when we want to treat a group of objects in same way. The composite design pattern has following elements. Component This is a class that contain all the members that needs to be implemented by all the objects. Composite This class is used to add, remove and traverse components. Leaf The leaf object in tree structure is defined as leaf element. Code Sample I want to print salaries of all employees in my organization with names and designation. The root of organization tree is CEO. The CEO has directors as child composite. The director has managers as child composite. Finally, engineers at level 1 as leaf because no one is reporting them. // ignore this, just to print static int i = 0; interface IComponent { void print(); } class Composite : IComponent { private string name; private string designation; private decimal salary; private List<IComponent> listComponent = new List<IComponent>(); public Composite(String name, String designation, decimal salary) { this.name = name; this.designation = designation; this.salary = salary; } public void addComponent(IComponent component) { listComponent.Add(component); } public void printDesignation() { Console.Write(designation); Console.Write(" "); } public void printName() { Console.Write(name); Console.Write(" "); } public void printSalary() { Console.Write(salary); Console.Write(" "); } public void print() { printName(); printDesignation(); printSalary(); Console.WriteLine(" "); i++; foreach (var component in listComponent) { for(int k =0;k <i; k++) { Console.Write(" - "); } component.print(); } } } class Leaf : IComponent { private string name; private string designation; private decimal salary; public Leaf(String name, String designation, decimal salary) { this.name = name; this.designation = designation; this.salary = salary; } public void print() { printName(); printDesignation(); printSalary(); Console.WriteLine(" "); } public void printDesignation() { Console.Write(designation); Console.Write(" "); } public void printName() { Console.Write(name); Console.Write(" "); } public void printSalary() { Console.Write(salary); Console.Write(" "); } } static void Main(string[] args) { Leaf ram = new Leaf("Ram", "SE1", 1000000); Leaf sham = new Leaf("Sham", "SE1", 1000000); Composite teamLead = new Composite("Mohan", "Team Lead", 1000000); teamLead.addComponent(ram); teamLead.addComponent(sham); Composite manager = new Composite("John", "Manager", 1000000); manager.addComponent(teamLead); Composite director = new Composite("kuku", "Director", 1000000); director.addComponent(manager); //traverse through all director.print(); } } Output: ...

January 24, 2021 · 2 min · 385 words

Android Application implementing Azure Active Directory Authentication to call protected Azure Function

In this post, I am writing about how to setup Azure Active Directory Android application login to access Azure functions protected with Azure Active Directory authentication. Create an Android Application Open Android Studio and create new Project with Empty Activity. Configure project with below settings Get SHA1 & package name Open powershell and cd to C:\Users<username>.android Execute below command, if prompted for password enter android or leave blank keytool -list -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android Copy SHA1 -> Navigate to https://base64.guru/converter/encode/hex and convert SHA1 to Base64 Copy package name from AndroidManifest.xml Now you have packagename & Base64 SHA1 hash Setup Azure Active Directory I followed steps from Register your app under Azure Active Directory (using Android platform settings) to setup AAD. Login to Azure Open AAD Click App Registration -> New Registration Select Authentication Select Add a platform Enter SHA1 Hash & package name Copy Android Configuration ...

January 23, 2021 · 6 min · 1186 words

Android Studio Enable Checkstyle (Gradle)

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. Steps to enable checkstyle for Android Project Create checkstyle.xml Create folder checkstyle inside Android Project app folder. Create file checkstyle.xml Reference <?xml version="1.0"?> <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"> <!-- Checkstyle configuration that checks the sun coding conventions from: - the Java Language Specification at http://java.sun.com/docs/books/jls/second_edition/html/index.html - the Sun Code Conventions at http://java.sun.com/docs/codeconv/ - the Javadoc guidelines at http://java.sun.com/j2se/javadoc/writingdoccomments/index.html - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html - some best practices Checkstyle is very configurable. Be sure to read the documentation at http://checkstyle.sf.net (or in your downloaded distribution). Most Checks are configurable, be sure to consult the documentation. To completely disable a check, just comment it out or delete it from the file. Finally, it is worth reading the documentation. --> <module name="Checker"> <!-- If you set the basedir property below, then all reported file names will be relative to the specified directory. See http://checkstyle.sourceforge.net/5.x/config.html#Checker <property name="basedir" value="${basedir}"/> --> <!-- Checks that a package-info.java file exists for each package. --> <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage --> <module name="JavadocPackage"/> <!-- Checks whether files end with a new line. --> <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile --> <module name="NewlineAtEndOfFile"/> <!-- Checks that property files contain the same keys. --> <!-- See http://checkstyle.sf.net/config_misc.html#Translation --> <module name="Translation"/> <!-- Checks for Size Violations. --> <!-- See http://checkstyle.sf.net/config_sizes.html --> <module name="FileLength"/> <!-- Checks for whitespace --> <!-- See http://checkstyle.sf.net/config_whitespace.html --> <module name="FileTabCharacter"/> <!-- Miscellaneous other checks. --> <!-- See http://checkstyle.sf.net/config_misc.html --> <module name="RegexpSingleline"> <property name="format" value="\s+$"/> <property name="minimum" value="0"/> <property name="maximum" value="0"/> <property name="message" value="Line has trailing spaces."/> </module> <module name="TreeWalker"> <!-- Checks for Javadoc comments. --> <!-- See http://checkstyle.sf.net/config_javadoc.html --> <module name="JavadocMethod"/> <module name="JavadocType"/> <module name="JavadocVariable"/> <module name="JavadocStyle"/> <!-- Checks for Naming Conventions. --> <!-- See http://checkstyle.sf.net/config_naming.html --> <module name="ConstantName"/> <module name="LocalFinalVariableName"/> <module name="LocalVariableName"/> <module name="MemberName"/> <module name="MethodName"/> <module name="PackageName"/> <module name="ParameterName"/> <module name="StaticVariableName"/> <module name="TypeName"/> <!-- Checks for Headers --> <!-- See http://checkstyle.sf.net/config_header.html --> <!-- <module name="Header"> --> <!-- The follow property value demonstrates the ability --> <!-- to have access to ANT properties. In this case it uses --> <!-- the ${basedir} property to allow Checkstyle to be run --> <!-- from any directory within a project. See property --> <!-- expansion, --> <!-- http://checkstyle.sf.net/config.html#properties --> <!-- <property --> <!-- name="headerFile" --> <!-- value="${basedir}/java.header"/> --> <!-- </module> --> <!-- Following interprets the header file as regular expressions. --> <!-- <module name="RegexpHeader"/> --> <!-- Checks for imports --> <!-- See http://checkstyle.sf.net/config_import.html --> <module name="AvoidStarImport"/> <module name="IllegalImport"/> <!-- defaults to sun.* packages --> <module name="RedundantImport"/> <module name="UnusedImports"/> <!-- Checks for Size Violations. --> <!-- See http://checkstyle.sf.net/config_sizes.html --> <module name="LineLength"/> <module name="MethodLength"/> <module name="ParameterNumber"/> <!-- Checks for whitespace --> <!-- See http://checkstyle.sf.net/config_whitespace.html --> <module name="EmptyForIteratorPad"/> <module name="GenericWhitespace"/> <module name="MethodParamPad"/> <module name="NoWhitespaceAfter"/> <module name="NoWhitespaceBefore"/> <module name="OperatorWrap"/> <module name="ParenPad"/> <module name="TypecastParenPad"/> <module name="WhitespaceAfter"/> <module name="WhitespaceAround"/> <!-- Modifier Checks --> <!-- See http://checkstyle.sf.net/config_modifiers.html --> <module name="ModifierOrder"/> <module name="RedundantModifier"/> <module name="AvoidNestedBlocks"/> <module name="EmptyBlock"/> <module name="LeftCurly"/> <module name="NeedBraces"/> <module name="RightCurly"/> <module name="AvoidInlineConditionals"/> <module name="DoubleCheckedLocking"/> <!-- MY FAVOURITE --> <module name="EmptyStatement"/> <module name="EqualsHashCode"/> <module name="HiddenField"/> <module name="IllegalInstantiation"/> <module name="InnerAssignment"/> <module name="MagicNumber"/> <module name="MissingSwitchDefault"/> <module name="RedundantThrows"/> <module name="SimplifyBooleanExpression"/> <module name="SimplifyBooleanReturn"/> <module name="DesignForExtension"/> <module name="FinalClass"/> <module name="HideUtilityClassConstructor"/> <module name="InterfaceIsType"/> <module name="VisibilityModifier"/> </module> </module> Create checkstyle.gradle Create checkstyle.gradle inside app folder (at same level where build.gradle exists) ...

January 17, 2021 · 3 min · 624 words

Generation of Sequence Diagram using Mermaid

I use online tools to generate sequence diagrams. Recently, my colleague at work guided me about Mermaid to generate sequence diagrams. This is an awesome tool. Mermaid Mermaid has online editor Editor. However, I did not use online editor for confidentiality reasons. I created index.html and opened in browser. <html> <body> <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script> <script> mermaid.initialize({ startOnLoad: true }); </script> <div class="mermaid"> sequenceDiagram participant A participant B A->>B:How are you? B-->> A: I am good loop test loop A->>B:How are you? B-->> A: I am good end </div> </body> </html>

January 6, 2021 · 1 min · 89 words

2020 Review

The year 2020 was a year of unpredicted event Covid-19. In January, my wife travelled to Toronto for her co-op and I planned to spend my evenings studying algorithms and software engineering concepts alongside full time job. I planned to complete most of the study-topics in March and completed as planned. In mid-March my office shared guidelines to work from home. My wife was also back from Toronto and started a co-op remotely. I saved two hours of commute time. My office had layoffs. Some of my teammates were laid off. It was a hard time to see teammates leaving, and I got worried about myself. I started to spend more time studying software engineering topics. Usually, I develop hobby projects using technologies I do not use as a part of my job. Because of Covid-19, I got much time to work on hobby projects to explore AWS and Azure infrastructures. ...

December 31, 2020 · 2 min · 347 words

Accessing Azure Pipeline variables in Webpack Node.js

Recently, I struggled a bit to figure out a way to access Azure-Pipeline Variables in Node.js JavaScript/TypeScript project. However, it is easy. .yml Pipeline code - task: Npm@1 displayName: "Run project" env: MyVariableName: $(MYVARIABLENAME) // this is pipeline variable name, in Capital letters inputs: commands: 'custom' CustomCommand: 'run test' npm Package install package string-replace-loader TypeScript/JavaScript File Create a file with any name “test.ts” test.ts const test = () => { const myVariable = "My-Variable"; }; Setup webpack.config.js module: { rules: [ { test: /test\.ts$/, loader: 'string-replace-loader', options: { search: 'My-Variable', replace: process.env['MyVariableName'] // from .yml env } } ] } } Finally "scripts" :{ "test": "webpack --config webpack.config.js" }

December 30, 2020 · 1 min · 109 words