Design Patterns #6

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 Patterns #5

designp

Visitor pattern

The Visitor pattern defines a new operation to a collection of objects without changing the objects themselves. The new logic resides in a separate object called the Visitor.

Visitors are useful when building extensibility in a library or framework. If the objects in your project provide a ‘visit’ method that accepts a Visitor object which can make changes to the receiving object then you are providing an easy way for clients to implement future extensions.

In most programming languages the Visitor pattern requires that the original developer anticipates functional adjustments in the future. This is done by including methods that accept a Visitor and let it operate on the original collection of objects.

Visitor dofactory – link
Class code: Visitor shapes and tax example

Prototype pattern

The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype – or sample – object. The Prototype pattern is also referred to as the Properties pattern.

An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

deep

Prototype dofactory – link
Class code: Prototype

see immutable and struct clone here in our blog – blog link

Extension Methods in C#

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

… full article

Class code: Extension methods example

Links:

 

Design Patterns #4

designp

Proxy pattern

The Proxy pattern provides a surrogate or placeholder object for another object and controls access to this other object.

In object-oriented programming, objects do the work they advertise through their interface (properties and methods). Clients of these objects expect this work to be done quickly and efficiently. However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (resulting in network latency) or when an object takes a long time to load.

In situations like these you apply the Proxy pattern and create a proxy object that ‘stands in’ for the original object. The Proxy forwards the request to a target object. The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object

Proxy dofactory – link
Class code: Proxy ATM
Class code: Proxy for flight system

Memento pattern

The Memento pattern provides temporary storage as well as restoration of an object. The mechanism in which you store the object’s state depends on the required duration of persistence, which may vary.

You could view a database as an implementation of the Memento design pattern in which objects are persisted and restored. However, the most common reason for using this pattern is to capture a snapshot of an object’s state so that any subsequent changes can be undone easily if necessary.

Essentially, a Memento is a small repository that stores an object’s state. Scenarios in which you may want to restore an object into a state that existed previously include: saving and restoring the state of a player in a computer game or the implementation of an undo operation in a database.

Proxy dofactory – link
Class code: Memento (winform)

Nullable types

A nullable value type T? represents all values of its underlying value type T and an additional null value. For example, you can assign any of the following three values to a bool? variable: true, false, or null. An underlying value type T cannot be a nullable value type itself.
Any nullable value type is an instance of the generic System.Nullable structure. You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable or T?.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool, variable can only be either true or false. However, in some applications a variable value can be undefined or missing. For example, a database field may contain true or false, or it may contain no value at all, that is, NULL. You can use the bool? type in that scenario.

… full article

nice idea: implement Nullable yourself using decorator pattern

see more on value type here in our blog – blog link

Links:

Design Patterns #3

designp

Attributes

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection

Attributes have the following properties:

  • Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required..
  • You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.
  • Attributes can accept arguments in the same way as methods and properties.
  • Your program can examine its own metadata or the metadata in other programs by using reflection.

… full article

Template method + SQL + Reflection + Attributes – Cont.

Complete solution for query execution:

  • Select query
  • Insert query
  • Stored procedure using parameters (for select)

Class code: Full solution

Links:

Design Patterns #2

designp

Template method pattern

The Template Method pattern provides an outline of a series of steps for an algorithm. Objects that implement these steps retain the original structure of the algorithm but have the option to redefine or adjust certain steps. This pattern is designed to offer extensibility to the client developer.

Template Methods are frequently used in general purpose frameworks or libraries that will be used by other developer An example is an object that fires a sequence of events in response to an action, for example a process request. The object generates a ‘preprocess’ event, a ‘process’ event and a ‘postprocess’ event. The developer has the option to adjust the response to immediately before the processing, during the processing and immediately after the processing.

An easy way to think of Template Method is that of an algorithm with holes. It is up to the developer to fill these holes with appropriate functionality for each step.

Template method dofactory – link
Class code: Template method

Reflection in C#

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them

… full article

Class code: reflection demo #1
Class code: reflection demo #2

Template method + SQL + Reflection

Let’s try to build a generic mssql query using template method and reflection

Class code: MSSQL select
Class code: MSSQL select + generics + reflection

The next step will be to implement the Generic query into the template method pattern …

Links:

Design Patterns #1

designp

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects. The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral

Singleton pattern

The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

Singletons are useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’.

Singleton dofactory – link
Class code: Singleton
Video: Singleton + design patterns intro [skip to 26:00]

Factory Method pattern

A Factory Method creates new objects as instructed by the client. One way to create objects is by invoking a constructor function with the new operator. There are situations however, where the client does not, or should not, know which one of several candidate objects to instantiate. The Factory Method allows the client to delegate object creation while still retaining control over which type to instantiate.

The key objective of the Factory Method is extensibility. Factory Methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics (i.e. methods and properties) in common. An example would be a collection of documents with a mix of Xml documents, Pdf documents, and Rtf documents.

Factory Method dofactory – link
Class code: Factory method – simple
Class code: Factory method – advanced

Composite pattern

The Composite pattern allows the creation of objects with properties that are primitive items or a collection of objects. Each item in the collection can hold other collections themselves, creating deeply nested structures.

A tree control is a perfect example of a Composite pattern. The nodes of the tree either contain an individual object (leaf node) or a group of objects (a subtree of nodes).

All nodes in the Composite pattern share a common set of properties and methods which supports individual objects as well as object collections. This common interface greatly facilitates the design and construction of recursive algorithms that iterate over each object in the Composite collection.

Composite dofactory – link
Class code: Composite drawing app

State pattern

The State pattern provides state-specific logic to a limited set of objects in which each object represents a particular state. This is best explained with an example.

Say a customer places an online order for a TV. While this order is being processed it can in one of many states: New, Approved, Packed, Pending, Hold, Shipping, Completed, or Canceled. If all goes well the sequence will be New, Approved, Packed, Shipped, and Completed. However, at any point something unpredictable may happen, such as no inventory, breakage, or customer cancelation. If that happens the order needs to be handled appropriately.

Applying the State pattern to this scenario will provide you with 8 State objects, each with its own set of properties (state) and methods (i.e. the rules of acceptable state transitions). State machines are often implemented using the State pattern. These state machines simply have their State objects swapped out with another one when a state transition takes place.

Two other examples where the State pattern is useful include: vending machines that dispense products when a correct combination of coins is entered, and elevator logic which moves riders up or down depending on certain complex rules that attempt to minimize wait and ride times.

State dofactory – link
Class code: State – lightswitch

Recursion

a recursive definition is defined in terms of itself. Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step having a termination condition so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first.

Sometimes a problem is too difficult or too complex to solve because it is too big. If the problem can be broken down into smaller versions of itself, we may be able to find a way to solve one of these smaller versions and then be able to build up to a solution to the entire problem. This is the idea behind recursion; recursive algorithms break down a problem into smaller pieces which you either already know the answer to, or can solve by applying the same algorithm to each piece, and then combining the results.

Recursion : geeks-for-geeks
Class code: Fibonacci w/o recursion

Time complexity

the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elementary operation takes a fixed amount of time to perform.

… full article

Sometime, time complexity in a recursive solution may be significantly larger than a non-recursive solution..,.

Links:

 

ASP.NET #66

htmlform.png

What are HTML forms?

HTML Forms are one of the main points of interaction between a user and a web site or application. Forms allow users to enter data, generally sending that data to the web server (but a web page can also use form data client side).
An HTML Form is made of one or more widgets. Those widgets can be single or multi-line text fields, select boxes, buttons, check-boxes, or radio buttons. The single line text field widgets can even require data entered to be of a specific format or value. Form widgets should be paired with a properly implemented label that describes their purpose — labels help instruct both sighted and blind users on what to enter into a form input
… full article

How to send HTML form to the server?

We provide a name to each form control. The names are important both browser and server sides; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name. The form data is sent to the server as name/value pairs.
To name the data in a form you need to use the name attribute on each form widget that will collect a specific piece of data.

Example:

forms1.PNG

How to receive the HTML form’s input in the server-side?

We will create an ASP.NET application with an MVC controller containing a function for the form submitting. in this function, we will use Request.Form to retrieve all of the data that the user has entered into our HTML form. each input data will be stored in a key-value format in the Request.Form dictionary: the key will be the html widget form input-name and the value will be the data entered by the user

More topics covered:

  • input + required
  • input type- text, number, password, email
  • radio-button, check-box
  • button type submit
  • form method: GET vs POST
  • storing the html form on the server
  • choosing result page depend on the form-input

Links:

 

ASP.NET #65

htmlcss3

What is HTML?

HTML stands for Hypertext Markup Language. It allows the user to create and structure sections, paragraphs, headings, links, and blockquotes for web pages and applications.
HTML is the standard markup language for Web pages
HTML elements are the building blocks of HTML pages
HTML elements are represented by <> tags
The three block level tags every HTML document needs to contain are:
The  html  tag is the highest level element that encloses every HTML page.
The  head  tag holds meta information such as the page’s title and charset.
Finally, the  body tag encloses all the content that appears on the page.

htmlcode.PNG

What is CSS?

CSS stands for Cascading Style Sheets with an emphasis placed on “Style.” While HTML is used to structure a web document (defining things like headlines and paragraphs, and allowing you to embed images, video, and other media), CSS comes through and specifies your document’s style—page layouts, colors, and fonts are all determined with CSS.
External stylesheets are stored in CSS files

css1.PNG

Example:

css2.jpg

Whats is Visual Studio Code (VSCode)?

vscode

Visual Studio Code is a source-code editor developed by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control and GitHub, syntax highlighting, intelligent code completion, snippets, and code refactoring. It is highly customizable, allowing users to change the theme, keyboard shortcuts, preferences, and install extensions that add additional functionality. The source code is free and open source and released under the permissive MIT License. The compiled binaries are freeware and free for private or commercial use.
Visual Studio Code is based on Electron, a framework which is used to deploy Node.js applications for the desktop running on the Blink layout engine.

VSCode Home Page link

More topics covered:

  • Loading html pages from local hard drive
  • Embed CSS styles into HTML page: inline, style tag, file
  • What is Markup language?
  • VSCode loading from CMD using “code”
  • VSCode – “!” shortcut
  • HTML semantics
  • CSS selectors
  • HTML Tags: b, u, i, p, div, a, hr, h1..h6, img, ul, ol, li, br, btn
  • What is Bootstrap?
  • Developer tools – clicking F12 in Chrome
  • w3schools

Links: