Computer Science

Computer

Science

HTML

1.  Definition

2.  Format

3.  Editor Names

4.  Declaration

5.  Elements

6.  Attributes

7.  CSS

8.  Text Formatting

9.  Colors

10.      Coding Manual

11.      Links

12.      Images

13.      Favicon

14.      Tables

15.      Lists

16.      Block & Inline Elements

17.      Classes & ID

18.      Iframes

19.      JavaScript

20.      File Paths

21.      Head

22.      Layout

23.      Responsive Web Page

24.      Computer Code Elements

25.      Semantic Elements

26.      Entities & Symbols

26.1.        Emojis

26.2.        Charset

27.      URL Encoding

28.      XHTML

29.      Forms

29.1.        Form-Attributes and Elements

29.2.        Input Types-Attributes and Form Attributes

30.      Graphics

30.1.        Canvas

30.2.        SVG

31.      Media

31.1.        Media, Video & Audio

31.2.        Plug-ins and Youtube

32.      APIs

32.1.        Geolocation

32.2.        Drag-Drop

32.3.        Web-Storage

32.4.        Web Workers

32.5.        SSE

33.      jQuery

34.      C#

35.      Data Structures and Algorithms

36.      SQL Server

 

 

 

 

 

 

 

 

 

 

 

 

 

HTML

1.  Definition

It is a Language that Creates, Describes, Structures, Displays and Labels content of a Web Page

2.  Format

<html>

<head>

<title>Page Title</title>

</head>

<body>

<h1>A Heading</h1>

<p>A Paragraph</p>

</body>

</html>

3.  Editor Names

Web Page Editing Tool for PC is Notepad and for Mac is TextEdit

4.  HTML Document

It contains Source Code of the Web Page

Parts: Document Type Declaration, Container(Root) and Visible Part(Body)

<!DOCTYPE html>

<html>

<body>

<h1>Heading</h1>

<p>Paragraph</p>

</body>

</html>

5. Elements

HTML Source Code has a Structure of Elements and contains different types of Tags

Syntax for Non Empty Tag: <TagName>..Content..</TagName>

Structure & Types of Tags:

1.  Document Declaration Tag

2.  Root Element (Document Body)

3.  Head Element

4.  Body Element

5.  Sub Elements

Ø Elements can be Nested

Ø There are Empty Tags which have no Closing Tag

Structure of HTML Document and Tag Names:

 

      <!DOCTYPE>                  Document Type

      <html>                             Root

      <head>                            Head

      <body>                            Body

      <br>                                 Line Break

      <h1> to <h6>                  Headings

      <p>                                  Paragraph

 

6.  Attributes

Attributes are Properties of Elements. They are declared In Start Tag

Syntax: <TagName AttributeName = ”Value”>

      width and height             Parameters Information

      style                                  CSS Styling

      href                                   Address

      src                                     Path

7.  CSS

Methods of Adding CSS:

·     Inline (Style Properties Declared Inside Elements)

·     Internal (Style Properties Declared Inside Head)

·     External (Style Properties Declared Inside Head)

CSS can be added to HTML Document by following ways:

      style attribute                    Inline

<tagname style=”property: value;”>

      <style> element                Internally

<style>

Elementname or Reference { property: value;}

 </style>

      <link> element                  Externally

<link rel="stylesheet" href="filename.css">

8.  Text Formatting

There are many Tags for Formatting Text

9.  Colors

Colors are CSS Pre-Defined Color Names Or RGB, HEX, HSL, RGBA, HSLA Values

10.      Coding Manual

Guidelines and Tips for Creating Standard HTML Code

11.      Links

Links are used to Hyperlink. They have Various States Attributes

Syntax: <a href = “Link Address”>..Content to Hyperlink.. </a>

12.      Images

Image Element Links an Image to any given Position on Page. This Element has No Closing Tag

Syntax: <img src = “Image Link Path”>

·     Image Map

An Image Map defines a Map of Clickable areas on Image

Attribute Usemap is used in Image Element Tag for referring to an Image Map by its Name

Syntax:

<img src="Image Link Path" alt="Alternate Text" usemap="#MapName">

<map name="MapName ">

<area shape="ShapeName" coords="ShapeCoordinates" href="Link Address" onclick="EventFunction">

</map>

Here area element is clickable area in the Image

·     Background Images

Background Images can be added to a Web Page or an HTML Element by using CSS background-image or background property

Syntax:

Inline CSS Method:

<ElementName style="background-image: url('Image Link Path');">

Internal CSS Method:

<style>

ElementName {

  background-image: url('Image Link Path');

  background-repeat: Value;

  background-attachment: Value;

  background-size: Value;

}

</style>

·     Picture Element

HTML Picture Element is used to Display different version of Image for different Devices. It contains zero or more Source Elements and one Image Element

Syntax:

<picture>

  <source media="(min-width: Value)" srcset="Image Link Path">

  <source media="(min-width: Value)" srcset="Image Link Path">

  <img src="Image Link Path">

</picture>

The browser checks for the matching source element for the device, if not found source of image element is displayed

13.      Favicon

It is Image Next to Page Title. Link for it is Defined in Head

Syntax:

<head>

  <title>Page Title</title>

  <link rel="icon" type="image/x-icon" href="Icon Link Path">

