11 MAR 2020

layouts clicks views logcat

andy4

Views

A View occupies a rectangular area on the screen and is responsible for drawing and event handling.The View class is a superclass for all GUI components in Android.

Commonly used Views are :

  • EditText
  • ImageView
  • TextView
  • Button
  • ImageButton
  • CheckBox

… read more – views section

ViewGroup (+layouts)

A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.

Android contains the following commonly used ViewGroupsubclasses:

  • LinearLayout
  • RelativeLayout
  • FrameLayout
  • ScrollView

… read more – view-group section

TableLayout

A layout that arranges its children into rows and columns. A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

tlay

… full example

Activity implements OnClickListener

onclick

… full example

Log + Logcat

Generally, you should use the Log.v()Log.d()Log.i()Log.w(), and Log.e() methods to write logs. You can then view the logs in logcat (android studio).

… full article

developer.android.com

anddev

here you can find all the documentation about android (by google)

Link to site

Links:

08 MAR 2020

android first app

andy4

Android is a mobile operating system based on a modified version of the Linux kernel and other open source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of developers known as the Open Handset Alliance, with the main contributor and commercial marketer being Google.
Initially developed by Android Inc., which Google bought in 2005, Android was unveiled in 2007, with the first commercial Android device launched in September 2008. The current stable version is Android 10, released on September 3, 2019.
Android has been the best-selling OS worldwide on smartphones since 2011 and on tablets since 2013. As of May 2017, it has over two billion monthly active users, the largest installed base of any operating system, and as of January 2020, the Google Play Store features over 2.9 million apps.

Android Studio

andst2

Android Studio is the official integrated development environment (IDE) for Google’s Android operating system, built on JetBrains’ IntelliJ IDEA software and designed specifically for Android development.It is available for download on Windows, macOS and Linux based operating systems.It is a replacement for the Eclipse Android Development Tools (ADT) as the primary IDE for native Android application development.

On 2019, Kotlin replaced Java as Google’s preferred language for Android app development.Java is still supported, as is C++.

Bios

an acronym for Basic Input/Output System and also known as the System BIOSROM BIOS or PC BIOS) is firmware used to perform hardware initialization during the booting process (power-on startup), and to provide runtime services for operating systems and programs.

The BIOS (Basic Input Output System) controls communication between system devices such as the disk drive, display, and keyboard. It also stores configuration information for peripherals types, startup sequence, system and extended memory amounts, and more. Each BIOS version is customized based on the computer model line’s hardware configuration and includes a built-in setup utility to access and change certain computer settings.

… read more

In order to use Android Virtual Device (to run application in android studio) you need to enable the Intel HAXM in the BIOS

… read more

Set Intel HAXM in the BIOS – video!

Anonymous class in Java

In Java, a class can contain another class known as nested class. It’s possible to create a nested class without giving any name. A nested class that doesn’t have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class

anon

More topics covered:
– Installing Android Studio
– Setting virtualization in BIOS (HAXM)
– Creating our first hello world application
– Android Virtual Device (AVD)
– Android application structure
– Resources ( R )
– Manifest file
– Clicking a button event

Links:

 

04 MAR 2020

lazy volatile event-viewer window-service TCP

advance_dot_net9

Lazy<T>

Lazy initialization of an object means that its creation is deferred until it is first used. Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

The lazy keyword which was introduced as part of .NET Framework 4.0 provides the built-in support for lazy initialization i.e. on-demand object initialization. If you want to make an object (such as Singleton) as lazily initialized then you just need to pass the type (Singleton) ) of the object to the lazy keyword as shown below.

private static readonly Lazy<Singleton> Instancelock = new Lazy<Singleton>(() => new Singleton());

The most important point that you need to remember is the Lazy<T> objects are by default thread-safe. In a multi-threaded environment, when multiple threads are trying to access the same Get Instance property at the same time, then the lazy object will take care of thread safety.

… read more

Volatile

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. The compiler, the runtime system, and even hardware may rearrange reads and writes to memory locations for performance reasons. Fields that are declared volatile are not subject to these optimizations. Adding the volatile modifier ensures that all threads will observe volatile writes performed by any other thread in the order in which they were performed. There is no guarantee of a single total ordering of volatile writes as seen from all threads of execution.

… read more

Windows Event Viewer

The Windows Event Viewer shows a log of application and system messages, including errors, information messages, and warnings. It’s a useful tool for troubleshooting all kinds of different Windows problems.

eve2

… read more

Windows Service

Windows Services are a core component of the Microsoft Windows operating system and enable the creation and management of long-running processes.
Unlike regular software that is launched by the end user and only runs when the user is logged on, Windows Services can start without user intervention and may continue to run long after the user has logged off. The services run in the background and will usually kick in when the machine is booted. Developers can create Services by creating applications that are installed as a Service, an option ideal for use on servers when long-running functionality is needed without interference with other users on the same system.

… read more

The 7 Layers of the OSI Model + TCP

The Open System Interconnection (OSI) model defines a networking framework to implement protocols in seven layers. Use this handy guide to compare the different layers of the OSI model and understand how they interact with each other.

osi7

… read more

read OSI model – wikipedia

More topics covered:

  • Developer Command Prompt for Visual Studio
  • Installutility.exe
  • Windows service tray icon
  • TCP- client
  • TCP – server
  • TCP- client fire AJAX
  • Implementing REST API in TCP

Class code:

Links:

Design Patterns – complete

adapter rabbitmq

designp

Adapter pattern

The Adapter pattern translates one interface (an object’s properties and methods) to another. Adapters allows programming components to work together that otherwise wouldn’t because of mismatched interfaces. The Adapter pattern is also referred to as the Wrapper Pattern.

One scenario where Adapters are commonly used is when new components need to be integrated and work together with existing components in the application.

Another scenario is refactoring in which parts of the program are rewritten with an improved interface, but the old code still expects the original interface.

Adapter dofactory – link
Class code: Adapter – 3D shape example
Class code: Adapter employee example
Class code: Adapter for flight system

rabbit

RabbitMQ is a message-queueing software also known as a message broker or queue manager. Simply said; it is software where queues are defined, to which applications connect in order to transfer a message or messages.

mq

A message can include any kind of information. It could, for example, have information about a process or task that should start on another application (which could even be on another server), or it could be just a simple text message. The queue-manager software stores the messages until a receiving application connects and takes a message off the queue. The receiving application then processes the message.

A message broker acts as a middleman for various services (e.g. a web application, as in this example). They can be used to reduce loads and delivery times of web application servers by delegating tasks that would normally take up a lot of time or resources to a third party that has no other job.

mq2

… full article

Possible message deliver mechanism:

  1. Work queues
  2. Publish/Subscribe
  3. Routing
  4. Topics
  5. RPC – remote procedure call (request-reply)
  6. Publisher confirms

… full article

RabbitMQ Enable Web Management Plugin

http://localhost:15672/
username: guest
password: guest rabbitgui

Download the RabbitMQ prerequisite – link
Download the RabbitMQ – link
Installation tutorial – link

RabbitMQ demo code

Class code: Rabbit Listener
Class code: Rabbit Producer

More topics covered:

  • different flavors of builder
  • usage or RabbitMQ in asp.net rest
  • observer less relevant today because of events

Links:

26 FEB 2020

command fluent flyweight weak reference

designp

Command pattern

The Command pattern encapsulates actions as objects. Command objects allow for loosely coupled systems by separating the objects that issue a request from the objects that actually process the request. These requests are called events and the code that processes the requests are called event handlers.

Suppose you are building an application that supports the Cut, Copy, and Paste clipboard actions. These actions can be triggered in different ways throughout the app: by a menu system, a context menu (e.g. by right clicking on a textbox), or by a keyboard shortcut.

Command dofactory – link
Command dotnettutorials – link
Class code: Command – azure example
Class code: Command – javascript example

Fluent pattern

