C# Example of Math Expressions, Variables, and If Statements

Anyone getting into C# and ASP.NET development will likely be starting with basic expressions, variables, and if statements. Get familiar with these concepts:


private void radioButton1_CheckedChanged(object sender, EventArgs e) 
{ 
    string x = this.textBox1.Text; 
    string y = this.textBox2.Text; 
    if (x == "") //See if x has no value 
    { 
        x = "0"; //Set x to 0 
    } 
    if (y == "") //See if x has no value 
    { 
        y = "0"; //Set y to 0 
    } 
    int x_number = Convert.ToInt32(x); //Converts the string x to a number then stores it in x_number 
    int y_number = Convert.ToInt32(y); 
    int random = x_number + y_number; //Sets the integer variable random to the value of x_number plus y_number 
    string random_string = Convert.ToString(random); //Converts the integer random to the string random_string 
    this.label3.Text = random_string; 
}

What is MVC or Model, View, Controller

In object-oriented programming development, model-view-controller (MVC) is the name of a methodology or design pattern for successfully and efficiently relating the user interface to underlying data models. The MVC pattern is popular when coding with Java, C, and C++.

A Model : Represents the underlying, logical structure of data in a software application and the high-level class associated with it. This object model does not contain any information about the user interface.

A View : Is a collection of classes representing the elements in the user interface (all of the things the user can see and respond to on the screen, buttons, display boxes, etc.)

A Controller : Represents the classes connecting the model and the view, and is used to communicate between classes in the model and view.

More Basic:
Model = Handles data and business logic.
View = Presents data to the user in any layout form.
Controller = Receives user requests and calls appropriate resources to execute them.

MVC Follows This Basic Flow:

Let’s take the program Spotify

1. The user interacts with the user interface in some way, say they press the button to add a song to the playlist.

2. A controller handles the input event from the user interface, often via a registered handler or callback.

3. The controller notifies the model of the user action, possibly resulting in a change in the model’s state. In this instance the song is added to a playlist.

4. A view uses the model (indirectly) to generate an appropriate user interface (i.e. the view produces a screen displaying your music list made in Spotify). The view gets its own data from the model. The model has no direct knowledge of the view.

5. The user interface waits for further user interactions, which begins the cycle again.

Example of a MVC pattern : A calculator

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
// Note: The view should not send to the model but it is often useful
// for the view to receive update event information from the model. 
// However you should not update the model from the view.
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        frmCalcView view = new frmCalcView();
        CalculatorModel model = new CalculatorModel();
        CalcController controller = new CalcController(model, view);
        Application.Run(view);
    }
}
/// <summary>
/// The controller process the user requests.
/// Based on the user request, the Controller calls methods in the View and
/// Model to accomplish the requested action. 
/// </summary>
class CalcController : IController
{
    ICalcModel model;
    ICalcView view;

    public CalcController( ICalcModel model, ICalcView view)
    {
        this.model = model;
        this.view = view;
        this.view.AddListener(this); // Pass controller to view here.
    }

    public void OnClick( int number )
    {
        view.Total = model.SetInput(number).ToString();
    }

    public void OnAdd()
    {
        model.ChangeToAddState(); 
    }
}

Example of a MVC pattern : IController

/// <summary>
/// Windows Form that will host our MVC based functionality.
/// 
/// </summary>
public partial class frmCalcView : Form, ICalcView
{
    IController controller;
    public frmCalcView( )
    {
        InitializeComponent();
    }
    /// <summary>
    /// The view needs to interact with the controller to pass the click events
    /// This could be done with delegates instead.
    /// </summary>
    /// <param name="controller"></param>
    public void AddListener( IController controller )
    {
        this.controller = controller;
    }
    private void lbl_Click(object sender, EventArgs e)
    {
        // Get the text out of the label to determine the letter and pass the
        // click info to the controller to distribute.
        controller.OnClick((Int32.Parse(((Label)sender).Text)));
    }
    private void lblPlus_Click(object sender, EventArgs e)
    {
        controller.OnAdd();
    }

#region ICalcView Members
    public string Total
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text = value;
        }
      }
#endregion
}

