Wednesday, September 3, 2008

notes 2



>> Dependency Injection
ICustomerDAO dao = (ICustomerDAO) ObjectFactory.GetInstance(typeof(ICustomerDAO));
public class DAOFactory
{
public static T Create<T>()
{
IDatabase db = Registry.Fetch<IDatabase>();
T dao = Registry.Fetch<T>();
dao.Database = db;
return dao;
}
}
ICustomerDAO dao = DAOFactory.Create<ICustomerDAO>();
>> mutex
mutual exclusion object
>>DAL Using LINQ to SQL
1. add a record
var db = new DashboardData(connectionString);
var newPage = new Page();
...
db.Pages.Add(newPage);
db.SubmitChanges();

// Get and Update
var page = db.Pages.Single(p=>p.ID=PageId);
page.Title = ~
db.SubmitChanges();

// Read Scalar Data
var userGuid = (from u in db.Users
where u ...
select u.UserId).Single();
// Create object on the fly - also projection
var users = from u in db.Users
select {UserId= u..., UserName = ...};
// use skip and take
// Starts from 10th and get 20 recs
var users = (from u in db.Users
select {UserId=u.UserId, ...}).skip(10).take(20);
// use transaction
using(var ts = new TransactionScope())
{
List<Page> pages = db.Pages.where(p=>p.UserId == oldGuid).ToList();
foreach(Page page in pages)
page.uid= newId; // changes
//another changes
//Add/remove records
db.SubmitChanges();
ts.Complete();
}
// Generate data model with VS 2008 Designer
// drag and drop/ ORM design
each table maps to a class including methods of operation.
can turn on/off lazy loading and validation etc.
modify association
Database Helper/ Dashboard - Facade of DB layer?
class DatabaseHelper
{
public static DashboardData GetDashboardData()
{
var db = new DashboardData(ConfigManager.ConnectionStrings(connectionString].Connectionstring);
return db;
}
}