A fluent interface is normally implemented by using method chaining to implement method cascading, concretely by having each method return this (self). Stated more abstractly, a fluent interface relays the instruction context of a subsequent call in method chaining, where generally the context is

  • Defined through the return value of a called method
  • Self-referential, where the new context is equivalent to the last context
  • Terminated through the return of a void context

Note that a “fluent interface” means more than just method cascading via chaining…

Class code: fluent – LINQ
Class code: fluent Customer

Flyweight pattern

The Flyweight pattern conserves memory by sharing large numbers of fine-grained objects efficiently. Shared flyweight objects are immutable, that is, they cannot be changed as they represent the characteristics that are shared with other objects.

Essentially Flyweight is an ‘object normalization technique’ in which common properties are factored out into shared flyweight objects. (Note: the idea is similar to data model normalization, a process in which the modeler attempts to minimize redundancy). An example of the Flyweight Pattern could be a is a list of immutable strings that are shared across the application.

Other examples include characters and line-styles in a word processor, or ‘digit receivers’ in a public switched telephone network application. You will find flyweights mostly in utility type applications such as word processors, graphics programs, and network apps; they are less often used in data-driven business type applications.

Flyweight dofactory – link
Flyweight dotnettutorials – link
Class code: Flyweight – big numbers
Class code: Flyweight – java GUI example

Weak reference

Objects that are referenced must be kept in memory until they are unreachable. use the WeakReference type, which leaves objects accessible in memory until they are collected by the Garbage Collector (GC).

If you have cache layer implemented with C# it’s much better too put your data in cache as weak references, it could help to improve your cache layer performance. Think that approach also could be applied to session implementation. Because session is long living object most of the time, it could be some case when you have no memory for new user. In that case it will be much better to delete some else user session object then throwing OutOfMemoryException.

Also, if you have a large object in your application (some big lookup table, etc), that should be used quite seldom and recreating of such an object isn’t a very expensive procedure. Then better have it like a week reference to have a way to free your memory when you really need that.

Class code: weak reference

Weak reference regenerate

More topics covered:

  • GC.Collect( )
  • Gather commands in different invokers
  • Add a button which invokes a command
  • WPF command

Links:

23 FEB 2020

mediator builder observer

designp

Builder pattern

The Builder pattern allows a client to construct a complex object by specifying the type and content only. Construction details are hidden from the client entirely.

The most common motivation for using Builder is to simplify client code that creates complex objects. The client can still direct the steps taken by the Builder without knowing how the actual work is accomplished. Builders frequently encapsulate construction of Composite objects because the procedures involved are often repetitive and complex. Usually it is the last step that returns the newly created object which makes it easy for a Builder to participate in fluent interfaces in which multiple method calls, separated by dot operators, are chained together (note: fluent interfaces are implementation of the Chaining Pattern as presented in the Modern patterns section).

Builder dofactory – link
Builder dotnettutorials – link
Class code: builder – hamburger!

Observer pattern

The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs. This pattern is the cornerstone of event driven programming, The Observer pattern facilitates good object-oriented design and promotes loose coupling.

When building web apps you end up writing many event handlers. Event handlers are functions that will be notified when a certain event fires. These notifications optionally receive an event argument with details about the event (for example the x and y position of the mouse at a click event).

The observer pattern was the key idea behind events and delegates

Observer dofactory – link
Class code: observer – observing stock market – in Java!

Mediator pattern

The Mediator pattern provides central authority over a group of objects by encapsulating how these objects interact. This model is useful for scenarios where there is a need to manage complex conditions in which every object is aware of any state change in any other object in the group.

The Mediator patterns are useful in the development of complex forms. Take for example a page in which you enter options to make a flight reservation. A simple Mediator rule would be: you must enter a valid departure date, a valid return date, the return date must be after the departure date, a valid departure airport, a valid arrival airport, a valid number of travelers, and only then the Search button can be activated.

Another example of Mediator is of course a chat room when every message passes through a mediator which publishes only appropriate messages