</head>

Link Element to Display a Favicon

14.      Tables

Table contains Cells and Headers inside Row Elements

Syntax:

<table>

  <tr>

    <th>Header Cell</th>

  </tr>

  <tr>

    <td>A Cell</td>

  </tr>

</table>

A Table Declaration with <tr> Tag as Rows

15.      Lists

List is a Grouping of Related Items

·     UL-Unordered List

Syntax:

<ul>

  <li>List Item</li>

</ul>

An Unordered List Declaration with <ul> Tag as Assembly

·     Styling

There can be various CSS Styling Properties for Lists

Values for CSS Property list-style-type for UL:

Disc, Circle, Square & None

·     OL-Ordered List

Syntax:

<ol>

  <li>List Item</li>

</ol>

An Ordered List Declaration with <ol> Tag as Assembly

·     Attributes

    There can be various Attributes for Ordered Lists

Values for Type Attribute:

“1”, “A”, “a”, “I” & “i”

 

·     DL-Description List

Syntax:

 <dl>

  <dt>Term</dt>

  <dd>..Description..</dd>

</dl>

A Description List with <dl> Tag as Assembly

16.      Block & Inline Elements

Block Level Elements: These Elements Starts in a New Line and Takes Full Width

Inline Level Elements: These Elements Does Not Start in a New Line and Takes Necessary Width

17.      Classes & ID

These Attributes are used to Refer or Mark Elements in the Document

Syntax:

Class

<TagName class="ClassName">..Content..</TagName>

ID

<TagName id="ID_Name">..Content..</TagName>

Denotation for Referring:

Class   .ClassName

ID        #ID_Name

Both are used in Style Attributes of CSS and in Methods of JavaScript

ID is Unique unlike Classes

Both Properties are used By CSS & JavaScript

18.      Iframes

Iframe Elements are used for Inline Nesting of Web Page inside a Web Page

Syntax:

<iframe src = "Link Address"></iframe>

An Inline Frame Declaration

19.      JavaScript

Defines Client Side Script Externally or Internally

JavaScript uses <script> tag and can be used to modify Content, Style and Attributes of HTML Elements

Syntax:

<script>

1.  document.getElementById("ID_Name").innerHTML = "..Some Text Content..";

2.  document.getElementById("ID_Name ").style.color = "ColorName";

3.  document.getElementById("ID_Name ").src = "ImagePath";

</script>

Above is Example of JavaScript Code with Methods having different Properties

20.      File Paths

Used for Linking to External Files from Web Site Folder Structure-Absolute(Full URL), Relative(Localhost)

21.      Head

Contains Metadata (Data about Data) Tags

Examples:

<head>

1.  <title>Page Title</title>

2.  <style>

ElementName or Reference {Property: Value;}

</style>

3.  <link rel="stylesheet" href="Link Address">

4.  <meta charset="CharsetName">

5.  <script>

document.getElementById("ID_Name").innerHTML = "..Some Text Content..";

</script>

</head>

Above are different Examples of Head Elements which are Metadata for HTML Document

22.      Layout

Layouts are used to Display a Website in Structured Form with Multiple Sections. There are several Semantic Elements in HTML which define different parts of a Web Page

A Web Page Layout:              Semantic Elements:

<header>      Header of Document

<nav>            Navigation Panel

<section>     Section in Document

<article>       Independent Article

<aside>        Content Aside

<footer>       Footer of Document

<details>      Details of Document

<summary> Heading for <details>                                                              

Layout Techniques:

1.  CSS framework

It is a Library containing Premade Metadata Files which are used for Building Web Projects. CSS Frameworks comply with Standard Web Design Practices

There are many types of CSS Frameworks, they can differ in features. Some popular Frameworks are:

Bootstrap

Foundation

2.  CSS float property

Float Property is used to Position an Element in a Web Page. It is used to set Position of an Element Left or Right in a wrapped around Content Layout

Syntax:

ElementReference {

                                           float: value;

   }

3.  CSS grid

CSS Grid is a two-dimensional Layout consisting of Rows and Columns for Designing a Web Page

Syntax:

ElementReference {

                                           display: grid;

   }

4.  CSS flexbox

CSS Flexbox is a one-dimensional Flexible Box Layout consisting of Flex Container and Child Elements. Child Elements can be set in any Direction and have Flexible Size

It is a Responsive Web Layout that can adjust according to User Interface

Syntax:

ElementReference {

                                           display: flex;

   }

23.      Responsive Web Page

In Responsive Web Design HTML & CSS are used to Automatically Modify Dimensions and Visibility of a Web Page according to a Device

To Create a Responsive Website a Viewport can be set using <meta> tag in the Head Element

Syntax:  

<meta name="viewport" content="width=device-width, initial-scale=1.0">

 

24.      Computer Code Elements

These Elements are used for defining Text for required Display Format

Examples:

<code> Computer Code

<kbd>   Keyboard Input

<var>    Variable

<samp>Program Output

<pre>    Preformatted Text

25.      Semantic Elements

These Elements Describe their Meaning to Browser and Developer

26.      Entities & Symbols

Character Entities are used to Display Reserved Characters and Symbols

Syntax:

&EntityName; 

  OR 

&#EntityNumber; 

