9. 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;
...
}
10. 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
{
.....
}
}
11. 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>
{
}
12. Class members
● Fields – readonly field
● Constants
● Properties, Indexer
● Methods
● Constructor – static constructor
● Events
● Operator
● Destructors
● Nested Types
13. 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)
{
}
14. 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];
}
}
15. StructsStructs
● useful for small data structures
● No null! use with Nullable types
public struct RGB
{
public int red;
public int Green;
public int blue;
}
16. InterfaceInterface
● An interface contains only the signatures of methods,
delegates or events.
public interface IStatus
{
char Status { get; set; }
bool Equal(IStatus other);
}
17. Casting and Type Conversions
● Implicit Conversions
● Explicit Conversions
● Is, as, typeof
18. 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();
19. 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};
20. Delegates & EventsDelegates & Events
● Delegate
public delegate int Calculate (int value1, int value2);
public delegate void ChangedEventHandler();
● Event
public event ChangedEventHandler Changed;
public event EventHandler<EventArgs> Changed;
● Subscribe
publisher.Changed += HandleChangedEvent;
● Unsubscribing
publisher.Changed -= HandleChangedEvent;
void HandleCustomEvent(object sender, CustomEventArgs a)
{
// Do something useful here.
}
21. 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)]
28. 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)
29. ● 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.
32. 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}
33. 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}
34. 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}
35. Boyce–Codd normal form (or BCNFBoyce–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}
38. 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
39. 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
45. 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
46. 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?
48. 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_sales
FROM orders
WHERE region IN (SELECT region FROM top_regions)
GROUP BY region, product;
50. Anonymous Methods
// Defines a delegate that takes an int and returns an int
public delegate int ChangeInt(int x);
// Define a method to which the delegate can point
static 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));
51. 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 int
public delegate int MultiplyInts(int arg, int arg2);
MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));
52. 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);
53. Lambda Expressions that Return
Void
// Defines a delegate that takes a string and returns void
public 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 void
public delegate void OutputHelloToConsole();
static void Main(string[] args)
{
OutputHelloToConsole o = () =>
{
Console.WriteLine("Hello, World");
};
o();
}
54. 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);
55. 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);
}
}
59. 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
76. 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
78. 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
79. Opensource License
● GNU General Public License (GPL)
● GNU Lesser General Public License (LGPL)
● MIT License
● BSD License
● Apache License
● Public Domain
82. 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);
}
83. 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;
}
84. 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);
}
86. 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
88. 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)