Here is a look at the model

 /// <summary>
    /// Calculator model, The model is independent of the user interface.
    /// It doesn't know if it's being used from a text-based, graphical, or web interface
    /// This particular model holds the state of the application and the current value.
    /// The current value is updated by SetInput
    /// </summary>
    class CalculatorModel : ICalcModel
    {
        public enum States { NoOperation, Add, Subtract };
        States state;
        int currentValue;
        public States State
        {
            set { state = value; }
        }
        public int SetInput ( int number )
        {
            if (state == States.NoOperation)
            {
                currentValue = number;
            }
             else if (state == States.Add)
            {
                currentValue = Add(currentValue , number );
            }
            return currentValue;
        }
        public void ChangeToAddState()
        {
            this.state = States.Add;
        }
        public int Add( int value1, int value2 )
        {
            return value1 + value2;
        }
        public int Subtract(int value1, int value2)
        {
            throw new System.ApplicationException(" Not implemented yet");
        }
}

4 Pillars of Object Oriented Programming

1.Abstraction
Abstraction is a process of exposing essential feature of an entity while hiding other irrelevant detail. Why would you want to use abstraction? abstraction reduces code complexity and at the same time it makes your aesthetically pleasant.

2.Encapsulation
We have to take in consideration that Encapsulation is somehow related to Data Hiding.
Encapsulation is when you hide your modules internal data and all other implementation details/mechanism from other modules. it is also a way of restricting access to certain properties or component. Remember, Encapsulation is not data hiding, but Encapsulation leads to data hiding

3.Inheritance
The ability of creating a new class from an existing class. Like the word Inheritance literally means it is a practice of passing on property, titles, debts, rights and obligations upon the death of an individual. in OOP this is somehow true(Except the death of an individual) ,where The base class(the existing class sometimes called as the Parent class) has properties and methods that will be inherited by the sub class (sometimes called a subtype or child class) and it can have additional properties or methods.

Inheritance is also a way to use code of an existing objects.

4. Polymorphism
Just like in biology, Polymorphism refers to the ability to take into different forms or stages.A subclass can define its own unique behaviour and still share the same functionalities or behavior of its parent/base class.Yes, you got it right, subclass can have their own behavior and share some behaviour from its parent class BUT!! not vice versa. A parent class cannot have the behaviour of its subclass.

What are Stacks and Bubble Sorts

Stacks are a type of list in which all inserts and removals happen at one end

class stack
{
  public:
    stack(void);                // Constructor and Initializer

    bool push(int data);        // Push onto stack
    bool pop(int data);         // Pop from stack
    int  peek(int depth);       // Peek several layers down

  private:
    const int MAX_SIZE;         // Maximum stack size
    int   stack_data[MAX_SIZE]; // Stack Data Array
    int   stack_top;            // Keeps track of Stack Top
};

BUBBLE SORT

// By convention, 'n' is usually the size of the
// array to be sorted.
void bubblesort( int array[], int n )
{
  for ( int i = 0; i < n-1; ++i )
    for ( int j = 1; j < n-i; ++j )
      if ( array[j-1] > array[j] )
        // Note the use here of swap()
        swap( array[j-1], array[j] );
}

Linked List Example

Here is the code structure for the linked list:

class linked_list {
  public:
    linked_list(void);     // Constructor
    ~linked_list(void);    // Destructor

    void print(void);      // Prints Entire List
    void insert(int item); // Insert Function
    void remove(int item); // Remove Function
    bool search(int item); // Search Function
  
  private:
    linkedNode *first;     // Pointer to first node
};

class linkedNode {
  public:
    int data;            // Data held by this node
    linkedNode *next;    // Pointer to next node
};

Using REGEX to Eliminate Extra Strings in Table

The code to search for additional letters is

<td[A-Z]?

You’ll want to set the replace character to

<td

A lot of people need to remove URLs from a copied webpage, instead of removing the links one by one you can use regex to remove URLS that have slightly different links with this REGEX code:

// Example: you want to select a long list of URLS for removal from a webpage.

<a href="https://www.sethcodes.com/file/7045">
<a href="https://www.sethcodes.com/file/7035">

// This will select the entirety of both above lines:
<a href="https://www.sethcodes.com/file/70[0-9]*[0-9]">

[0-9]* Selects any number from 0-9
[A-Z]* Selects any letter from A-Z

Java Standard Collections

In the Collections Framework, there are many implementation classes to choose from. Most of the time, one of these “primary implementations” is the appropriate choice