26.1.        Emojis

UTF-8 Character Set is used to Display Emoji Characters

Syntax to Apply Character Set:

<meta charset="UTF-8">

26.2.        Charset

Character Set must be used to Display a Web Page Correctly

27.      URL Encoding

URL is Address of a Document. It is used by Servers to Request Pages

28.      XHTML

XHTML is Stricter Version of HTML. HTML Code is not Compatible with all Devices

29.      Forms

Form Element is used to Create an HTML Form for User Input and often sent to a Server for Processing

Syntax:

<form action="Server URL" method="get|post"> 

             .

             .

   Input Elements

             .

             .

</form> 

29.1.        Form-Attributes and Elements

Form Attributes are Properties of Form Elements. They are specified in Start Tag

 

Form Attributes:

1.  accept-charset          Character Encodings used for Form Submission

2.  action                          Address of Form Data Submission

3.  autocomplete            Form Auto complete On or Off (only for method="post")

4.  method                       HTTP Method used during Sending Form Data

5.  novalidate                  For setting Form as Non Valid

6.  rel                                Relation between Linked source and Document

7.  target                          Display Response Type while submitting

Some Form Elements:

      <button>                  Clickable Button

      <datalist>                List of Pre-Defined Options for Input Controls

      <fieldset>                Groups Related Elements in Form

      <input>                    Input Control

      <label>                     Label for an <Input> Element

      <legend>                 Caption for a <fieldset> Element

      <option>                  Option in a Drop-Down List

      <select>                   Drop-Down List

      <textarea>               Multiline Input Control

 

29.2.        Input Types

Input Types:

      button

      checkbox       

      text

      radio      

      submit

      reset

      image    

      password                                

      file  

Syntax:

<input type="">

Attributes:

      value

      size

      maxlength

      step

      autofocus

      list

Restriction Attributes:

      disabled

      checked

      readonly

      required

30.      Graphics

30.1.        Canvas

It is a Rectangular Container for Graphics. It uses JavaScript to draw Graphics

Syntax:

<canvas id="idname" width="" height="" style="border:1px solid Red;">

Your browser does not support the HTML canvas tag</canvas>

<script>

function funct() {

  var c = document.getElementById("idname");

  var ctx = c.getContext("2d");

  ctx.fillRect(0,0,0,0);

}

</script>

30.2.        SVG

It is a Container for Graphics in which Shapes are Drawn as Objects in XML Format

Syntax:

<svg width="" height="">

<circle cx="" cy="" r="" stroke="colorname" stroke-width="" fill="colorname" />

</svg>

31.      Media

Multimedia Elements are Stored in Media Files identified by Extension

31.1.        Video & Audio

These Elements are used to Show or Play a Multimedia File on a Web Page

Syntax for Video Element:

<video width="" height="" controls>

  <source src="filename.extension" type="filetype/extensionname">

Your browser does not support the video tag.

</video>

      Syntax for Audio Element:

<audio controls>

  <source src="filename.extension" type="filetype/extensionname">

Your browser does not support the audio element.

</audio>


31.2.        Plug-ins and YouTube

Plug-ins are Programs that Extend the Standard Functionality of the Browser

Object Element:

<object width="" height="" data=" filename.extension "></object>

Embed Element:

<embed width="" height="" src=" filename.extension">

YouTube Videos can be Embedded in HTML Code using Video ID

<iframe width="" height="" src="fileURL">

</iframe>

 

32.      APIs

32.1.        Geolocation

This API is used to get the Geographical Position of a User if it gets Approved

Syntax:

<button onclick="getlocation()">Click me</button> 

<div id="location"></div> 

<script> 

    var x= document.getElementById("location"); 

    function getlocation() { 

        if(navigator.geolocation){ 

            navigator.geolocation.getCurrentPosition(showPosition) 

          } 

        else 

        { 

             alert("Sorry! your browser is not supporting") 

         } } 

      

     function showPosition(position){ 

       var x = "Your current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")"; 

                document.getElementById("location").innerHTML = x; 

     } 

</script> 

32.2.        Drag-Drop

It is an API to Drag and Drop Elements

Syntax:

<script> 

function allowDrop(ev) {ev.preventDefault();} 

function drag(ev) {ev.dataTransfer.setData("text/html", ev.target.id);} 