>> Spring.Net
ProxyFactory factory = new ProxyFactory(new ServiceCommand());
factory.AddAdvice(new(ConsoleLoggingAfterAdvice());
ICommand command =(ICommand) = (ICommand)factory.GetProxy();
command.Executes();

>> use var in javascript
function f1()
{
i=10;
fz();
alert(i); // i=100
}
function fz()
{
for(i=0; i++; i<=100)
{
}
}
because this confuses the compiler upon the scope of a variable
solution: user "var"
in f1
var i = 10; // tell the compiler this i is a local i (local to {})
in f2
for(var i=0 ...)
>> javascript typeof
typeof x = "string"|"function" |"undefined" ...
version 1.0, 1.2, 1.3 (IE5)

>>Dependency Injection - inversion of control
dependency injection framework
when accessing a service, instead of holding a reference to that service, a software component provide a property that can hold that type of reference, when the object is created, a service implementation reference is automatically injected into the property, configurable framework support
SOA - service oriented architecture
service - a set of business or functionalities
configur mechanism for deciding which implementation gets injected into an object
"let the outside caller provide the desired implementation"
ObserverFactory

//>> javascript interpreter optimization
switch block
use delegate
for(var i=0; i<count; i++)
$get('divContent').appendChild(element[i];
=>
var divContent = $get('divContent');
for(var i=0; i<count; i++)
divContent.appendChild(elementp[i]);
=>
var divContentAppendChild = $get('divContent').appendChild;
for(var i=0;i<count;i++)
divContentAppendChild(element[i]);
-- using delegate saves time for javascript interpreter to lookup the scope chain for the function or other element
$get('divContent').innerHtml = strContent;
//>> javascript arrary
var links = ["microsoft.com", "yahoo.com", "cbc.ca"];
var strArray = new Array();
strArray.push("<div>");
strArray.push("some content");
strArray.push("/div");

>> RBC IRIS project (July 4 - Oct 4)
keyword:
IRIS, Infinity, RIMMS, EOPS, Fedware

Infinity generates settlements from stock exchange and other business, that are the input of IRIS project.
IRIS process these settlements by the following actions:
Release
Verify
Exception
Netting
Remove
After a settlement is released by IRIS, RIMMS take it and accomplish the money transfer.
RIMMS has three systems: London, New York and Toronto.
EOPS is a visual interface for the commandline based RIMMS.
Fedware is a software for government transactions
Before IRIS is developed, settlement processing is handy work. IRIS is targeted to be a bridge between Infinity and RIMMS. it is an automation effort of the business process.

>> Queue Centric Design Idea
asynchronous
To implement a project of long business process, it is a good idea to cut the long pipeline in to several projects, with a queue in between. the output of previous project is pushed in the queue and be consumed by the successive project.
queue can be implemented with database tables
In IRIS for example, Infinity produce settlements and save to SettlementsToRelease table, and then settlements for Verifying, Netting are put in correspondent tables waiting for further processing. IRIS is structured with such queues. It makes tracing and maitaining state of settlement very easy.
>> The problem with middle-state

Just as computer circuit avoids generate a middle state between 0 and 1, an application also need to clarify the prestate and and poststate. A middlestate is error prone. It is a computer application's ingenious feature to certain states.
So any business action step which may involve multiple object methods should have clear prestate and postcondition of business object. It is different from precondition and postcondition of the method.
if the state is maintained in database, then we use database transaction to ensure it. how about the state is in memory or other infrastrucure?



.Net language
CLR based languages
CLR types mapping to development languages refered as "standard types"
Parameters passed-by-value means that changes made to them within a method won't be seen by the caller once the method return. pass-by-reference parameters do the opposite, changes will reflect back to the caller.
keyword ref, out
if a parameter is value type it will be boxed/unboxed, if it is ref type, it doesn't need to indicate with keyword "ref".

>> Survey the .Net Library
typical issues has programming API in terms of namespaces.
// namespace overview
System.Xml
System.IO;
System.Windows
System.Management
System.Media
System.Messaging
System.Transaction
-- support for app using transaction .Net2.0 prior version uses ADO.Net for handling database transaction.
System.Timer - for recursive events
System.Drawing
-- GDI+ - Graphics Device Interface
pens, brushes
.Drawing2D
.Imaging
.DrawingPrinting
.DrawingText
.DrawingDesign


>> Assembly Securities
assembly is a scope of types: "protected"
logical/physical development unit. it is alsoa security boundary
two types of securities:
1.Code Access Security
2.Role-Based Security

what CLR based code only allow to do based on permissions, the intersection of:
what the code is requested
what granted (SecurityPolicy)

Permissions an assembly can request:
UIPermission
FileIOPermission
...
finer-grained options:
e.g. FileIOPermission = {readonly, write, delete, override}

// developer specify permissions
-declarative security(attributes)
attributes then becomes metadata that CLR can access
-Imparative Security
dynamically within source code
"can not request new permission on the fly, but can demand any caller have specific permission."
assembly identified by identity and origin
the creator or admin can establish security policy for the machine on the assembly
the permission granted toe an assembly when it runs based on security policy.
each assembly has an evidence that CLR can use to determine who created it and where it comes from.
evidence:
identity of publisher, by digital signature
identity of assembly, by the strong name
website can specify URL which an assembly was downloaded
zone: local intranet or internet or others
the CLR determines what an assembly is allowed to do.
Role-based security (user based security)
what an assembly is allowed to do, based on the identity of the user on whose behalf the assembly is running.
[user(identity)] [is athenticated for] [Principle object]
a user can belong to one or more roles, an assembly can use roles to limit what its users are allowed to do.

(granularity)
permissions can be specified to an assembly, a class, a method, property and event.
with imperative way, code explicitly check
with declarative way, CLR will check automatically

overall, who is allowed to do what.


>>ACL - Access Control List
each and every file or folder has an associated ACL.
Basic permission
special permission
effective permission

>> DataRow.RowState
DataRow.AcceptChange();
DataTable.AcceptChange();
DataSet.AcceptChange();
made changes permanently and change RowState (DataTable, DataSet) to "unchanged".

>> DataSet and Xml Data
DataSet.ReadXml(source); //source={file|stream|XmlDataReader}
DataSet.WriteXml(target); // target= {stream|XmlWriter}
XmlWriter accepts options such as how columns are mapped to xml elements and other options
System.Xml namespace
XmlDocument <=> DataSet
XmlReader <=> DataReader
XSD Schema <=>Database Schema (tables)
DataSet.ReadXmlSchema();
explicitly instruct DataSet a schema or the Xml data has a refered schema.
DataSet.WriteXmlSchema() output schema
>> Synchronization of DataSet and XmlDataDocument inherited from XmlDocument, allows access data in both relational and hierarchical way it allows running XPATH query and XSLT transforms. it also allow user access data as a dataset.

DataSet.ReadXml() convert hierarchical data into relational data tables, similarly, WriteXml convert tables to hierarchical trees.
>> OR Mapping Overview
EJB has entity beans as a way to automate the process of reading object's state from DB and storing it back into DB. JDO provide a slightly different way. Hibernate.
.Net latest LINQ queries and perform against relational tables and XmlDocument.
>>Exists Method
List<T>.Exists(), asks a Predict<T> as it's input. Predict<T> actually is a delegate. Here is how to use it:
if(list.Exists(delegate(T item){
return(item==theValueToMatch);))
{
...
}
Here is how it works:
Exists method iterate all the elements in the list calling the delegate to compare with TheValueToMatch. whenever metched return true;
>> To Read a File From Assembly
suppose there is a text file or binary image file in an assembly, it will be wrapped into the dll or exe file when compiled. In application code how to access the file?
Stream stream = typeof(anthem.Manager).Assembly.GetManifestResourceStream("Anthem.Anthem.js");
StreamReader sr = new StreamReader(stream);
string result = sr.ReadToEnd();

>> Silverlight
Silverlight is very similar to Flash in terms of the use in a Web page, except that Silverlight is feeded with XAML, while Flash with SWF file.
// Silver Browser Object
a browser embeded binary used to parse XAML and render the onto the web page
<object> tag is used as usual to create a plug-in instance of an Silver browser object
Silverlight.js, a javascript library is imported to a page. <object> tag only create an instance, We still need to initialize the instance with specific values such as the XAML source file, the size of the area of the object on the page, the event handlers such as error handler.


>>Web Service and Xml
SOA, from solution perspective, is a predominate approach for distributed software application.
Services are hosted with web servers, such as IIS, Apache, etc. Because web services can be consumed through SOAP, a HTTP based internet protocol. Client app makes request through SOAP protocol and get response from Web service with SOAP as well.
SOAP, like Http post and Http Get, which uses key-value pair to pass parameters along with a request, while SOAP use more complex way - xml pass parameters. The limitation of Get and Post is that they can only pass string values. while SOAP can pass objects. The type of the object, that is the schema if also represented with xml and so that both client and server can use serialize and deserialize object and transfer over the wire.
figure
S1<-SOAP->S2
S1<-SOAP-Client>


// Connectivity
to specify the location of a service
protocol: httpd://
address: ip address
port:80 or others
service : a server may host multiple services
message type
Because it uses serialization, the type being serialized has to have an default constructor (no parameters).

// the WSDL and the Proxy
description of a web service (one or more web methods), xml used to generated a proxy for client. the proxy has all the info for accessing a web service. it also has stubs of the web methods

Security of Web Service
1. authentication, impersonation
type of credentials: username/password, certificate
2. authorization- assign privileges to user accounts, certificates
3. Avoid breach of credentials:
SSL - information passed through SSL use special encryptography.
Manually asymetric algorithm -
publish a pub key, client application encrypt credentials with the pub key
the service side decrypt it with corresponding private key.
4. the message passing along with request and response.
MTOM - Message based security. it is transparent to developer, just by configuring lower level layer's behavior.

>> LinQ and compiler awareness of db schema change
if you know Hibernate, it is easy to understand LINQ. LINQ integrates .Net language with database object mapping, in other words, with LINQ you can directly get data from database in the form of objects. without tidious conversion from db query result to objects, which is the common implementation in DAL code before LINQ.
The challenge of the solution with ADO.Net is that the compiler has no idea of schema change made in database. because the code to access the result of a query use column name as a string parameter or use an index number to access data of a column.

this is changed with LINQ. when DB schema is changed, SQLMetal tool will regenerate LINQ classes, so any mismatch of code using LINq classes will be caught by the compiler.
the schemas that is reflected by SQLMetal include:
stored procedures
functions
tables
views
An example of a LINQ based DAL
..
compile time verification vs string parameters
defered execution
INumerable and IQueryable - ToList(), Count()
IQueryable<Category> myQuery =
from cat in categories
select cat;
Category cat = myQueryable.where(c=>c.id==1).SingleOrDefault;
>> CLR
figure
.Net Languages => MISL with metadata => CLR
{
load assembly
compile JIT
NGEN
heap and GC - garbage collection
AppDomain -
one thread, isolated by type safe
securing assembly
}

intermediate language
ildasm

// CTS common type system
boxing
value type - reference type
Common Language Spec
Process Directives
#define DEBUG
#IF
#ELSE
#ENFIF
struct is a value type
array is reference type - System.Array
delegate and events
public delegate void SDelegate(params);
public event SDelegate SEvent;
// attribute programming
[WebService]
public void MyMethod()
{
..
}
once compiled, "Every C# type has associated metadata"
meta data can include attributes with that type. CLR provides a way to ctore attributes
attributes are used to extentively by .net framework class library. they can be applied to classes, interfaces, structures, methods fieldsm parameters, and even assemblies.

[assembly: AssemblyCompanyAttribute("QuickBunk")]
it is stored in the assembly's manifest
custom attributes
System.Attributes
System.Reflection
Attribute.GetCustomAttributes to access
"attributes are a commonly used feature in CLR-based software"

No comments: