Software Developer Training

Post on 10-May-2015

323 views 0 download

Tags:

description

UML, C#, RDBMS, ASP.NET MVC, JavaScript

Transcript of Software Developer Training

Software Developer TrainingSoftware Developer Training●UML diagramUML diagram●C#C#●.net standard library.net standard library●LinqLinq●DatabaseDatabase●NHibernate ORMNHibernate ORM●ASP.NET MVCASP.NET MVC●Javascript, jQuery, jQueryUI, jqGridJavascript, jQuery, jQueryUI, jqGrid●CssCss●GISGIS●Google Maps APIGoogle Maps API●Task Parallel LibraryTask Parallel Library●SubversionSubversion

UML DiagramUML Diagram

● Use case diagram● Class diagram● Sequence diagram

Use case diagramUse case diagram

● Actors● Use cases● Associations

– Include

– Extend

Class diagramClass diagram

● Class● Members

– Visibility eg. Public private protected

● Relationships– Association

● Aggreation, Composition

● Generalization● Multiplicity

0..1, 1, 0..* or *, 1..*

Sequence diagramSequence diagram

● interaction diagram that shows how processes operate with one another and in what order

C#C#● Variables and Types

● Operators

● Control Statements

● Namespace

● Class

● Method

● Properties

● Structs

● Interface

● Enum

● Generic

● Events

● Attribute

// Hello1.csusing System;

public class Hello1{ public static void Main() { System.Console.WriteLine("Hello, World!"); }}

// Hello1.csusing System;

public class Hello1{ public static void Main() { System.Console.WriteLine("Hello, World!"); }}

Variable and TypesVariable and Types

● Integral Types– Sbyte, byte, short, ushort, int, uint, long, ulong, char

● Floating Point and Decimal Types– Float, double, decimal

● String Type– Escape Sequences, verbatim string literals

● Array Type– Multidimesional Arrays

– Jagged Arrays

OperatorsOperators

Control statementsControl statements

● If, if...else, if...else if● Switch● While● Do..while● For● Foreach● Continue, break

if(...){

}

else if(...){

}

else{

}

Switch(...){

Case 1:Break;

Case 2:Break;

Default:}

for(var i=0; i<10; i++){

if(I%2==0) continue;...

}

NamespaceNamespace

● The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.

using System.Data;

namespace NavTECH.Data{

class String{

\\.....}

}

ClassClass● Class● Static class● Abstract class● Generic class● Nested class● Partial class

class Aaa{

public Aaa(){

...}

}

public static class Bbb{

static Bbb(){}

}

abstract class Ccc{

}

class ddd : Ccc{

}

class Eee<T>{

}

Class members● Fields – readonly field● Constants● Properties, Indexer● Methods● Constructor – static constructor● Events● Operator● Destructors● Nested Types

MethodMethod

● Return type → void, int, string, object, array[]● Parameters → ref, out, optional● Static method● Abstract method● Virtual, Override● Generic method● Extension method

public void DoWork(){

}

public string DoWork2(int num){

…Return str;

}

public static DoWork3(ref int num2) { }

public abstract DoWork4(out float num3);

public virtual void DoWork5(int num1, int num2 = 0){

}

PropertiesProperties

● Get● Set● Indexer

public int total{

get { return price * qty; }}

Public string FullName{

get { return firstname + lastname };set{

var strings = value.split(' ');firstname = strings[0];lastname = strings[1];

}}

StructsStructs

● useful for small data structures● No null! use with Nullable types

public struct RGB{

public int red;public int Green;public int blue;

}

InterfaceInterface

● An interface contains only the signatures of methods, delegates or events.

public interface IStatus{

char Status { get; set; } bool Equal(IStatus other);

}

Casting and Type Conversions

● Implicit Conversions● Explicit Conversions● Is, as, typeof

GenericGeneric

● Use generic types to maximize code reuse, type safety, and performance.

● The most common use of generics is to create collection classes.

public class Stack<T>public class Stack<T>{{ T[] m_Items; T[] m_Items; public void Push(T item)public void Push(T item) {...}{...} public T Pop()public T Pop() {...}{...}}}Stack<int> stack = new Stack<int>();Stack<int> stack = new Stack<int>();stack.Push(1);stack.Push(1);stack.Push(2);stack.Push(2);int number = stack.Pop();int number = stack.Pop();