Mediator dotnettutorials – chat room
Mediator dofactory – link
Class code: mediator – selling stocks – in Java!

More topics covered:

  • different flavors of builder
  • observer less relevant today because of events

Links:

19 FEB 2020

bridge iterator foreach yield

designp

Bridge pattern

The Bridge pattern allows two components, a client and a service, to work together with each component having its own interface. Bridge is a high-level architectural pattern and its main goal is to write better code through two levels of abstraction. It facilitates very loose coupling of objects. It is sometimes referred to as a double Adapter pattern.

An example of the Bridge pattern is an application (the client) and a database driver (the service). The application writes to a well-defined database API, for example ODBC, but behind this API you will find that each driver’s implementation is totally different for each database vendor (SQL Server, MySQL, Oracle, etc.).

Bridge is very similar to strategy!

Bridge dofactory – link

Bridge pattern vs Strategy pattern

“They both look the same on the surface to me as well. The main difference I see is the fact that in the Bridge pattern, the abstraction is PART OF the object, but in the Strategy pattern the abstraction is performed BY the object.

Bridge: ( A structural pattern)

Bridge pattern decouples abstraction and implementation and allows both to vary independently.

Use this pattern when :

  1. Abstractions and implementations have not been decided at compile time
  2. Abstractions and implementations should be changed independently
  3. Changes in implementation of abstraction should not affect caller application
  4. Client should be insulated from implementation details.

Strategy: ( Behavioural pattern)

Strategy patterns enable you to switch between multiple algorithms from a family of algorithms at run time.

Use Strategy pattern when :

  1. Multiple versions of algorithms are required
  2. The behaviour of class has to be changed dynamically at run time
  3. Avoid conditional statements”

Iterator pattern

The Iterator pattern allows clients to effectively loop over a collection of objects. A common programming task is to traverse and manipulate a collection of objects. These collections may be stored as an array or perhaps something more complex, such as a tree or graph structure. In addition, you may need to access the items in the collection in a certain order, such as, front to back, back to front, depth first (as in tree searches), skip evenly numbered objects, etc. The Iterator design pattern solves this problem by separating the collection of objects from the traversal of these objects by implementing a specialized iterator.

Today, many languages have Iterators built-in by supporting ‘for-each’-type constructs and IEnumerable and IEnumerator interfaces.

Iterator dofactory – link

foreach + yield + IEnumerable

yield1

yield2

yield3

You use a yield return statement to return each element one at a time.

The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

You can use a yield break statement to end the iteration.

… full article
nice article on yield
Class code: foreach yield
Youtube code: foreach yield list

foreach + GetEnumerator

y22

y111

y3

The foreach statement executes a statement or a block of statements for each element in an instance of the type that contains GetEnumerator method. The foreach statement is not limited to those types and can be applied to an instance of any type that satisfies the following conditions:

  • has the public parameterless GetEnumerator method whose return type is either class, struct, or interface type
  • the return type of the GetEnumerator — which has public Current property, public parameterless MoveNext method whose return type is Boolean and public Reset

(of course you can also implement System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interfaces)

Class code: foreach a class using enumerator
Youtube code: foreach my data collection

More topics covered:

  • advantages of IEnumerable
  • enumerate a non-existing collection
  • ASP.NET REST IEnumerable

Links:

16 FEB 2020

abstract-factory strategy log4net

designp

Strategy pattern

The Strategy pattern encapsulates alternative algorithms (or strategies) for a particular task. It allows a method to be swapped out at runtime by any other method (strategy) without the client realizing it. Essentially, Strategy is a group of algorithms that are interchangeable.

Say we like to test the performance of different sorting algorithms to an array of numbers: shell sort, heap sort, bubble sort, quicksort, etc. Applying the Strategy pattern to these algorithms allows the test program to loop through all algorithms, simply by changing them at runtime and test each of these against the array. For Strategy to work all method signatures must be the same so that they can vary without the client program knowing about it.

Strategy dofactory – link
Class code: strategy demo in JAVA!

Abstract factory pattern

