.NET C#
.NET Building Blocks
Core Programming
OOPS Concept (value type & Reference Type)
- The role of system.valuetype is to ensure derived type allocated on stack instead of garbage collected heap
- data allocated on stack can be stored & destroyed quickly.Its lifetime defined by its scope
- Heap allocated data monitored by .net garbage collector and its lifetime determined by lot of factors
- base class of system.valuetype is system.object
Methods & Parameters
LINQ
- Linq centric features are
1.1. implictly typed local variables
1.2. object/collection initialization syntax
1.3. lambda expression
1.4. Extension methods
1.5. anonymous types
Dynamic keyword
1.Dynamic keyword can be assigned to any value
dynamic t="hello"
t=false;
t=new list<int>();
2.It can take the identity of any type on the fly
3.
Process,Domain,context,clr
- its an os level concept used to describe set of resources and necessary memory allocation used by application
- every executable function will have primary thread and primary thread can spawn multiple secondary threads
- .net executable are hosted by logical partition within a process called app domain
- each process may contain multiple app domains
- app domain are far less expensive in terms of processing power and memory than full blown process
- app domain improves scalability of server applications
- app domain provides deeper level isolation and failing of one app domain will not impact other app domain
- one app domain cant use other app domain data unless its using distributed programming protocol such as wcf
- adding assemly to custom domain
appdomain ad=appdomain.createdomain("seconddoamin");
ad.load("carlibrary") | car library is the assembly - single appdomain can contain multiple contextual bounderies
- contextual boundaries can be synchronize or a synchronize
- CIL is the only .net language that allows to use every aspect of CTS
MVC & Web API
Base class libraries
CLR
1.Locate,Load,Manage .NET Objects
2.Takes care of memory managemnet,App hosting,Thread management
CTS
1.All possible data types supported by CLR
CLS
1.Supports CLS feature compliant data types
Base class libraries builds upon CLR
Database Access
Desktop GUI
Security
Remoting API
Threading
File I/O
Web APIS
JIT
1.NET Framework run time uses JIT complier for CPU targeting machine
CTS Class Type
1.Class composed of members such as constructor,properties,methods,events
CTS Interface Type
1.Its a named collection of abstract member definition
CTS Structure Types
1.Best suited for modeling geometrical & mathematical data
CTS Enumeration Types
- Programming construct allows to group name value pairs
CTS Delegate Type
1.Deligates type safe
2.class derives from multicast delegate
1.MSCoree.dll is the main dll loaded in memory
2.It interact with mscore.lib whcih contains large core data
NameSpace
1.Grouping of semantically related types contained in assembly
1System.Collections:Number of stock container Type
2.System.IO:Worked with File I/O operation
3.System.Reflections:Support Runtime type discovery and dynamic creation type
4.Syste.Runtime.Introspective:Helps to interact with unmanaged code
5.System.windows: For windows presentation foundation
6.System.Web: For ASP.NET website
7.system.web.http: Build restfull service
8.system.servicemodel: For WCF service
9.System.workflow.runtime: For workflow related application 10.System.Threading: To build mult threding application
11.System.security: for building security(permision etc)
12.system.xml: To interact with XMLdata
Visual studio IDE
Express Edition
- It provides c#,asp.net& WCF
Community edition
- Provides desktop and web apps
2.supports F#,python,javascript
3.Project targets for windows phone
4.Project for android device,IOS Family
5.Allows class diagram & designer
Visual studio professional
Community edition + new features
- TFS to manage agile & kanban boards
- Sharepoint integration & developer chat room
- manage sprint planning
Xamarian
1.This IDE runs in windows,MAC OS and Linux 2.Its using Mono runtime and mono toolset
3.Mono installation required
4.Mono doesnt support WPF
Fundamental Properties
Piller of OOPS
- Encapsulation
- Inheritance
- Polymorphisim
System Properties 1.System.environment
Formatting Numerical Data
Ex:{0:C}
1.c-Used to format currency
2.D-Format Decimal
3.E-Exponential Notation
4.F-Fixed Point Formatting
5.G-General
6.N-Numerical Formatting
7.X-Hexadecimal formatting
Data Types derived from system.object
- It has methos such as tostring(),equals(),GetHashcode()
- Numerical datatypes derived from system.valuetype
- Numerical data types allocated on stack
System,types/.string/.array/.exceptions are on garbage collected heap
BigInteger comes from system.Numerics dll
System.String brings number of methods
- compare()-compares two strings
- padleft()-pad string with characters
- ToUpper()-returns string in uppercase format
string literals
1.\'-insert single quote into string literal
2.\" -insert double quote into string literal
3.\-defining file network
4.\n-for new line
5.\r-insert carriage return
6.\t-insert horizontal tab into string literal
system.string is immutable
1.For any string formatting change it returns a copy of it
string.format can be replaced with $
1.Ex:$"Hello {0} sam"
Iteration constructs
1.For loop
2.Foreach Loop
3.While Loop
4.Do/While Loop
5.Switch
6.If/Else
Do/While & While Loop
- do/while loop:-You need to perform this action when you need to do it undetermined number of times
- while loop:-While looping is useful when you need to execute a block till a terminate condition reached
- do/while have the difference to while loop is do while loo has corresponding block of code to be executed at least once where as while loop may not execute if terminating condition is false
Ref & Out Parameter in method
1.multiple out parameter can be returned from single method
2.Ref parameter required to be initialized
3.output parameter must be assigned by method being called and are passed by reference
void add(int x,int y,out int ans)
{ans=x+y}
Param keyword in method parameter
1.It allows programmer to pass into method an variable number of identical typed parameters
ex: methodane(param double[] value)
Collections
Arrays
Array of object data type
object[] obj=new object[4]
Enum
- Enum is a custom data type of name value pairs
- Enumerator is a class or structure that implements I Enumerable
- Ienumerable can work within for-each loop
4.Default storage values of enum is system.int32 - it can be changed to other system types(byte,short,long)
Establish enumaration as byte to save storage in memory
Random Concepts
Transnational database
- group of operations are atomic and any sub-operation failure will end up with a rollback of the whole which makes the set of operations reliable
- property of this kind of structure of operations are called as transnational
- transaction is one or more add, update, delete, and modify changes to the database that must all be completed or none of the steps should be executed
- Transactional databases are useful when data integrity is important
- User can easily modify the things without touching isolated sensitive information
- Improved ability to restore history with data being stored in constrained environment
- Due to constrained environment there is minimal risk of data loss
- very user friendly when it comes to writing SQL queries and joins and very fast (compared to Mongo) when it comes to grouping on a large tables
- Less ability to change information for many end users
10.Slower inserts because of relational structure
Non Transnational Database
- Non Transactional Database means that the data is not directly accessed by the OLTP (Online Transaction Processing) systems
- it is stored on a central repository were all the systems feed from and post updates once every X hours (on a pre-determined interval)
- A non-transactional database would probably have better performance because it doesn't have to worry about rolling back changes
- For Non Transactional table, you need to roll back the changes with manual code. No Impact of rollback and commit. These tables are useful for performing the statements with high performance
- NoSQL databases are document-oriented
- Storing data in bulk, requires extra processing effort and more storage than highly organized SQL data
7.It is not preferred when more detailed information is needed - Mongo DB as compared to SQL, is not very user friendly when it comes to writing more complex queries especially for grouping since standard group option is limited and for returning more than 20,000 records. You need to use map-reduce option
- When it comes to grouping data, Mongo DB will be much slower than SQL, when this operation need to be done on large group of records.
Switch
1.this can help to evaluate string data with numerical value
- switch can be used upon enumeration data type
Named Parameters
displayfancymessage(consolcolor textcolor,consolecolor backgroundcolor,string message)
Array
- Its a set of contiguous data points of same type
- Two ways to declair
2.1. string[] stringaray=new string[]{"one","two",three"}
2.1. bool[] bool array={false,false,true} - Using var keyword helps not to define the same type and all should be in one data type
3.1. var a=new[] {1,2,3} - for system.object datatype the sub items can be anything
4.1. object[] myobj=new object[4]
Members of array class
- Clear()-required to empty values
- CopyTp()-copy elements from source array to destination array
- length-returns number of items within array
- Rank-returns number of dimensions of current array
- reverse()-reverse content of one dimensional array
- sort()-sorts one dimensional array of intrinsic type
Value Type
- when copy from value type to another,member by member copy of field data is achieved
In case of point x & y values are copied into new structure
ex:
point p1=new point(10,10);
point p2=p1;
p1.x=100
output: P2= x=10,y=10
P1 x=100,y=10
P1 Get manipulated with the x field
Allocated on stack
- value type variables are local copies
- basetype? implicitly extends system.valuetype
- valuetype always sealed and can not inherited
- variables passed by value
- it can not override system.object.finalize()
- default constructor is always reserved
- It dies when fall out of scope
Reference Type
lets example create a class of pointref
public pointref(int xpos,int ypos)
{x=xpos;y=ypos;}
pointref p1=new pointref(10,10)
pointref p2=p1;
p1.x=100
output:
before change (P1 & P2): x=10,y=10
after change (P1 & P2) x=100,y=10
- allocated on managed heap
- reference type variables pointed to memory occupied on allocated instance
- can be derived from system.valuetype
- yes it can be base to othertypes
- yes it override system.object.finalize();
- yes constructor can be created
- It dies when garbage collected
Passing reference type by Value
1.value types can be passed as parameters to methods
2.passing it as reference type is different from passing it as value
ex:
class person
{
public string personName;
public string personAge;
public person(string name,int age) #constrictor for class
{
personName=name;
personAge=age;
}
static void SendPersonByValue(Person P) #After Value assignment
{
p.personAge=99;
p=new person("Nikki,99);
}
Output:
Before assignment: Fred,12
After Assignment: Fred ,99
Passing reference Type by Reference
1.changing above method as below
static void sendAPersonByReference(ref Person P)
{
p.personAge=555;
p=new person ("Nikki",999);
}
Output
Before assignment Fred,23
After Assignment Nikki,999
Use of variable type in array
2.Size is not declared in var type
Exitcode
2.Is4bitoperatingsystem
3.machinename
4.newline
5.systemdirectory
6.userName
7.version
Null Operator
1.It can be used with ?? operator
2.To assign value incase its null returned from db
ex
int i=dr.getintfromdatabase() ?? 100;
3.it provides more compact version of if/else condition
Encapsulation
- Always better to keep the member of the class as private
- Member data should be exposed through the method to outside
Constructors
- It allows state of the object to be established at time of creation
- its a special method of class called indirectly when created using new key word
- constructors never have return value and always named identical to class
- every class has default constructor and that never takes any argument
ex:
class car
{
public string petname;
public int currspeed;
public car()
{
petname="chuck";
currspeed=10;
} } - above example forces all car objects to start with name chuck and speed of 10 mph
Chaining a constructors
1.chaining constructors using this keyword
class motorcycle
{
public int driverintensity;
public string driverName;public motorcycle(){}
public motorcycle(int intensity): this( intensity,"") {}
public motorcycle(string name): this (0,name){}public motorcycle(int intensity,string name)
{
if(intensity>10)
{intensity=10; }
driverintensity=intensity;
drivername=name;
}
Optional arguments in constructor
class motorcycle
{
public motorcycle(int intensity=0,string name="")
{ if(itensity>10)
{intensity=10;}
driverintensity=intensity;
drivername=name;
}
}
1.You can pass zero,one or two arguments to the object of class
Static Keyword
- usually static keyword found in utility classes
- static data is shared by all objects of class
- the value of static data is not reset
- clr will allocate static data into memory exactly one time
- CLR calls static constructors before 1st use
ex: class savingaccount
{
static savingaccount()
{
console.writeline("");
currentinterestrate=0.04;
}
} - static constructor executes exactly one time regardless of how many objects of the type are created
Access Modifier
- Public: it can be accessed from object and as well from derived class
- Private: private items accessed by class that defines them
- protected: protected items used by class and any child class
- Internal: internal items accessed within current assembly other assemblies cannot use it
- protected internal: item is defined within assembly and within defined class and by derived class
To get read only properties
1.There will not be any set properties
public string socialsecuritynumber
{
get{return empssn; }
}
Automatic properties(use VS keyword)
1.Provides automatic properties for all data types
ex: public string petName {get; set}
Partial Class
1.Its used to divide number of codes in the class into two
2.partial class will contain properties and constructors and starts with partial keyword
Inheritance & polymorphisim
1.Inheritance always preserves encapsulation
2.inherited class can not access parent class private members
3.one class can not derive from two or more than two base classes
Sealed Class
- Having keyword as sealed prevents inheritance
Optimizing code during class derive
- never use custom constructor in the derived class
- custom constructor execution have to pass base class,property,default constructor executions
- To optimize code have the base class must have following constructor
ex:
public employee(string name,int age,float pay,string ssn):this (name,age,id,pay)
{empssn=ssn;
}
now to retrofit custom constructor
public manager(string fullname,int age,float pay,string ssn,int numberofopts): base (fullname,age,currpay,ssn)
{
stock options=numberofopts;
}
4.In above code derived class make explicit call to parent constructor that saves unnecessary time during child class creation
Containment/Delegation
- Containing class into another class
ex
class benefitpackage
{
public double computepay()\
{
return 125.0;
}
} - Using it inside partial class
partial class employee
{
protected Benifitpackage empbenefits=new BenefitPackage();
public double getBenefitcost()
{ return empbenefits.computepay(); }
public BenefitPackage Benefits
{
get {return empbenefits;}
set{empbenefits=value;}
}
Nested types
- its possible to define type(enum,class,interface,struct or delegate) inside a class
- nested type considered as member of nesting class
- in run time it can be manipulated by any other member (field,properties,methods,events)
ex: partial class Employee
{
public class BenefitPackage
{
public enum BenefotPackageLevel
{
standard,gold,premium;
}
}
}
Main()-Execution
Employee.BenefitPackage.benefotPackageLevel mybenefotlevel=Employee.BenefitPackage.BenefotPackageLevel.platinum;
Polymorphisim
Virtual & Override keyword
- If a base class wants a method to be overridden in subclass
- method in base class has to be named with virtual keyword
- two derived subclass can have two different methods having override keyword
- having sealed keyword in method stops overwriting
- To prevent creating object of base class abstract keyword is used
Abstract
1.Abstract class will have number of abstract members
2.abstract member doesnt supply with default implementations
3.abstract member must be accounted for each derived class
4.having abstract in base method will force subclass to derive that method
5.
New keyword
1.Having new keyword in derived methods will allow it rewrite same method of base class
ex: class circle
{
public void draw()
{}
}
class thredcircle:circle
{
public new void draw()
{
}
}
Base class/derived class casting
- all classes descendant of object. so reference can be created with following way
object frank=new manager("frank",9,3000,4000,"111",5) - For above example of employee base class there are managers,salesperson as derived classes
- casting can happen using base class
ex Employee emp=new Manager("","")->Manager is an derived class of Employee - saving the derived class object within base class reference called as implicit class
- creating class object referencing superset of base class reference will be a problem
ex:object frank=new manager()->manager is derived from employee. system.object is higher up the chain - Like above scenario down cast is needed for compiler to work
ex: givepromotion((Manager)) frank)
Methods of object class
- Equals()->items being compared refered to same item in memory
- finalize()->used to free any allocated resources
- Tostring()-this method returns string of the object
- gettype()-returns the type of object that describes the object
- gethashcode()-provides general idea where object is located
Exceptions
- Derived from system.exceptions class
- it has 5 key words(try,catch,finally,throw,when)
- system.exception derives from system.object
- Throw will show all the details of error in window
- finally block will be used to clean up the bugs
Properties
- Data->retrieves collection of key value pair
1.1. ex.data.add("","")-> can be used to provide custom data of error - helplink-> provide url to describe error full in details
2.1. ex.helplink->usually comes as blank value. it can provided with url to custom messages - innerexception->provides details of previous exception that occurs this exception
- sorce-> provide the assembly source
- targetsite-> provides method name that threw exception
5.1. e.targetsite.membertype-> provides the membertpe of the object(property /method) - e.stacktrace-> provides the line of code where it fails in a sequence of calls
7.
System exceptions
1.these are thrown by .net platform
2.system exception derives from system.systemexception and that derives from system.exception
3.
Application exception
- it is used to identify the source of the error
- customeexception can be created using separate class and having its exception properties
- custom exception class can be derived from application execption
Interface
1.Its a named set of abstract members
2.a class can multiple interface that means support multiple behavior of interface
3.interface can not have datafields
4.interface cant have implementation of members
- you can not create an object of interface like an class
6.interface is just a named collection of abstract memebers
Array of interface
1.Ex:IPointy[] ipointyobjarray={new hexagon(),new Knife(),new Traingle()}
foreach(ipointy i in ipointobjarray)
{ console.writeline(i.points);
}}
2.Here all the classes implementing same interfaces
Connections
1.All connections derived from IDBConnections
2.
Inheriting multiple interface
- for multiple interface having same method name scenario
- interfacename.method name is used to distinguish method name
- Interface can inherit another interface and the class inheriting sub interface has to implement all the members in the chain if interface
- Interface can inherit multiple interface as well.class has to implement all the interface members in the chain
IEnumerator
- System.collections comes with IENUMERATOR
- looping through array of class foreach loop is not needed and using foreach loop instead of ienumerator will throw compilation error
ex-public IENumerator GetEnumerator()
{return cararray.getenumerator();
}
Generics
- generics provide better performance by not doing boxing and unboxing of value types
- generics are type safe and can contain the type you specify
- generics greatly reduces the need for custom collection types
- stack<T>-> represents last in first out manner
4.1. stack<T> has two members push() and pop() - Queue<T> is used as container for first in and first out manner
5.1. queue<T> has dequeue() and enqueue() member - sortedset<T> is used as it ensures the item sets are sorted as it is inserted or removed
Delegates,Events,Lambda expression
- In .NET Framework callbacks are accomplished in type safe and object oriented manner using delegates
- every delegate automatically endowed with the call to method as synchronously or asynchronously
- using delegate keyword it indirectly creates a class taht is multicast delegate
- member of multicast delegate
4.1. method->property returns object that details about static method
4.2. target->target returns the object maintained by the delegate
4.3. combine()-> to combine methods to the list
4.4. getinvokationlist()-> provides array of delegate objects
5.Action<> delegate returns void value - func<> delegate returns non void value
ex:func<int,int,string>funcdelegate=new func<int,int,string>(add/function name)
Events
Lambda expression
- List<Int> evennumbers=list.findall(i=>(i%2)==0);
1.1..i is the parameter list,i%2 is the statement set to process - Argumentstoproces => statements toprocessthem
- i can be explicitely defined by following example
3.1. list<int> evennumbers=list.findall((int i)=>(i%2)==0);
Implicit typing of local variable
- var keyword allows you to define local variable without explicitly defining the data type
- the compiler determines the data type based upon initial assignment
- varius terms available
3.1. linq to objects-> this term refers to applying linq quries to arrays and collections
3.2. Linq to xml->using linq to manipulate and query xml document
3.3. linq to dataset->applying linq queries to ado.net dataset objects
3.4. linq to entities->LINQ allows you to make use of linq quries within ado.net entity framework
3.5. Parallel Linq->this allows parallel processing of data returned from linq query
asemblies for linq
- system.core.dll->this is used for linq to objects
- system.data.datasetextensions.dll->used for linq to datasets
- system.xml.linq->used for linq to sql
Query structure using LINQ
- int[] numbers={10,11,12,13};
IEnumerable<int> subset=from i in numbers where i<10 select i;
Note: Ienumerable<T> T represents the return type of query - Implicit tyep such as var can be used
var subset=from i in numbers where i<10 select i; - Applying LINQ to non-generic collections
arraylkst mystuf=new araylist();
mystuff.addrange(new object[]{10,400,8,false,new car(),""});
var myints=mystuff.offtype<int>()
note: this will collect only int items from the array - projecting new datatypes from the query result | ex: collects name and description data
var namedesc=from p in products select new {p.name,p.description}; - finding difference in two list|finding delta between two list
List < string > myCars = new List < String > {" Yugo", "Aztec", "BMW"};
List < string > yourCars = new List < String >{" BMW", "Saab", "Aztec" };
var carDiff =( from c in myCars select c) .Except( from c2 in yourCars select c2); - union() -> returns all common members from both the lists
List < string > myCars = new List < String > { "Yugo", "Aztec", "BMW" };
List < string > yourCars = new List < String > { "BMW", "Saab", "Aztec" }; // Get the union of these containers.
var carUnion = (from c in myCars select c) .Union( from c2 in yourCars select c2); - concat()-> returns concatenation of two result set
- following aggregate functionsc an be used on linq result set
max(),min(),average(),sum()
LINQ Query operators
- From,In->used to extract subset of data
- where->used to define restriction
- select->select sequence from conatiner
- join,in,equals,into->perform joins based on key
- order by,ascending,descending->used to set orders
- group,by->used to yields subset with data grouped by
Thread, asynchonous call
- One appdomain can have multiple thread and thread can shift different app domain bounderies
- single thread can not work in multiole app domain
- when C# complier process delegate key word it invokes begineinvoke() and eninvoke() method
public sealed class BinaryOp : System.MulticastDelegate
{
public IAsyncResult BeginInvoke( int x, int y, AsyncCallback cb, object state);
// Used to fetch the return value // of the invoked method.
public int EndInvoke( IAsyncResult result);
}
4.return type of endinvoke() will be same as delegate return type - Iasync result interface will be like below
public interface IAsyncResult {
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; } } - Iasync result comes with iscompleted property that helps calling thread to continue the job
while(! iftAR.IsCompleted) { Console.WriteLine(" Doing more work in Main()!"); Thread.Sleep( 1000); } - Iasynch interface provides asyncwaithandler property
- the benefit of waithandler.waitone() is that wait time can be specified,asynchronous call
- asynchronouscallback object when passed as delegate parameter ,the delegate will call specified method automaticaly when the asynchronous call is completed
IAsyncResult iftAR = b.BeginInvoke( 10, 10,new AsyncCallback( AddComplete), null); - starting object call with a new thread
Thread backgroundThread = new Thread( new ThreadStart( p.PrintNumbers));
Thread synchronization
- Lock keyword can be used to manage thread syncronization
private object threadLock = new object(); public void PrintNumbers() {
// Use the lock token.
lock (threadLock) { ... } - CLR threadpool can be used instead of manually creating thread.
- thread pool helps to manage threads by minimizing number of threads that must be created
- using thread pool helps to focus on business problem instead of threading infrastructure
- to queue a method ina worker thread threadpool.queueuserworkitem can be used
public static bool QueueUserWorkItem( WaitCallback callBack);
public static bool QueueUserWorkItem( WaitCallback callBack, object state); - waitcallback delegate can point to any method
- TPL(Task parallel library) will automatically distribute application workload across available cpu dynamically using CLR thread pool
- TPL handles partitioning of work,thread scheduling,state management and other low level details
- system.threading.tasks comes with paralel class whcih will help to iterate over collection of data in parallel fashion
- this parallel class support two static methods parallel.for() & parallel.foreach()
- the benefit of parallel class is that it will pluck threads from thread pool
Parallel.ForEach( files, currentFile = > { string filename = Path.GetFileName( currentFile);
using (Bitmap bitmap = new Bitmap( currentFile)) {
bitmap.RotateFlip( RotateFlipType.Rotate180FlipNone);
bitmap.Save( Path.Combine( newDir, filename));
Thread.CurrentThread.ManagedThreadId); } } - GUI control through windows forms always have thread affinity.if secondary thread directly attempts to access a control that they didnt create,itsa run time error
- Through anonymous delegate secondary thread can access the GUI control.
this.Invoke(( Action) delegate { this.Text = string.Format(" Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId); } ); - In Above example TPL distributes workload among multiple threads from thread pool using as many CPUs
- Alternative to asynchronous delegate is by using task class
Task.Factory.StartNew(() = > { ProcessFiles(); }); - The factory property of task returns taskfactory object when startnew() method called
Parallel LINQ Queries
- Using AsParallel in Plinq query TPL will pass workload into available CPU
int[] modThreeIsZero = (from num in source.AsParallel() where num % 3 = = 0 orderby num descending select num). ToArray(); - using async and await keyword thread can be run in asynchronous way
private async
void btnCallMethod_Click( object sender, EventArgs e) { this.Text = await DoWork(); }
// See below for code walkthrough... private Task < string > DoWork() { return Task.Run(() = > {Thread.Sleep( 10000); return "Done with work!"; }); } - using async keyword with task<T>
private async Task < string > DoWorkAsync() { return await Task.Run(() = > - during await expression calling thread is suspended until awaited task is complete
File I/O
- Binary Reader/writer: allows to retrieve and store primitive datatype(int,string,bollean ) as binary value
- bufferedstream:provides temporary storage of bytes
- Directory:these calsses used to manipulate directiry structure
- driveinfo,fileinfo: provides details of directory and files
- filestream: this class gives random file access
- filesystemwatcher:allows to monitor modification of external files
- memorystream: provides random access to streamed data stored in memory rather than file
- path: provides file and directiry path
- stream writer/reader:classes used to store /retrieve textual information to file
- string writer/reader:classes work with textual info but rather work with string buffer instead of physical file
FileInfo
- Fileinfo class has create method which return filestream object
- fileinfo.open() returns filestream object as well
- fileinfo.opentext() returns streamreader type rather than filestream type
- fileinfo has createtext() and appendtext() methods returns streamwriter object
- readallbytes() returns binary data as array of bytes adn closes the file
- readalllines() returns character data as array of strings
- readalltext() returns character data as system.string
stream class
- it has following properties
1.1. canread/canwrite:determnes whether current stream supports reading/ writing
1.2. close():closes current stream and releases any resources associated with stream
1.3. flush():updates the datasource with current state of buffer and then flush it
1.4. lenghth:provides lenghth of stream
1.5. position:determines position of stream
1.6. read()/readbyte():reads sequence of bytes from current stream
1.7. seek() sets position in current stream
1.8. setlenghth():sets length of current stream
1.9. write()/writebyte():write sequence of bytes to current stream
using( FileStream fStream = File.Open(" C:\ myMessage.dat", FileMode.Create)) {
// Encode a string as an array of bytes.
string msg = "Hello!"; byte[] msgAsByteArray = Encoding.Default.GetBytes( msg); // Write byte[] to file.
fStream.Write( msgAsByteArray, 0, msgAsByteArray.Length); // Reset internal position of stream. fStream.Position = 0; - streamwriter and stream reader is needed when its needed to read/write character based data
2.1. streamreader deerives from textreader as like stringreader
2.2. streamwriter derives from textwriter
Binary reader/Writer
- derive from system.object and allows to read and write Deseret data types into stream in a binary format
- To notify any file change filesystemwatcher is used
FileSystemWatcher watcher = new FileSystemWatcher();
try { watcher.Path = " C:\ MyFolder"; }
catch( ArgumentException ex) { Console.WriteLine( ex.Message); return; } // Set up the things to be on the lookout for.
watcher.NotifyFilter = NotifyFilters.LastAccess| NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*. txt"; // Add event handlers.
watcher.Changed + = new FileSystemEventHandler( OnChanged); watcher.Created + = new FileSystemEventHandler( OnChanged); watcher.Deleted + = new FileSystemEventHandler( OnChanged); watcher.Renamed + = new RenamedEventHandler( OnRenamed);
Serialization
- Its the process of persisting(possibly transfering) object into stream
- The persisted data sequence contains all the data needed to reconstruct
- Having [serializable] keyword helps the class object to persist
[Serializable]
public class UserPrefs
{ public string WindowColor; public int FontSize;}
static void Main( string[] args) { UserPrefs userData = new UserPrefs();
userData.WindowColor = "Yellow"; userData.FontSize = 50;
BinaryFormatter binFormat = new BinaryFormatter();
// Store object in a local file. using( Stream fStream = new FileStream(" user.dat", FileMode.Create, FileAccess.Write, FileShare.None)) { binFormat.Serialize( fStream, userData); } - when derived class persisted all data up the chain get serialized
- it got serializaed into soap/xml format as the persisted object can be traveled across operating system,language
- filestream is used to persist into an file.memorystream can be used accordingly
- when child class derives from serialized parrent class,child classes must be serialized
- xml serializer only serialize public data fields and private data fields exposed by public properties
- binaryformatter and soapformatter can serialize public and private properties
- Iformatter interface defines core serialize() and deserialize() methods which helps to move object graph into or out of stream
- Iremotingformater derives from iformatter interface and overall serialize,desrialize methods
- binary formatter persist not only field data ob object, also assembly nameand assembly qualified name into stream.
- As bianry formatter supports complete copy of object serilaization. its a ideal choice for transport between .net applications
- xml serilizer doesnt serilize full object type. its more suitable to use across the environment(os/application framework)
Bianry formatter
- serializes objects state to stream using binary format
soap formatter
- It persists objects state as soap message
XMLSerialize
- XMLAttribute: using xmlserializer to serialize the data as xmlattribute
- xmlelement: this property or field serialized as xml element
- xmlroot: this attribute controls how root element will be constructed
ADO.NET
- represented by core assembly syste,data.dll
ado.net can be used with connected /disconnected approach
Dataset(disconnected layer)
- dataset properties are
acceptchanges()-commit all changes made to data set
getchange()-returns copy of all changes since last loaded
haschanges()-gets value whether dataset has changes
readxml()-allows to define structure of dataset object and populate
writexml()-write contents of dataset to valid stream - datacolumn has propertes like allowdbnull,autoincrement,caption,columnmapping,columnname
- datatable reader works like data reader object and reads the data from datatable
- to make datatable linq query compatible .use ASenumerable() extension method. this returns enumerablerowcollection object
enumerablerowcollection enumdata=dataset.asenumerable(); - maintenance of type safety required by using field<T>()
ex: ID=car.field<int>("CARID");
connected layer
- datareader: provides forward only readonly access data using server side cursor
- dataadapter:transfer dataset between calleer and datastore.it contains connections and command objects
- odbc: it is widespread model that provides access to data stores
- open connection set for project
static IDbConnection GetConnection( DataProvider dataProvider) {
IDbConnection connection = null; switch (dataProvider) { case DataProvider.SqlServer: connection = new SqlConnection(); break; case DataProvider.OleDb: connection = new OleDbConnection(); break; case DataProvider.Odbc: connection = new OdbcConnection(); break; } return connection;
Entity Framework
- DBContext:it represents unit of work and repository pattern that can be used to qury from database ad changes can be updated to database as group
- dbcontext provides number of core services including the ability to save the changes,call sp,delete objects
- dbcontext implements ibjectcontextadapter.so all its functionality available in objectconext class
- To add tables in context dbset<T> is used
- each dbset<T> provies number of core services
5.1. addrange-allows to insert new object
5.2. attach-associate object with dbcontext
5.3. create<T>-create new instances of specific entity type
5.4. findasync-finds data row by primary key and returns object representing taht row
5.5. removerange-marks object for deletion
5.6. sqlquery-creates raw sql query that will return entities - Using Linq to query with sql syntax
foreach (Car c in context.Cars.SqlQuery(" Select CarId, Make, Color, PetName as CarNickName from Inventory
where Make =@ p0", "BMW")) - each LINQ query hits the database. so to avoid hitting db, caching is used and data collected as Tolist<T>() or Toarray<T>()
ex: var alldata=context.cars.ToArray(); - lazy loading in EF prevents entire data to be loaded into memory
ex: foreach (Car c in context.Cars) { foreach (Order o in c.Orders) { WriteLine( o.OrderId); }
8.1. instead of loading all the car and orcer record,it will load only order specific to particular car - when its preferable to load all teh data into memory
foreach (Car c in context.Cars.Include( c = > c.Orders)) { foreach (Order o in c.Orders) { WriteLine( o.OrderId); } - lazy loading can be disabled with
context.Configuration.LazyLoadingEnabled = false;
Repository Pattern
- its to mediate between domain and data mapping layers
- Advantage of EF is all models and collections strongly typed
- add baserepo to the directory which will implement common functionality for repository classes
- retrieving records-getone/getoneasync and getall/getallasync is used to wrap the methods
public T GetOne( int? id) = > Table.Find( id);
public Task < T > GetOneAsync( int? id) = > Table.FindAsync( id);
public List < T > GetAll() = > Table.ToList();
public Task < List < T > > GetAllAsync() = > Table.ToListAsync(); - baserepo implements idisposible interface which ensures resources released in timely manner
- entitystate of the entity is to be modified into entitystate.modified and then call savechanges()
- entuty state has to be changed to entitystate.deleted after calling delete() method
- dropcreatedatabasealways()-this method always re creats database everytime programme is executed
- dropcreatedatabaseifmodelchanges<TContext> only recreates when there is any changes in the model
MVC
1.favicon.ico-> its needed for browser to display in address bar .otherwise it will be a performance issue
- global.asax-> entry point to application
- package.config->config information for nuget package to use
- project_readme.html->provides usefull infor about mvc
- startup.cs->start up calss for owin(asp.net identity)
- web.config-> project configuration file
global.asax
1.its where asp.net pipeline can be hooked
- it has the same events like asp.net web forms
2.1. applciation start
2.2..application_end
2.3. application_error
2.4. session_start
2.5. session_end
2.6. application_beginrequest
2.7. application_endrequest
App_Start
1.any code in app_start folder get compiled into site
- following files in app_start
2.1. bundleconfig.cs->create file bundles for java script and css files
2.2. filterconfig.cs->registers action filters at global scope
2.3. identityconfig.cs->support classes for asp.net identity
2.4. routeconfig.cs->where routing table is configured
2.5. startup.auth.cs->entry point for asp.net identity
bundling
- process of combining multiple files into one
- This will help in speeding up the site
- minification: its designed to speed up load time for web pages
3.1.minification is the process of replacing long names with short names - Bootstrap: its an open source HTML,CSS,Javascript framework for developing responsive mobile first websites
- bootstrap ships with glyphlcons halfling fornt sets that is used to enhance application UI
6.routing can be done to reroute some of urls
routes.maproute("contact","contact/{*pathinfo}",new{controller="Home",action="contact"})
6.1. pathonfo allws to pass any parameter into it - redirectiing to other users can be done using html link
html.actionlink("contact","contact",Home")
Model Binding
1.There is implicit and explicit binding
- model binding engine attempts to assign values.if it cant assiign model state.isvalid=false.
- if it successfully assigned modelstate.isvalid=true
- if model can't be bound it throws error like modelstate.addmodelerror(string.empty,<head>quot;unable to create record:{ex.message}");
- antiforgerytoken is used in forms to avoid hacking
- fields can be black/white listed during binding
public async Task<ActionResult>Create([Bind(Include="Make,clor")]Inventory inventory)
MVC Controller & Views
- MVC views can be built using razor view engine / web forms view engine
- Razor view is designed as improvement over web forms view
- Razor is template markup syntax that is interpreted to c#
- using razor in html/ css results in cleaner and easier to read mark up
- Razor uses @ instead of <%%>
- code blocks can intermix markup and code.lines that begin with markup tag are interpreted as HTML
- lines that are begin with code are interpreted as code
foreach (var item in Model) { int x = 0; < tr > </ tr > } - razor html helper renders mark .The helper can output details of inventory record
using AutoLotDAL.Models
helper ShowInventory( Inventory item)
{ item.Make < text >-</ text >@ item.Color < text >( </ text >@ item.PetName < text >) </ text > - Razor can have functions to encapsulate code
functions
{ public IList < Inventory > SortCars( IList < Inventory > cars)
{ var list = from s in cars orderby s.PetName select s;
return list.ToList(); } } - foreach loop can use the functions in the page
foreach (var item in SortCars( Model.ToList()))
{ <!-- rest removed for brevity --> }
Razor partial view
- useful to encapsulating UI that reduces repeating code
- partial view rendered from action method where as full view will use a layout page
ways to send data to view
- TempData:short lived object works between current and next request
- ViewData:It allows storing name value pairs
- ViewBag:its a dynamic wraper for view data dictionary
- For large amount of data model property is used
- glyphlcons are ste of icons that ships with bootstrap
Web API
- Json is one way to transport data between services
- its a key value text representation of objects and classes
- webapi is centered on controller and actions
- in addition to httpget and http post httpput and httpdelete are used
- creating view models using automaper
public InventoryController()
{ Mapper.Initialize(
cfg = > { cfg.CreateMap < Inventory, Inventory >() .ForMember( x = > x.Orders, opt = > opt.Ignore()); }); } - above code creates mapping for inventory type ignoring order property
- responsetype attribute is used to specify the entity type returned in httpresponsemessage
- nofound() returns not found result that translates to 404 message
- calling through httpclient to web api. webapi returns two properties
- issuccessstatuscode property returns as true
- the content property provides access to message body and if the result records returned,web api returns as httpok(200)
- the content property always holds the record in jason format
- httpclient have to use jsonconvert.deserializeobject<T>() method
- for updating add action system.net.http.formatting is needed as project reference
- for add postasjsonsync() is needed to add the data
- putasjsonasync() is needed for updating record using httpclient
- deleteassync() is needed to be used in client when you need to delete the record
- httprequestmesage take two parameter
**httpmethod & and the url
HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Delete, $" http:// localhost: 46024/ api/ Inventory/{ inventory.CarId }") { Content = new StringContent( JsonConvert.SerializeObject( inventory), Encoding.UTF8, "application/ json") };**