EnumEnum

● An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Delegates & EventsDelegates & Events

● Delegatepublic delegate int Calculate (int value1, int value2);

public delegate void ChangedEventHandler();

● Eventpublic event ChangedEventHandler Changed;

public event EventHandler<EventArgs> Changed;

● Subscribepublisher.Changed += HandleChangedEvent;

● Unsubscribingpublisher.Changed -= HandleChangedEvent;

void HandleCustomEvent(object sender, CustomEventArgs a) { // Do something useful here. }

AttributeAttribute

● Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection.

● [DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]

● [Serializable]

● [Authorize(Roles = "Administrator, Support")]

● [SessionState(SessionStateBehavior.Disabled)]

Exception and Exception Handling

● try { … }● catch(Exception e) { … }● throw new Exception();● finally { … }● e.g. NullReferenceException, ArgumentException,

ArgumentNullException, ArgumentOutOfRangeException, FormatException, IndexOutOfRangeException, NotSupportedException, OutOfMemoryException, StackOverflowException

.net standard library.net standard library● System.Collections.Generic

– List<T>, LinkedList<T>, Queue<T>, Stack<T>, Dictionary<TKey, Tvalue>, SortedDictionary<TKey, TValue>, SortedList<TKey, TValue>

● System.String– IsNullOrEmpty, IsNullOrWhitespace, Trim, Format, Split,

ToLower

● System.DateTime– Date, Day, Hour, Minute, Second, Now

● System.TimeSpan– Add, Subtract, Days, Hours, Minutes, Seconds, TotalDays,

TotalHours, TotalMinutes, TotalSeconds

DatabaseDatabase● DBMS (Database Management System)● Relations(Table) → Tuples(Row) → Attributes(Column)

● Keys → Primary keyPrimary key, Secondary key, Candidate key, Surrogate Surrogate key,key, Composite key, Super key, Foreign keyForeign key

● Normalization → 1NF, 2NF, 3NF, BCNF, 4NF, 5NF

● Algebra of sets → Relational algebra → SQL● Query, View, CTE Query● Transaction● Index● Collation

Relational database theoryRelational database theory

● Functional dependency (FD)● Transitive dependency● Super key● Candidate key

Functional DependencyFunctional DependencyStudentID Semester Lecture TA

1234 6 Numerical Methods John

2380 4 Numerical Methods Peter

1234 6 Visual Computing Ahmed

1201 4 Numerical Methods Peter

1201 4 Physics II Simone

● StudentID → Semester.

● {StudentID, Lecture} → TA

● {StudentID, Lecture} → {TA, Semester}

● {StudentID, Lecture} is a superkey of the relation.

Transitive dependencyTransitive dependency

{Book} → {Author}{Author} does not → {Book}{Author} → {Author Nationality}

Therefore {Book} → {Author Nationality} is a transitive dependency.

SuperkeySuperkey

● A superkey is a set of attributes within a table whose values can be used to uniquely identify a tuple.

{Monarch Name, Monarch Number} (Candidate Key){Monarch Name, Monarch Number, Royal House} (trivial superkey)

● Non-prime attribute

– A non-prime attribute is an attribute that does not occur in any candidate key. Employee Address would be a non-prime attribute in the "Employees' Skills" table.

● Prime attribute

– A prime attribute, conversely, is an attribute that does occur in some candidate key.

Normal formsNormal forms

First normal form (1NF)First normal form (1NF)

● First normal form (1NF) is a property of a relation in a relational database. A relation is in first normal form if the domain of each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain.

{Customer ID} → {FirstName, Surname}{Telephone Number} → {Customer ID}

Second normal form (2NF)Second normal form (2NF)

● A table is in 2NF if and only if it is in 1NF and every non-prime attribute of the table is dependent on the whole of a candidate key.

{Employee} → {Current Work Location}{Employee, Skill}

Third normal form (3NF)Third normal form (3NF)

● The relation R (table) is in second normal form (2NF)

● Every non-prime attribute of R is non-transitively dependent (i.e. directly dependent) on every superkey of R.

{Tournament, Year} → {Winner}{Winner} → {Date of Birth}

{Tournament, Year} → {Winner} → {Winner Date of Birth}

Boyce–Codd normal form (or BCNF Boyce–Codd normal form (or BCNF or 3.5NF)or 3.5NF)

● Every non-trivial functional dependency in the table is a dependency on a superkey

{Rate Type} → {Court}{Rate Type, StartTime} → {End Time}{Rate Type, EndTime} → {Start TIme}

{Court, Start Time}{Court, End Time}{Rate Type, Start Time}{Rate Type, End Time}{Court, Start Time, End Time}{Rate Type, Start Time, End Time}{Court, Rate Type, Start Time}{Court, Rate Type, End Time}

Fourth normal form (4NF)Fourth normal form (4NF)

SQL ElementSQL Element

● Clauses● Expressions● Predicates● Queries● Statements

SQL operatorsSQL operators

● = Equal

● <> or != Not equal

● > Greater than

● < Less than

● >= Greater than or equal

● <= Less than or equal

● BETWEEN Between an inclusive range

● LIKE Search for a pattern

● IN To specify multiple possible values for a column

Data query

● Select – as, subquery● From – join, subquery● Where – In, Exists, subquery● Group by● Having● Order by - asc, desc, null first, null last● Offset, Limit

Aggregate Functions

● Count● Max, Min, Avg, Sum● First, Last

Data manipulationData manipulation

● Insertinsert into tbl(col1, col2) values(...)insert into tbl(col1, col2) select … from … where ...

● Updateupdate tbl set col1 = val1, col2 = val2 where col3 = val3

● Deletedelete from tbl where col1 = val1

● Merge (Upsert)

Data definitionData definition

● Create– Create table, create index

● Drop– Drop table, drop index

● Alter– Alter table, alter index

ConstraintConstraint

● Not null● Unique● Primary key – auto increment● Foreign key

CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

● Check● Default

ACID on TransactionACID on Transaction

● Atomicity

● Consistency

– Entity integrity eg. no primary key value can be null, no duplicate primary keys

– Referential Integrity

– Domain Integrity eg. Type, range

– User Defined Integrity eg. Age>=18 && Age<=60

● Isolation

– how/when the changes made by one operation become visible to other concurrent operations

● Durability

● Implicit transaction, Explicit transaction

● Begin, Commit, Rollback

IndexIndex

● B-tree, GIST● Cardinality● Multiple columns, Column ordering● Use with columns use by where clause, group

by, order by, join● B-tree with like '%abc' statement?● Performance impact on Insert update delete?

OthersOthers● Views, Materialized views● Triggers● Functions● Store procedures● Sequences● Table partitioning● Query cost & Query optimization● CTE Query● Window Functions

CTE QueryCTE Query

WITH regional_sales AS ( SELECT region, SUM(amount) AS total_sales FROM orders GROUP BY region ), top_regions AS ( SELECT region FROM regional_sales WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales) )SELECT region, product, SUM(quantity) AS product_units, SUM(amount) AS product_salesFROM ordersWHERE region IN (SELECT region FROM top_regions)GROUP BY region, product;