function drop(ev) { 

ev.preventDefault(); 

var data = ev.dataTransfer.getData("text/html"); 

ev.target.appendChild(document.getElementById(data)); 

</script> 

<p>Drag the Element:</p> 

<div id="div1"   ondrop="drop(event)" ondragover="allowDrop(event)"></div> 

<br> 

<img id="drag1" src="" alt=""   draggable="true" ondragstart="drag(event)"/> 

32.3.        Web-Storage

With it Web Applications can Store Data Locally in Browser

Types of Web Storage:

1.  Local Storage                 uses Windows.localStorage Object, Stores Data with no Expiration

2.  Session Storage             uses Windows.sessionStorage Object, Stores Data for one Session

32.4.        Web Workers

It is a JavaScript running in the Background without affecting the Performance of the Page

Syntax:

var worker= new Worker('worker.js'); 

32.5.        SSE (Server Sent Event)

It allows a Web Page to Automatically get Updates  from a Server

Example:

var source = new EventSource("SSEfile.php");

source.onmessage = function(event) {

  document.getElementById("output").innerHTML += event.data + "<br>";

};

33.      jQuery

jQuery is a JavaScript Library that Shortens JavaScript Code into Methods and Simplifies Code

In jQuery Elements can be selected to perform required action. They can be linked to Events to Execute the given Code 

Syntax:

1.  Element Selector

$(Selector).action()

2.  Events

$(Selector).Event(function(

      Declaration

});

Selectors

jQuery Selectors are used to Select and Manipulate HTML Elements

Syntax:

$(ElementReference)

Events

Events are declared in the HTML Source Code. When an Event is Triggered it is detected by the Web Application to Execute Code linked to it

Syntax:

$( ElementReference).Event(function(){

        Code

});

Effects

With jQuery Effects can be added to a Web Page

Types:

Display Effects

Fade Effects

Slide Effects

Animate Effect

Other Effects

HTML/CSS

jQuery contains Methods for Manipulating Elements of HTML Document and for CSS

Functions:

HTML Methods are used to Set or Return Attribute Values or Content of HTML Elements

CSS Method is used to Set or Return Style Properties of HTML Elements

Traversing

Traversing Methods are used to Move Through HTML Document (DOM Tree) and Select Elements based on their Relation to Elements

Elements in DOM Tree

Ancestors

Descendants

Siblings

Filtering

Filtering Methods are used to Select Elements according to Some Criteria

Syntax:

$( ElementReference).MethodName();

Ajax

Ajax is Asynchronous JavaScript and XML. It is used to Receive and Send Data in the Background without Loading the Whole Page

Ajax Methods:

jQuery Ajax Methods are used to Send Asynchronous Request for Content to a Server using HTTP Get and HTTP Post

Properties

Some jQuery Properties:

jquery    

jQuery.fx.interval         

jQuery.fx.off 

jQuery.support    

length    

34.      C#

It is an OOP Language created by Microsoft that runs on .NET Framework

Basics

Syntax:

using System;

 

namespace HelloWorld

{

  class Program

  {

    static void Main(string[] args)

    {

      Console.WriteLine("Output Text");   

    }

  }

}

Control Statements

If-Else

If-else Statement is used to Check the Logical Validity of a Condition and Execute the Code Accordingly

Syntax:


If Statement

If Else Statement

if(condition)

{

  Code if True

}



if(condition){ 

  Code if True

}

         else{   

  Code if False

} 


Switch

Switch Statement is used to Execute a Single Code Block from Multiple Code Blocks after Matching the Case with given Expression

Syntax:

switch(expression)

{   

case “value”:   

   Code 

 break; 

        .

        . 

default:    

   Code 

 break; 

}   

While-Loop

It is used to Iterate a Block of Code till the given Condition Proves Invalid

Syntax:

while (condition)

{

     Code till Condition is Valid

}

Do-While Loop

It is used to Execute a Block of Code at Least Once and then Iterate it till the given Condition Proves Invalid

Syntax:

do

{

     Code

}

while (condition);

For Loop

It is used to Iterate a Block of Code till the given Condition Proves Invalid. For Loop is much Compact in Declaration

Syntax:

for(initialization; condition; increment/decrement;)

                          Code

For Loop

It is used to Loop through Elements in an Array

Syntax:

foreach (type VariableName in ArrayName)

{

                          Code

}

Break

Break Statement is used to Exit a Loop

Syntax:

Loop

{

         break;

}

Continue

Continue Statement Skips the Remaining Code in a Loop

Syntax:

Loop

{

         Code

continue;

         Code

}

Goto

Goto Statement is used to Skip to Specified Label in a Program

Syntax:

goto LabelName;

Functions

A Function is a Set of Statements contained in a Block of Code

Syntax:

class Program

{

  static void FunctionName()

  {

        Code

  }

}

Arrays

They are Data Types which are used to store Multiple Values in a Single Variable at Contiguous Memory Locations

Declaration Examples:

int[] arr = new arr[5];

int[] arr = new arr[5]{1, 2, 3, 4, 5};

int[] arr = new arr[]{1, 2, 3, 4, 5};

int[] arr = {1, 2, 3, 4, 5};

Strings

A String is a Data Type which Contains Collection of Characters

Declaration Examples:

string is a Keyword which is an alias of System.String Class

string str = “ABCD”;

String str=”ABCD”;

char[] ch = { 'A', 'B', 'C', 'D' }; 

string str = new string(ch); 

String Methods:

Concatenation

Methods for Joining Strings

1.  string.Concat(String,String)

2.  + Operator:

String + String

Interpolation

Methods to Embed String Variables inside a String

$”Text{StringName}Text”

Here $ is String Interpolation Operator

Accessing Strings

Methods for Accessing Strings

1.  Index Number inside [] Brackets

For Accessing a Character

2.  StringName.IndexOf(StringCharacter)

For Accessing Character Index

3.  StringName.Substring(StartingIndex)

For Accessing Substring

 

Special Characters

Special characters are predefined characters that modify a String

 Backslash (\) character turns special characters into string characters

\'          '        Single Quote

\"          "      Double Quote

\\         \      Backslash

\n                  New Line       

\t                  Tab 

\b                  Backspace

OOP

OOP is Object Oriented Programming. It is an Objects Creation Based Programming Procedure which Operates by the use of Functions and Data

Compared to Procedural Programming there is much Efficient use of Code

Classes and Objects

In OOP Language Classes and Objects are used for an Application. Objects are Instances of a Class

Declaration Example:

class WebPage

{

  string color = "red";

 

  static void Main(string[] args)

  {

    WebPage newpage = new WebPage();

    Console.WriteLine(newpage.color);

  }

}

Constructors

It is a Method for Initializing Content and Data Member Instances of an Object

Types:

1.  Default Constructor

2.  Parametrized Constructor

Syntax:

Default Constructor

   class WebPage

    { 

        public WebPage() 

        { 

            Console.WriteLine("Default Constructor Invoked"); 

        } 

        public static void Main(string[] args) 

        { 

            WebPage obj1 = new WebPage(); 

        } 

    }

Output: Default Constructor Invoked

Parameterized Constructor

class WebPage

    { 

          public String title;

        public WebPage(String str) 

        { 

               title=str;

        } 

         public void display() 

        { 

            Console.WriteLine(“Page Title :  ” + title); 

        } 

        public static void Main(string[] args) 

        { 

            WebPage obj = new WebPage(“DotNet”); 

            obj.display();

        } 

    }

Output: Page Title : DotNet

Destructors

Destructors are Opposite of Constructors. They are used to Clear the Initialization of Objects. They are Declared once and Invoked Automatically

Syntax:

  class WebPage

    { 

        public WebPage () 

        { 

            Console.WriteLine("Constructor Invoked"); 

        } 

        ~ WebPage () 

        { 

            Console.WriteLine("Destructor Invoked"); 

        } 

       public static void Main(string[] args) 

        { 

            WebPage obj = new WebPage ();

        } 

    } 

Output: Constructor Invoked

               Destructor Invoked

Ø Destructor don’t have Parameters and cannot have Modifiers

This

This Operator is used to Refer to the Current Instance of a Class

Syntax:

 this.InstanceName

Static

Static is a Modifier Keyword that is used for defining Data Members as Type Static. It is used for Global Declaration

Ø Static can be field, method, constructor, class, properties, operator and event

Static Class

Static Class cannot have Objects and can only have Static Members

Static Constructor

It is used to Initialize the Static Members of a Class

Access Modifiers

They are used to Set Scope of Classes, Variables or Methods

Access Modifier

Accessibility Level

public:

 

Access isn't restricted

file:

 

current source file

internal:

 

current assembly

protected internal:

 

current assembly or types derived

protected:

 

containing class or types derived

private protected:

containing class or types derived within the current assembly

 

private:

 

containing class

Properties

Properties are used to Access the Private Members of a Class. Properties are Extension Unit of Fields

Syntax:

class WebPage

{

  private string title; // field

 

  public string Title   // property

  {

    get { return title; }   // get method

    set { title = value; }  // set method

  }

}

Inheritance

It is a process in which a Class Inherits Properties of another Class

There are 2 Types Classes in Inheritance:

1.  Base Class (Parent Element)

2.  Derived Class (Child Element)

Syntax:

   class WebPage                      // base class (parent)

    { 

       public string pageName = “WebPage”; 

   } 

   class Iframe : WebPage        // derived class (child)

   { 

       public string frameName = “Iframe”; 

   } 

   class Website

  { 

       public static void Main(string[] args) 

        { 

            Iframe obj = new Iframe();    //object of derived class 

            Console.WriteLine("Frame: " + obj.frameName); 

            Console.WriteLine("Page: " + obj.pageName); 

        }

 } 

Polymorphism

Polymorphism means having many Forms. In OOP Same Property can have many Functionalities. It is Implemented in Classes with Inheritance

Types:

Compile Time

Method Overloading and Operator Overloading are used for it and is also called Static Binding or Early Binding

Run Time

Method Overriding is used for it and is also called Dynamic Binding or Late Binding

Overloading

It is a property of OOP in which two or more Members are Created with Same Name and different Type or Number of Parameters  

Example:

   class WebPage                     

    { 

         public static string Iframe(string title)

{  

                     return title;  

          }  

          public static int Iframe(int number)  

          {  

                     return number;  

          }  

   } 

   class Website

  { 

       public static void Main(string[] args) 

        { 

            Console.WriteLine(WebPage.Iframe(“Iframe”)); 

            Console.WriteLine(WebPage.Iframe(1)); 

        }

 }

Output: Iframe

               1 

Overriding

It is a property of OOP in which a Derived Class has Method with same Name as in Base Class. There can be Specific Implementation of a Method

Example:

   class WebPage                      // base class

    { 

       public virtual void Image() //virtual function

       {

          Console.WriteLine(“This image shows a server”);

       }

   } 

   class Iframe : WebPage        // derived class

   { 

       public override void Image()      //method overriding

       {

          Console.WriteLine(“This image shows a computer”);

       }

   } 

   class Website

  { 

       public static void Main(string[] args) 

        { 

            Iframe obj = new Iframe();    //object of derived class 

           obj.Image();

        }

 }

Output: This image shows a computer 

Abstraction

It means showing only Necessary details and hiding Internal Functionality. In C# there are Abstract Classes and Interfaces where Data Abstraction is Implemented

Abstract Class

It can only be Accessed by the use of a Derived Class and cannot be Instantiated

Abstract Method

It does not have Body and can only be Declared in Abstract Class. Its Implementation can be done in a Derived Class

Ø Abstract Method is Internally a Virtual Method

Syntax:

public abstract class Grid                            // abstract class declaration

{

  public abstract void inputDimensions(); // abstract method declaration

}

class WebPage : Grid                                  //implementation in a class

{

  public override void inputDimensions()

  {

      int w, h;

      Console.WriteLine("Width:");

      w = Console.ReadLine();                      //body of method          

      Console.WriteLine("Height:");

      h = Console.ReadLine();                       

  }

}

class Website

{

  static void Main(string[] args)

  {

      WebPage obj = new WebPage();          //object

      obj. inputDimensions ();

  }

}

Output: Width: 100

              Height: 100

Interface

Interface is a Blueprint for Class and Methods to be Implemented in Class are mentioned in it. Interface itself contains Declaration only

They can only contain Abstract Methods and cannot be Instantiated

Ø By default, Interface methods are public and abstract. They cannot be explicitly defined as same

Ø An Interface can contain properties and methods, variables are not supported

Syntax:

interface Layout

{

  void displayHeader();                      // method declaration

}

class WebPage : Layout                     //implementation in a class

{

  public void displayHeader()

  {

    Console.WriteLine("Network");    //body of method

  }

}

class Website

{

  static void Main(string[] args)

  {

      WebPage obj = new WebPage();  // object

      obj.displayHeader();

  }

}

Output: Network

Structure

It is a User Defined Data Type which can contain Fields and Methods as Sub Parts. It can be Instantiated in a Class

Syntax:

using System; 

public struct HTML

    public string Root; 

    public string Body;

class Website

    public static void Main(string[] args) 

    { 

        HTML obj = new HTML(); 

        obj.Root = “HTML Tag”;

        obj.Body = “Body Tag”;

        Console.WriteLine(obj.Root); 

        Console.WriteLine(obj.Body);     

    } 

}