An Abstract Factory creates objects that are related by a common theme. In object-oriented programming a Factory is an object that creates other objects. An Abstract Factory has abstracted out a theme which is shared by the newly created objects.

Suppose we have two Abstract Factories whose task it is to create page controls, such as, buttons, textboxes, radio buttons, and listboxes. One is the Light Factory which creates controls that are white and the other the Dark Factory which creates controls that are black. Both Factories creates the same types of controls, but they differ in color, which is their common theme. This is an implementation of the Abstract Factory pattern.

This includes scenarios in which the creation process involves object caching, sharing or re-using of objects, complex logic, or applications that maintain object and type counts, and objects that interact with different resources or devices. If your application needs more control over the object creation process, consider using a Factory.

Abstract factory dofactory – link
Class code: abs factory demo in JAVA!

Apache log4net

log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in production code without incurring a high performance cost. It follows that the speed of logging (or rather not logging) is crucial.

At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net (and common to all of the log4x libraries) is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity.

Apache log4net – home site!
Log4net appenders list
Log4net – demo project
Log4net – stackify demo!

Nice interview question

formula: “AA,ABC@BC,DD@CDA”….

for the question – click here

JSON viewer

Json viewer stack.hu – click here

More topics covered:

  • choosing strategy based on input
  • changing strategy at run-time

Links:

12 FEB 2020

chain-of-resp struct string-builder immutable

designp

Chain of resp. pattern

The Chain of Responsibility pattern provides a chain of loosely coupled objects one of which can satisfy a request. This pattern is essentially a linear search for an object that can handle a particular request.

An example of a chain-of-responsibility is event-bubbling in which an event propagates through a series of nested controls one of which may choose to handle the event.

Chain of resp. dofactory – link
Class code: chain of resp. demo in JAVA!

in – parameter modifier

The in keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. It is like the ref or out keywords, except that in arguments cannot be modified by the called method. Whereas ref arguments may be modified, out arguments must be modified by the called method, and those modifications are observable in the calling context.

in

… full article

Class code: in example

Mutable vs. Immutable

Mutable and immutable are English words that mean “can change” and “cannot change” respectively. The meaning of these words is the same in C# programming language; that means the mutable types are those whose data members can be changed after the instance is created but Immutable types are those whose data members can not be changed after the instance is created.

When we change the value of mutable objects, value is changed in same memory. But in immutable type, the new memory is created and the modified value is stored in new memory.

Let’s start with examples of predefined classes (String and StringBuilder)

StringBuilder in C#

A String is immutable, meaning String cannot be changed once created. For example, new string “Hello World!!” will occupy a memory space on the heap. Now, by changing the initial string “Hello World!!” to “Hello World!! from Tutorials Teacher” will create a new string object on the memory heap instead of modifying the initial string at the same memory address. This behaviour will hinder the performance if the same string changes multiple times by replacing, appending, removing or inserting new strings in the initial string.

To solve this problem, C# introduced StringBuilder. StringBuilder is a dynamic object that allows you to expand the number of characters in the string. It doesn’t create a new object in the memory but dynamically expands memory to accommodate the modified string

… full article

Structs in C#

Structs share most of the same syntax as classes. The name of the struct must be a valid C# identifier name. Structs are more limited than classes in the following ways:

  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct cannot declare a parameterless constructor (a constructor without parameters) or a finalizer.
  • Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • Structs are value types, unlike classes, which are reference types.
  • Unlike classes, structs can be instantiated without using a new operator.
  • Structs can declare constructors that have parameters.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from ValueType, which inherits from Object.
  • A struct can implement interfaces.
  • A struct cannot be null, and a struct variable cannot be assigned null unless the variable is declared as a nullable value type.

… full article

Class code: Struct example

Value Types in C#

Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type. By default, on assignment, passing an argument to a method, or returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied

… full article

More topics covered:

  • Structs GetHasCode
  • Structs Equals
  • Structs boxing/unboxing

Links:

 

Design a site like this with WordPress.com
Get started