NHibernate ORMNHibernate ORM

● Persistent class● Mapping● ISession, Transaction● Linq Query, QueryOver, HQL● Native SQL● Tools

– FluentNHibernate (Mapping by code)

– NHibernate Envers

Anonymous Methods

// Defines a delegate that takes an int and returns an intpublic delegate int ChangeInt(int x); // Define a method to which the delegate can pointstatic public int DoubleIt(int x){ return x * 2;}

ChangeInt myDelegate = new ChangeInt(DelegateSample.DoubleIt);Console.WriteLine("{0}", myDelegate(5));

ChangeInt myDelegate = new ChangeInt( delegate(int x) { return x * 2; });Console.WriteLine("{0}", myDelegate(5));

Lambda Expression

ChangeInt myDelegate = x => x * 2;Console.WriteLine("{0}", myDelegate(5));

ChangeInt myDelegate = (int x) => x * 2;Console.WriteLine("{0}", myDelegate(5));

// Defines a delegate that takes two ints and returns an intpublic delegate int MultiplyInts(int arg, int arg2);

MultiplyInts myDelegate = (a, b) => a * b;Console.WriteLine("{0}", myDelegate(5, 2));

Statement Lambda Expression

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where( x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i);

Lambda Expressions that Return Void

// Defines a delegate that takes a string and returns voidpublic delegate void OutputToConsole(string arg); static void Main(string[] args){ OutputToConsole o = a => { Console.WriteLine(a); }; o("Hello, World");}