Before JDK 1.5, HashMap and HashSet were the preferred implementations of Map and Set. However, the iterators returned by those classes have the somewhat bizarre property of having an undefined order. That is, iterating over a HashMap or HashSet can return elements in a different order at different times. Their iteration order is not guaranteed to be repeatable (and often isn’t). Even though HashMap and HashSet have slightly better overall performance, for most business applications it is likely best to avoid such undefined behavior.

To retain the sorting of items being manipulated in a graphical user interface, TreeSet and TreeMapare useful. They force a collection to maintain a sort order when the user adds and deletes items.

 

Collections Framework Overview

Introduction

The Java platform includes a collections framework. A collection is an object that represents a group of objects (such as the classic Vector class). A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.

The primary advantages of a collections framework are that it:

  • Reduces programming effort by providing data structures and algorithms so you don’t have to write them yourself.
  • Increases performance by providing high-performance implementations of data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations.
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
  • Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
  • Reduces the effort required to design and implement APIs by not requiring you to produce ad hoc collections APIs.
  • Fosters software reuse by providing a standard interface for collections and algorithms with which to manipulate them.

The collections framework consists of:

  • Collection interfaces. Represent different types of collections, such as sets, lists, and maps. These interfaces form the basis of the framework.
  • General-purpose implementations. Primary implementations of the collection interfaces.
  • Legacy implementations. The collection classes from earlier releases, Vector and Hashtable, were retrofitted to implement the collection interfaces.
  • Special-purpose implementations. Implementations designed for use in special situations. These implementations display nonstandard performance characteristics, usage restrictions, or behavior.
  • Concurrent implementations. Implementations designed for highly concurrent use.
  • Wrapper implementations. Add functionality, such as synchronization, to other implementations.
  • Convenience implementations. High-performance “mini-implementations” of the collection interfaces.
  • Abstract implementations. Partial implementations of the collection interfaces to facilitate custom implementations.
  • Algorithms. Static methods that perform useful functions on collections, such as sorting a list.
  • Infrastructure. Interfaces that provide essential support for the collection interfaces.
  • Array Utilities. Utility functions for arrays of primitive types and reference objects. Not, strictly speaking, a part of the collections framework, this feature was added to the Java platform at the same time as the collections framework and relies on some of the same infrastructure.

Collection Interfaces

The collection interfaces are divided into two groups. The most basic interface, java.util.Collection, has the following descendants:

The other collection interfaces are based on java.util.Map and are not true collections. However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Map has the following offspring:

Many of the modification methods in the collection interfaces are labeled optional. Implementations are permitted to not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) if they are attempted. The documentation for each implementation must specify which optional operations are supported. Several terms are introduced to aid in this specification:

  • Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable.
  • Collections that additionally guarantee that no change in the Collection object will be visible are referred to as immutable. Collections that are not immutable are mutable.
  • Lists that guarantee that their size remains constant even though the elements can change are referred to as fixed-size. Lists that are not fixed-size are referred to asvariable-size.
  • Lists that support fast (generally constant time) indexed element access are known as random access lists. Lists that do not support fast indexed element access are known as sequential access lists. The RandomAccess marker interface enables lists to advertise the fact that they support random access. This enables generic algorithms to change their behavior to provide good performance when applied to either random or sequential access lists.

Some implementations restrict what elements (or in the case of Maps, keys and values) can be stored. Possible restrictions include requiring elements to:

  • Be of a particular type.
  • Be not null.
  • Obey some arbitrary predicate.

Attempting to add an element that violates an implementation’s restrictions results in a runtime exception, typically a ClassCastException, an IllegalArgumentException, or a NullPointerException. Attempting to remove or test for the presence of an element that violates an implementation’s restrictions can result in an exception. Some restricted collections permit this usage.


Collection Implementations

Classes that implement the collection interfaces typically have names in the form of <Implementation-style><Interface>. The general purpose implementations are summarized in the following table:

Interface Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Deque ArrayDeque LinkedList
Map HashMap TreeMap LinkedHashMap

The general-purpose implementations support all of the optional operations in the collection interfaces and have no restrictions on the elements they may contain. They are unsynchronized, but the Collections class contains static factories called synchronization wrappers that can be used to add synchronization to many unsynchronized collections. All of the new implementations have fail-fast iterators, which detect invalid concurrent modification, and fail quickly and cleanly (rather than behaving erratically).

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide basic implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the implementer knows which methods must be overridden, given the performance of the basic operations of a specific implementation.