Output: HTML Tag

              Body Tag 

Ø Structures can’t inherit, they can be used to implement interfaces

Ø Fields and properties can’t be initialized at declaration

Enums

Enums are User Defined Data Types in which there can be defined Set of Constant Variables. They have associated Numeric Values as Pre-Defined

Syntax:

using System;

enum CSS

    {

      Color,               // Default Value 0

      Font                 // Default Value 1

    }

class Website

  {

    static void Main(string[] args)

    {

      int var = (int) CSS.Font; //Explicit conversion to int to

                                                    show associated value

      Console.WriteLine(var);

    }

  }

Output: 1

Ø Associated variable values can be explicitly specified

Ø Enums can be declared inside a class or struct, or outside

Exception Handling

Exception Handling is used to Define the Output of an Error or an Exception for a Block of Code

There are 4 Properties of System.Exception Class for Exception Handling:

Try

This Code Block is used to Test Code for Errors

Catch

This Code Block is Executed if there occurs an Exception in Try Block

Finally

This Code Block is Executed after Try and Catch Block

Throw

This Statement is used to Create a Custom Error

Example:

   class Website

  {

    static void Main(string[] args)

    {

Try                                             //Try block

{

  int var = “string”;

}

catch (Exception e)               //Catch block

{

  Console.WriteLine("Error in code");

}

Finally                                  //Finally block

{

  Console.WriteLine("This is finally block");

}

}

  }

Output: Error in code

               This is finally block

Custom Exception Example:

class NotAnIntException : Exception 

    public NotAnIntException(String message) : base(message) 

    { 

 

    } 

class Website

    public void validate(int var) 

    { 

        bool Valid;

        foreach (char ch in var)

       {

            if (!Char.IsLetter(ch))

             Valid = false;

        }

        if (Valid) 

        {  

            throw new NotAnIntException("Not an Integer");  //Throw

                                                                                               statement

        } 

    } 

    public static void Main(string[] args) 

    { 

        try 

        { 

            validate(“string”); 

        } 

        catch (NotAnIntException e)

        { 

            Console.WriteLine(e);

        } 

    } 

Output: NotAnIntException: Not an Integer

Files

File and FileStream Classes from System.IO Namespace are used for File Operations

Examples:

using System; 

using System.IO; 

public class FileExample 

    public static void Main(string[] args) 

    { 

string writeText = "Text Content"; 

File.WriteAllText("FileName.txt", writeText); 

string readText = File.ReadAllText("FileName.txt"); 

Console.WriteLine(readText);

    } 

Output: Text Content

Here WriteAllText() Method is used to Create File and Write Text to it

ReadAllText() Method is used to Read Content of File

 

using System; 

using System.IO; 

public class FileStreamExample 

    public static void Main(string[] args) 

    { 

        FileStream f = new FileStream("c:\File.txt", FileMode.OpenOrCreate);

        f.WriteByte(65);

        f.Close();

    } 

Output: A

Here FileStream Class is used to Write Single Byte Data into File

OpenOrCreate File Mode is used for Read and Write Operations

 

using System; 

using System.IO; 

public class FileStreamExample 

    public static void Main(string[] args) 

    { 

        FileStream f = new FileStream("c:\File.txt", FileMode.OpenOrCreate); 

        int i = 0; 

        while ((i = f.ReadByte()) != -1) 

        { 

            Console.Write((char)i); 

        } 

        f.Close(); 

    } 

}

Output: A

Here ReadByte() Method of FileStream Class is used to Read Single Byte from the   File

Classes

System.IO Namespace contains various Classes for different File Operations

Methods

The File Class of System.IO Namespace provides Methods for Manipulating Files

Data Conversion

It is Encoding and Decoding of Data. There are two Process for Data Conversion:

Serialization

It is a process of converting Object into byte Stream to that it could be saved to Memory, Database or File

Deserialization

It is a process of converting byte Stream saved in Memory into Object for Reading

35.      Data Structures and Algorithms

It is Storage of Data in Memory so that it can be used Efficiently

Introduction

Terms

Data

Data is a Set of Values stored in a Data Structure

Group Items

They are Data items divided into Sub Categories

Record

It is information linked to a Single Entity in a Table

File

It is a Stored Collection of Records and Fields

Entity

An Entity is a Row Item Object in a Database Table  

Attribute

An Attribute is an Entity Field in a Database Table

Field

It is a Datatype Container. A Single Item of Data is called a Single Field 

Need

Fast Data Search

Simultaneous Multiple Requests

Efficient Processor Utilization

Advantages

Efficiency

Reusability

Abstraction

Types

Primitive Data Structures

·     Integer, Long, Character, Float & Double

Non-Primitive Data Structures

·     Linear Data Structures

1.  Static

Array

2.  Dynamic

Linked List

Stack

Queue

·     Non-Linear Data Structures

Tree

Graph

Operations

Search

Sort

Insert

Update

Delete

Algorithms

Characteristics

Unambiguous: An Algorithm should be Clear in meaning and its Function

Input: An Algorithm should have 0 or more Input Values

Output: An Algorithm should have 1 or more Output Values  

Finiteness: An Algorithm should have Limited number of Steps

Feasibility: An Algorithm should be Feasible with available Resources

Independent: An Algorithm should be Independent of any Programming Language

Procedure for Creating

Algorithm Analysis

Priori Analysis

Posterior Analysis

Algorithm Complexity

Time Complexity

Space Complexity

Approaches for an Algorithm

Brute force algorithm

Divide and conquer

Greedy algorithm

Dynamic programming

Branch and Bound Algorithm

Randomized Algorithm

Backtracking

Data Structure Types

Array

It is defined as collection of similar Data Types stored at Contiguous Memory Locations

Linked Lists

It is a Linear Data Structure in which there are connected Nodes stored at Random Memory Locations. A Node contains a Data Part and Address Part

There can be many types of Linked Lists

Stack

A Stack is a Linear Data Structure that follows LIFO Principle. It is container of Data Items in which Pushing and Popping can be done from one End

Queue

A Queue is a Linear Data Structure that follows FIFO Principle. It is container of Data Items in which Enqueuing can be done from Rear End and Dequeuing can be done from Front End
Tree

A Tree is a Non-Linear Data Structure in which there is Hierarchal Storage of Data having Multiple Levels. It is Structure of Data Items which are stored as connected Nodes. Each Node contains a Data Part, Address of Left Child Node and Address of Right Child Node

Graph

A Graph is a Non-Linear Data Structure in which there is Storage of Data using Adjacency Matrix. It is Collection of Data Items which are stored as connected Vertex Nodes. Each Vertex Node contains a Data Part and Address of Adjacent Node

There can be many types of Graphs

Searching

Linear Search

In this Method of Searching, a List is Traversed Sequentially till the Element to be Searched is found

Binary Search

In this Method of Searching, a Sorted List is divided into 2 parts. Then the Middle Element is compared with the Element to be Searched, if it doesn’t match, then the Half of List is used as new List for Search

Sorting

Sorting is used for Arranging List Data in a Particular Order

Bubble Sort

Adjacent Elements are repeatedly Swapped if not found in Order

Heap Sort

Root Element of List Max Heap is placed Repeatedly at the End of the List

Insertion Sort

An Element is assumed sorted as Sub-List then next Element is fitted in this Sorted Sub-List, then the list is incremented by one Element

Merge Sort

A List is Divided into smallest Sub-Parts. Then adjacent Units are Compared and then Combined after Sorting, process is repeated

Quick Sort

A Pivot is selected from the List, then a new List is made keeping smaller Elements to the Left and greater Elements to the Right of List after comparisons with Pivot, then the List is recursively Divided along with same process

Selection Sort

Smallest Element from the List is placed at starting of the List, then this Part is defined as Sorted List. Remaining List becomes the new List for the same Process. Recursion is done until complete Sorting

36.  SQL Server

SQL Server is RDBMS Software developed by Microsoft. It is called as MS SQL Server and acts as Database Server which uses SQL as Query Language

SQL

SQL is a Structured Query Language used to Create, Access and Manipulate Databases

RDBMS

Features

1.    RDBMS applications store data in a tabular form

2.    The tables have an identifier field called primary key and the data values are stored in the form of records in tables

3.    Relationship between these data values is also stored as well

4.    There is Normalization present in records

5.    RDBMS defines the integrity constraint for the purpose of ACID (Atomicity, Consistency, Isolation and Durability) property which supports minimal use of memory

6.    It supports relationship between data to access the stored information

7.    RDBMS supports distributed database

8.    RDBMS is designed to handle large amount of data. it supports multiple users

Architecture

Client

Data Transmission

Server

Processing

Execution

Storage

Backup Cycle

Components

SQL Server Network Interface

It is a Network Protocol Layer used to connect Database Instance to a Server

Ø A network protocol is a set of data transmission rules

There are 3 main Network Protocols:

Shared Memory Protocol

It is used by the Clients to connect to SQL Server Instance running on the same machine

TCP/IP Protocol

It is the most commonly used protocol for Client-Server Connectivity

Named Pipes Protocol

It is used for LAN (Local Area Network)

SQL Server Database Engine

A Database Engine is a Software component of SQL Server and is the core service for Storing, Processing, and Securing data

SQL Server OS

It provides User Interface Services

Instances

There can be made Instance of a SQL Server Installation. Each Instance is run by a Single SQL Service

Ø SQL server instance is a copy of server files, databases and security credentials

Primary Instances

Primary Instances can be accessed by their IP addresses or Server Names

Named Instances

Named Instances can be accessed using a backslash and the Name of the Instance

Database Operations

Login

A Login is a Set of Credentials used to gain access to SQL Server and which requires proper authentication. Login can be done using SQL Server Management Studio

Create

Syntax:

CREATE DATABASE DatabaseName

Select

Syntax:

USE DatabaseName

Drop

Syntax:

DROP DATABASE DatabaseName

Database Management

There are different Commands for Database Management:

DML (Data Manipulation Language)

SELECT

Syntax:

Select *

FROM TableName

INSERT

Syntax:

INSERT INTO TableName(Field1Name, Field2Name, …)

VALUES(Field1Value, Field2Value, …)

UPDATE

Syntax:

UPDATE TableName

SET FieldName = Value

WHERE FieldName = Value

DELETE

Syntax:

DELETE

FROM TableName

WHERE FieldName = Value

DDL (Data Definition Language)

CREATE

Syntax:

CREATE TABLE TableName(FieldName1 DataType, FieldName2 DataType);

ALTER

Syntax:

ALTER TABLE TableName

ADD FieldName DataType

DROP

Syntax:

DROP TABLE TableName

RENAME

Syntax:

RENAME OldTableName TO NewTableName

DCL (Data Control Language)

GRANT

Syntax:

GRANT SELECT, INSERT, UPDATE, DELETE ON TableName TO Username

DENY

Syntax:

DENY UPDATE ON TableName TO Username

REVOKE

Syntax:

REVOKE INSERT ON TableName TO Username

TCL (Transaction Control Language)

BEGIN TRAN

COMMIT TRAN

ROLLBACK

Syntax:

BEGIN TRANSACTION

UPDATE dbo.TableName

SET FieldName = Value

WHERE FieldName = Value

 

UPDATE TableName

SET FieldName = Value

WHERE FieldName = Value

 

IF ConditionTrue

COMMIT TRANSACTION

ELSE

           ROLLBACK TRANSACTION

Functions

There are User-Defined and Inbuilt Functions in SQL Server for performing various Operations on Data

Operators

Arithmetic operators

Relational operators

Assignment operator

Scope resolution operator

Bitwise operators

Set operators (EXCEPT and INTERSECT, UNION)

Comparison operators

String Concatenation operator

Compound operators

Unary operators

Logical operators

Keys

Primary Key

A Primary Key is a Field or Combination of Fields in a Table that is used to Uniquely Identify each Record. A Column with Primary Key cannot have NULL Values

Syntax:

Methods for defining primary key

If Table doesn’t exist:

CREATE TABLE CUSTOMER(

   ID   INT              NOT NULL,

   NAME CHAR (20)     NOT NULL,

   AGE  INT              NOT NULL,

   ADDRESS  VARCHAR (30) ,

   PRIMARY KEY (ID)

);

If Table exists:

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

Here ID attribute is defined as primary key

Foreign Key

A Foreign Key creates Relationship between two Tables and Enforces Referential Integrity in the Database. A Foreign Key can be used to Reference a Primary or Unique Key in another Table or in same Table

The Referenced Table with Primary or Unique Key is Called Parent Table and the Table having Foreign Key is called Child Table

Syntax:

Methods for defining foreign key

If Table doesn’t exist:

CREATE TABLE CUSTOMER(

   ID   INT              NOT NULL,

   NAME CHAR (20)     NOT NULL,

   AGE  INT              NOT NULL,

   ADDRESS  VARCHAR (30) ,

   PRIMARY KEY (ID)

   CONSTRAINT fk_inventory_customer 

   FOREIGN KEY (product_id) 

   REFERENCES Inventory (product_id) 

);

Here foreign key constraint on column product_id is defined, it references product_id column in inventory table

fk_inventory_customer is foreign key object 

If Table exists:

ALTER TABLE CUSTOMER

ADD CONSTRAINT fk_inventory_customer  FOREIGN KEY (product_id) 

REFERENCES Inventory (product_id);

 

Comments