// Defines a delegate that takes no arguments and returns voidpublic delegate void OutputHelloToConsole(); static void Main(string[] args){ OutputHelloToConsole o = () => { Console.WriteLine("Hello, World"); }; o();}

The Func Delegate Types● public delegate TR Func<TR>();

● public delegate TR Func<T0, TR>(T0 a0);

● public delegate TR Func<T0, T1, TR>(T0 a0, T1 a1);

● public delegate TR Func<T0, T1, T2, TR>(T0 a0, T1 a1, T2 a2);

● public delegate TR Func<T0, T1, T2, T3, TR>(T0 a0, T1 a1, T2 a2, T3 a3);

The Func Delegate Types

class Program{ static List<T> MyWhereMethod<T>(IEnumerable<T> source, Func<T, bool> predicate) { List<T> l = new List<T>(); foreach (T item in source) if (predicate(item)) l.Add(item); return l; } static void Main(string[] args) { int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; List<int> filteredList = MyWhereMethod(source, i => i >= 5); foreach (int z in filteredList) Console.WriteLine(z); }}

LINQ (LINQ (llanguage anguage inintegrated tegrated qquery)uery)

● IEnumerable<T>● IQueryable<T>● Lazy evaluation● Query<T> in NHibernate

LINQ OperatorsLINQ Operators● Restriction Operators → Where

● Projection Operators → Select, SelectMany

● Element Operators → First, FirstOrDefault, Last, LastOrDefault

● Partitioning Operators → Take, Skip

● Ordering Operators → OrderBy, OrderByDescending, ThenBy, ThenByDescending

● Grouping Operators → GroupBy

● Aggregate Operators → Count, Sum, Min, Max, Average

● Join Operators

● Quantifiers → Any, All

QueryOver

CustomerBox cb = null;

CustomerBox cb1 = null;

session.QueryOver<CustomerBox>(() => cb)

.WithSubquery.WhereNotExists(QueryOver.Of<GeoFence>()

.JoinAlias(gf2 => gf2.CustomerBoxes, () => cb1)

.Where(gf2 => gf2.Id == geoFenceId)

.Where(() => cb.Id == cb1.Id)

.Select(gf2 => gf2.Id)) .Where(Restrictions.On<CustomerBox>(cb3 => cb3.CalledName).IsInsensitiveLike(search.CalledName, MatchMode.Anywhere))

Native Query

session.CreateSQLQuery(sql)

.AddEntity("bd", typeof(BoxData))

.AddScalar("cellsite_name", NhibernateUtil.String)

//.SetParameterList("userGroupId", userGroupIds)

.SetTimestamp("startDate", DateTime.Now - TimeSpan.FromDays(30))

.SetString("username", username)

.List()

select {bd.*}, c.name as cellsite_name

from v_user_realtime_9 urv left outer join nt_z_box_data bd on b.boxid = bd.boxid and b.latest_box_data_boxdatadate = bd.date left outer join nt_cellsite c on bd.cellsite_id = c.id

where urv.username = :username and date = :startDate

ASP.NET MVCASP.NET MVC

● Model-View-Controller

● Controller, Action

● View, Razor

● Filter, Routing

● Membership, Roles

● HTML

● Css, Bootstrap

● JavaScript

● i18n (internationalization)

MVC

Controllers

● Action methods● Attributes

– [HttpPost, ActionName("Delete")], [Authorize]

● Model Binding● ActionResult

– EmptyResult, ContentResult, FileContentResult

● HttpContext● Cookies

Views

● Razor view● HTML Helpers

– Html.DisplayFor, Html.ActionLink, Html.HiddenFor

● Layout● Section● Partial views

Controller – View data

● ViewBag● ViewData● TempData● ViewModel

Model

● Data Annotations– [Required], [Range(1, 100)], [StringLength(5)]

– [DataType(DataType.Date)]

– [Display(Name = "Current password")]

ASP.NET MVC Others

● Filters

● Routes

● Bundles

● i18n (internationalization)

JavaScriptJavaScript

● Function● Prototype● Closure → this● Callback● Class and Visibility Control● Unobtrusive JavaScript● Debug with firebug and Google chrome

jQueryjQuery

● $(“#div”)● .val● .prop● $.get, $.post● $.extend● .find

jQueryUIjQueryUI

● Dialog● Tabs● Button● Combobox● Calendar, datetime

jqGridjqGrid

● Create grid

● Local data, Paging

● Grouping header

● Search toolbar

● Formatter

– Number, Date, Rows color, Custom format● Grid functions

● Custom insert, update, delete,

● Custom button

● Multiple rows selection

CssCss

● Box model● Id, class● Selector● Select option group

Interesting topic

● Knockout Js● SignalR● WebSockets● Asynchronous controller● Less● Bootstrap● WebAPI

GIS (Geographic information system)GIS (Geographic information system)

● Latitude, Longitude ● WGS-84, SRID 4326● Geometry

– Point, LineString, Polygon

● Geometry function– Centroid, Intersect, WithIn, Area, Geography, Convex Hull

Google Maps APIGoogle Maps API

● Javascript● Map● Control → Pan, Rotate, Scale, Zoom

● Overlays → Marker, InfoWindow, Polyline, Polygon, Rectangle, Circle

● Services → GeoCoder, Direction, DistanceMatrix

https://developers.google.com/maps/documentation/javascript/reference?hl=th

SubversionSubversion

● Trunk● Branches● Tags● http://tortoisesvn.net/docs/release/TortoiseSVN_en/index.html

Coding problem● Code smell

– Duplicate code

– Long method

– Large class(God object)

– Too many parameters

– Feature envy

– Lazy class / Freeloader

– Contrived complexity

– Excessively long identifiers (Naming convention)

– Excessively short identifiers

– Excessive use of literals

– Complex conditionals

Duplicate code● How duplicates are created

– Copy and paste programming

– Functionally identical

● Problems– Code bulk affects comprehension

– Purpose masking

– Update anomalies

– File size

● Code reuse– Software libraries

– Design patterns

– Frameworks

Naming convention

● Class name → noun eg. Employee, Product, OrderDetail

● Interface name → I*able → IStatus, IEnumberable

● Constant → TAX_RATE, PI

● Property → Name, Price, Note

● Method → verb eg. DoWork(), Calculate(), Insert()

● Class variables – private string _name, private bool _switchFlag

● Local variables– bool switchFlag

Opensource License

● GNU General Public License (GPL)● GNU Lesser General Public License (LGPL)● MIT License● BSD License● Apache License● Public Domain

Profiling

Asynchronous ProgrammingAsynchronous Programming

● Asynchronous Programming Patterns– Asynchronous Programming Model (APM)

– Event-based Asynchronous Pattern (EAP)

– Task-based Asynchronous Pattern (TAP)

APM

public class MyClass{ public int Read(byte [] buffer, int offset, int count);}

public class MyClass{ public IAsyncResult BeginRead( byte [] buffer, int offset, int count, AsyncCallback callback, object state);

public int EndRead(IAsyncResult asyncResult);}

EAP

public class MyClass{ public int Read(byte [] buffer, int offset, int count);}

public class MyClass{ public void ReadAsync(byte [] buffer, int offset, int count);

public event ReadCompletedEventHandler ReadCompleted;}

TAP

public class MyClass{ public int Read(byte [] buffer, int offset, int count);}

public class MyClass{ public Task<int> ReadAsync(byte [] buffer, int offset, int count);}

Task Parallel Library

● Data Parallelism– Parallel.For, Parallel.ForEach

● Task Parallelism– Parallel.Invoke, Task.Run, TaskFactory.StartNew,

Task.ContinueWith

– Task Cancellation

– Exception Handling● PLINQ

Potential Pitfalls in Data and Task Parallelism

● Do Not Assume That Parallel Is Always Faster● Avoid Writing to Shared Memory Locations● Avoid Over-Parallelization● Avoid Calls to Non-Thread-Safe Methods● Limit Calls to Thread-Safe Methods● Be Aware of Thread Affinity Issues

Monitoring tools

● Event viewer● Performance counter● DB log file

Principle of software development

● D.R.Y. - Don't Repeat Yourself● Separation of concerns (SoC)● SOLID● KISS● GRASP● You aren't gonna need it (YAGNI)