Concurrent Collections

Applications that use collections from more than one thread must be carefully programmed. In general, this is known as concurrent programming. The Java platform includes extensive support for concurrent programming. See Java Concurrency Utilities for details.

Collections are so frequently used that various concurrent friendly interfaces and implementations of collections are included in the APIs. These types go beyond the synchronization wrappers discussed previously to provide features that are frequently needed in concurrent programming.

These concurrent-aware interfaces are available:

The following concurrent-aware implementation classes are available. See the API documentation for the correct usage of these implementations.


Design Goals

The main design goal was to produce an API that was small in size and, more importantly, in “conceptual weight.” It was critical that the new functionality not seem too different to current Java programmers; it had to augment current facilities, rather than replace them. At the same time, the new API had to be powerful enough to provide all the advantages described previously.

To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle distinctions as mutability, modifiability, and resizability. Instead, certain calls in the core interfaces are optional, enabling implementations to throw an UnsupportedOperationException to indicate that they do not support a specified optional operation. Collection implementers must clearly document which optional operations are supported by an implementation.

To keep the number of methods in each core interface small, an interface contains a method only if either:

  • It is a truly fundamental operation: a basic operations in terms of which others could be reasonably defined,
  • There is a compelling performance reason why an important implementation would want to override it.

It was critical that all reasonable representations of collections interoperate well. This included arrays, which cannot be made to implement the Collection interface directly without changing the language. Thus, the framework includes methods to enable collections to be moved into arrays, arrays to be viewed as collections, and maps to be viewed as collections.

200+ Most Common Java Libraries

The Software Development Process

Over the years software engineers and developers have created systems and methods so the planning and management of the development life cycle flows smoother. Two popular ones are Agile and Scrum environments.

Here is a breakdown of the software development process and elements of each phase or stage.

Core Activities
Requirements, Design, Construction, Testing, Debugging, Deployment, Maintenance

Paradigms & Models
Software Engineering, Waterfall, Cleanroom, Incremental, Spiral, V-Model, Agile

Methodologies & Frameworks
Prototyping, RAD, UP, XP, TSP, PSP, DSDM, MSF, Scrum, Kanban, Dual Vee Model, TDD, ATDD, BDD, FDD, DDD, MDD, IID, Lean, DevOps

Supporting Disciplines
Configuration Management, Infrastructure as Code, Documentation, Software Quality Assurance (SQA), Project Management, User Experience

Tools
Compiler, Debugger, Profiler, GUI Designer, Modeling, IDE, Build Automation, Release Automation, Testing

Standards and BOKs
CMMI, IEEE Standards, ISO 9001, ISO/IEC Standards, SWEBOK, PMBOK, BABOK

Java Design Patterns Reference List and Examples

Gang of Four (GoF) Creational Patterns

Abstract Factory : Sets of methods to make various objects.

Builder : Make and return one object various ways.
Factory Method Methods to make and return components of one object various ways.
Prototype Make new objects by cloning the objects which you set as prototypes.
Singleton A class distributes the only instance of itself.

GoF Structural Patterns
Adapter A class extends another class, takes in an object, and makes the taken object behave like the extended class.
Bridge An abstraction and implementation are in different class hierarchies.
Composite Assemble groups of objects with the same signature.
Decorator One class takes in another class, both of which extend the same abstract class, and adds functionality.
Facade One class has a method that performs a complex process calling several other classes.
Flyweight The reusable and variable parts of a class are broken into two classes to save resources.
Proxy One class controls the creation of and access to objects in another class.
GoF Behavorial Patterns
Chain Of Responsibility A method called in one class can move up a hierarchy to find an object that can properly execute the method.
Command An object encapsulates everything needed to execute a method in another object.
Interpreter Define a macro language and syntax, parsing input into objects which perform the correct opertaions.
Iterator One object can traverse the elements of another object.
Mediator An object distributes communication between two or more objects.
Memento One object stores another objects state.
Observer An object notifies other object(s) if it changes.
State An object appears to change its` class when the class it passes calls through to switches itself for a related class.
Strategy An object controls which of a family of methods is called. Each method is in its` own class that extends a common base class.
Template An abstract class defines various methods, and has one non-overridden method which calls the various methods.
Visitor One or more related classes have the same method, which calls a method specific for themselves in another class.