构建面向对象的应用软件系统框架
转自:http://www.lvjiyong.com/books/OODesigner/
图2.2
public class Product
{
public string Name; //名称
public decimal Price;//价格
public int Count;//数量
}
可以按照如下方法使用Product类:
Product p=new Product();
//……处理Product
|
public class Form
{
public string ID; //入库单编号
public DateTime AddTime; //入库时间
public FormDetail[] FormDetails; //入库单明细
}
public class FormDetail
{
public Product InProduct; //入库产品
public int Count; //入库数量
}
|
public class FormDetailsCollection: ArrayList
{
public void Add(FormDetail detail)
{
base.Add(detail);
}
public new FormDetail this[int nIndex]
{
get
{
return (FormDetail)base[nIndex];
}
}
}
|
[TableMap("Schdule","GUID")]
[WebsharpEntityInclude(typeof(Schdule))]
public abstract class Schdule : PersistenceCapable
{
[ColumnMap("GUID",DbType.String,"")]
public abstract string GUID{get;set;}
[ColumnMap("UserID",DbType.String,"")]
public abstract string UserID{get;set;}
[ColumnMap("StartTime",DbType.DateTime)]
public abstract DateTime StartTime{get;set;}
[ColumnMap("EndTime",DbType.DateTime)]
public abstract DateTime EndTime{get;set;}
[ColumnMap("Title",DbType.String,"")]
public abstract string Title{get;set;}
[ColumnMap("Description",DbType.String,"")]
public abstract string Description{get;set;}
[ColumnMap("RemidTime",DbType.DateTime)]
public abstract DateTime RemidTime{get;set;}
[ColumnMap("AddTime",DbType.DateTime)]
public abstract DateTime AddTime{get;set;}
[ColumnMap("Status",DbType.Int16,0)]
public abstract short Status{get;set;}
}
|
Schdule schdule = EntityManager.CreateObject(typeof(Schdule)) as Schdule;
|
EntityData schdule =EntityManager.GetEntityData("Schdule");
|
string Title = schdule["Title"]
|
Schdule schdule=new Schdule(……);
PersistenceManager PM=PMFactory.initialize(……);
Pm.persist(schdule);
|
public bool AddSchdule(Schdule schdule)
{
PersistenceManager pm =
PersistenceManagerFactory.Instance().CreatePersistenceManager();
try
{
pm.PersistNewObject(schdule);
return true;
}
catch
{
return false;
}
finally
{
pm.Close();
}
}
|
public bool AddSchdule(Schdule schdule)
{
if(!CheckSchdule(schdule))
return false;
PersistenceManager pm =
PersistenceManagerFactory.Instance().CreatePersistenceManager();
Transaction trans = pm.CurrentTransaction;
trans.Begin();
try
{
pm.PersistNewObject(schdule);
trans.Commit();
return true;
}
catch
{
trans.Rollback();
return false;
}
finally
{
pm.Close();
}
}
|
public bool AddSchdule(Schdule schdule,string[] otherPeoples)
{
if(!CheckSchdule(schdule))
return false;
PersistenceManager pm =
PersistenceManagerFactory.Instance().CreatePersistenceManager();
Transaction trans = pm.CurrentTransaction;
trans.Begin();
try
{
pm.PersistNewObject(schdule);
foreach(string otherPeople in otherPeoples)
{
Schdule s = EntityManager.CreateObject(typeof(Schdule)) as Schdule;
s.GUID = Guid.NewGuid().ToString();
s.UserID = otherPeople;
s.StartTime = schdule.StartTime;
s.EndTime = schdule.StartTime;
s.Title = schdule.Title;
s.Description = schdule.Description;
s.RemidTime = schdule.RemidTime;
s.AddTime = DateTime.Now;
s.Status = 0;
pm.PersistNewObject(s);
}
trans.Commit();
return true;
}
catch
{
trans.Rollback();
return false;
}
finally
{
pm.Close();
}
}
|
public interface ISecuritySystem
{
bool Login(string userID,string password);
void Logout();
bool IsLogin();
Suser CurrentUser();
}
……
//在需要调用服务的客户端:
ISecuritySystem ss = ServiceLocator.FindService(
"SecurityService",typeof(ISecuritySystem)) as ISecuritySystem;
|
double price = 100 ;
|
struct product
{
char* name;
double price;
double weight;
}
|
public class Product
{
public String name;
public double price;
public double weight;
}
|
public class Product
{
public String name;
public double price;
public double weight;
public Size size;
}
public class Size
{
public int height;
public int width;
}
|
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<description>Here is the description of the test's beans</description>
<enterprise-beans>
<entity>
<description>... Bean example one ...</description>
<display-name>Bean example two</display-name>
<ejb-name>ExampleTwo</ejb-name>
<home>tests.Ex2Home</home>
<remote>tests.Ex2</remote>
<ejb-class>tests.Ex2Bean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>tests.Ex2PK</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>1.x</cmp-version>
<cmp-field>
<field-name>field1</field-name>
</cmp-field>
<cmp-field>
<field-name>field2</field-name>
</cmp-field>
<cmp-field>
<field-name>field3</field-name>
</cmp-field>
<primkey-field>field3</primkey-field>
<env-entry>
<env-entry-name>name1</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>value1</env-entry-value>
</env-entry>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>ExampleTwo</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Supports</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
|
<?xml version="1.0"?>
<jdo>
<package name="org.lgd.test">
<class name="Human" objectid-class="Human$ObjectId">
<field name="ID" primary-key="true"/>
<field name="name" primary-key="true"/>
<field name="dress">
<collection element-type="Dress"/>
</field>
</class>
<class name="Dress">
<field name="color">
<map key-type="String" value-type="ColorTye"/>
</field>
</class>
<class name="ColorTye">
<field name="red" embedded="true"/>
<field name="blue" embedded="true"/>
</class>
</package>
<package name="org.lgd.test">
<class name="Human"/>
<class name="Asian" persistence-capable-superclass="Human">
<field name="country">
<collection element-type="Asua$Chinese"/>
<extension vendor-name="kodo" key="inverse-owner" value="Human"/>
</field>
</class>
<class name="Human$Asian"/>
</package>
</jdo>
|
[TableMap("Schdule","GUID")]
[WebsharpEntityInclude(typeof(Schdule))]
public abstract class Schdule : PersistenceCapable
{
[ColumnMap("GUID",DbType.String,"")]
public abstract string GUID{get;set;}
[ColumnMap("UserID",DbType.String,"")]
public abstract string UserID{get;set;}
[ColumnMap("StartTime",DbType.DateTime)]
public abstract DateTime StartTime{get;set;}
[ColumnMap("EndTime",DbType.DateTime)]
public abstract DateTime EndTime{get;set;}
[ColumnMap("Title",DbType.String,"")]
public abstract string Title{get;set;}
[ColumnMap("Description",DbType.String,"")]
public abstract string Description{get;set;}
[ColumnMap("RemidTime",DbType.DateTime)]
public abstract DateTime RemidTime{get;set;}
[ColumnMap("AddTime",DbType.DateTime)]
public abstract DateTime AddTime{get;set;}
[ColumnMap("Status",DbType.Int16,0)]
public abstract short Status{get;set;}
}
|
public interface CustomerHome extends EJBHome
{
public Customer create(String CustomerID,String CustomerName)
throws RemoteException , CreateException;
public Customer findByrimaryKey(String CustomerID)
throws RemoteException , FinderException;
}
|
public interface Customer extends EJBObject
{
public void setCustomerName(String customerName) throws RemoteException;
public String getCustomerName() throws RemoteException;
}
|
public class CustomerEJB implements EntityBean
{
public String customerID;
public String customerName;
public void setCustomerName(String customerName)
{
this.customerName = customerName ;
}
public String getCustomerName()
{
return this.customerName;
}
}
|
Customer customer = new Customer(“12345”);
customer.setCustomerName(“My Customer”);
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(props);
PersistenceManager pm = pmf.getPersistenceManager();
pm.makePersistent(customer);
pm.close();
|
public interface Query extends java.io.Serializable
{
void setClass(Class cls);
void setCandidates(Extent pcs);
void setCandidates(Collection pcs);
void setFilter(String filter);
void declareImports(String imports);
void declareParameters(String parameters);
void declareVariables(String variables);
void setOrdering(String ordering);
void setIgnoreCache(boolean ignoreCache);
boolean getIgnoreCache();
void compile();
Object execute();
Object execute(Object p1);
Object execute(Object p1, Object p2);
Object execute(Object p1, Object p2, Object p3);
Object executeWithMap (Map parameters);
Object executeWithArray (Object[] parameters);
void close (Object queryResult);
void closeAll ();
}
|
Class empClass = Employee.class;
Extent clnEmployee = pm.getExtent (empClass, false);
String filter = “salary > sal”;
Query q = pm.newQuery (clnEmployee, filter);
String param = “Float sal”;
q.declareParameters (param);
Collection emps = (Collection) q.execute (new Float (30000.));
|
public interface DataAccess
{
#region Support Property & Method
DatabaseType DatabaseType{get;}
IDbConnection DbConnection{get;}
IDbTransaction BeginTransaction();
void Open();
void Close();
bool IsClosed{get;}
#endregion
#region ExecuteNonQuery
int ExecuteNonQuery(CommandType commandType, string commandText);
int ExecuteNonQuery(string commandText);
int ExecuteNonQuery(string commandText, QueryParameterCollection commandParameters);
int ExecuteNonQuery(CommandType commandType, string commandText, QueryParameterCollection commandParameters);
#endregion ExecuteNonQuery
//……因篇幅的原因,这里没有列出所有的方法,关于其他方法的定义请参见源代码。
}
|
图5.1
public abstract class AbstractDataAccess : DataAccess
{
#region DataAccess
#region Support Property & method
public abstract DatabaseType DatabaseType{get;}
public abstract IDbConnection DbConnection{get;}
public void Close()
{
this.DbConnection.Close();
}
public void Open()
{
if(this.DbConnection.State.Equals(ConnectionState.Closed))
this.DbConnection.Open();
}
……
#endregion Support Property & method
#region ExecuteNonQuery
public int ExecuteNonQuery(CommandType commandType, string commandText)
{
return this.ExecuteNonQuery(commandType, commandText, null);
}
public int ExecuteNonQuery(string commandText)
{
return this.ExecuteNonQuery(CommandType.Text, commandText, null);
}
public int ExecuteNonQuery(string commandText, QueryParameterCollection commandParameters)
{
return this.ExecuteNonQuery(CommandType.Text, commandText, commandParameters);
}
public abstract int ExecuteNonQuery(CommandType commandType, string commandText, QueryParameterCollection commandParameters);
#endregion ExecuteNonQuery
protected void SyncParameter(QueryParameterCollection commandParameters)
{
if((commandParameters!=null) && (commandParameters.Count>0) )
{
for(int i=0;i<commandParameters.Count;i++)
{
commandParameters[i].SyncParameter();
}
}
}
}
|
public sealed class MSSqlDataAccess : AbstractDataAccess
{
#region Constructor
public MSSqlDataAccess(SqlConnection conn)
{
this.m_DbConnection=conn;
}
public MSSqlDataAccess(string connectionString)
{
this.m_DbConnection=new SqlConnection(connectionString);
}
#endregion
#region DataAccess
#region Support Property & method
public override DatabaseType DatabaseType
{
get{return DatabaseType.MSSQLServer;}
}
private SqlConnection m_DbConnection;
public override IDbConnection DbConnection
{
get
{
return m_DbConnection;
}
}
private SqlTransaction trans=null;
public override IDbTransaction BeginTransaction()
{
trans=m_DbConnection.BeginTransaction();
return trans;
}
#endregion Support Property & method
#region ExecuteNonQuery
public override int ExecuteNonQuery(CommandType commandType, string commandText, QueryParameterCollection commandParameters)
{
SqlCommand cmd=new SqlCommand();
PrepareCommand(cmd,commandType, commandText,commandParameters);
int tmpValue=cmd.ExecuteNonQuery();
SyncParameter(commandParameters);
cmd.Parameters.Clear();
return tmpValue;
}
#endregion ExecuteNonQuery
#region ExecuteDataSet
public override DataSet ExecuteDataset(CommandType commandType, string commandText, QueryParameterCollection commandParameters,DataSet ds,string tableName)
{
SqlCommand cmd=new SqlCommand();
PrepareCommand(cmd,commandType, commandText,commandParameters);
SqlDataAdapter da=new SqlDataAdapter(cmd);
if(Object.Equals(tableName,null) || (tableName.Length<1))
da.Fill(ds);
else
da.Fill(ds,tableName);
SyncParameter(commandParameters);
cmd.Parameters.Clear();
return ds;
}
#endregion ExecuteDataSet
#region ExecuteReader
public override IDataReader ExecuteReader(CommandType commandType, string commandText, QueryParameterCollection commandParameters)
{
SqlCommand cmd=new SqlCommand();
PrepareCommand(cmd,commandType, commandText,commandParameters);
SqlDataReader dr=cmd.ExecuteReader();
SyncParameter(commandParameters);
cmd.Parameters.Clear();
return dr;
}
#endregion ExecuteReader
#region ExecuteScalar
public override object ExecuteScalar(CommandType commandType, string commandText, QueryParameterCollection commandParameters)
{
SqlCommand cmd=new SqlCommand();
PrepareCommand(cmd,commandType, commandText,commandParameters);
object tmpValue=cmd.ExecuteScalar();
SyncParameter(commandParameters);
cmd.Parameters.Clear();
return tmpValue;
}
#endregion ExecuteScalar
#region ExecuteXmlReader
public override XmlReader ExecuteXmlReader(CommandType commandType, string commandText, QueryParameterCollection commandParameters)
{
SqlCommand cmd=new SqlCommand();
PrepareCommand(cmd,commandType, commandText,commandParameters);
XmlReader reader=cmd.ExecuteXmlReader();
SyncParameter(commandParameters);
cmd.Parameters.Clear();
return reader;
}
#endregion ExecuteXmlReader
#endregion
private void PrepareCommand(SqlCommand cmd,CommandType commandType, string commandText, QueryParameterCollection commandParameters)
{
cmd.CommandType=commandType;
cmd.CommandText=commandText;
cmd.Connection=this.m_DbConnection;
cmd.Transaction=trans;
if((commandParameters!=null) && (commandParameters.Count>0) )
{
for(int i=0;i<commandParameters.Count;i++)
{
commandParameters[i].InitRealParameter(DatabaseType.MSSQLServer);
cmd.Parameters.Add(commandParameters[i].RealParameter as SqlParameter);
}
}
}
}
|
public sealed class DataAccessFactory
{
private DataAccessFactory(){}
private static DatabaseProperty defaultDatabaseProperty;
public static DatabaseProperty DefaultDatabaseProperty
{
get{return defaultDatabaseProperty;}
set{defaultDatabaseProperty=value;}
}
public static DataAccess CreateDataAccess(DatabaseProperty pp)
{
DataAccess dataAccess;
switch(pp.DatabaseType)
{
case(DatabaseType.MSSQLServer):
dataAccess = new MSSqlDataAccess(pp.ConnectionString);
break;
case(DatabaseType.Oracle):
dataAccess = new OracleDataAccess(pp.ConnectionString);
break;
case(DatabaseType.OleDBSupported):
dataAccess = new OleDbDataAccess(pp.ConnectionString);
break;
default:
dataAccess=new MSSqlDataAccess(pp.ConnectionString);
break;
}
return dataAccess;
}
public static DataAccess CreateDataAccess()
{
return CreateDataAccess(defaultDatabaseProperty);
}
}
|
DataAccess dao=DataAccessFactory.CreateDataAccess(persistenceProperty);
db.Open();
db.需要的操作
db.Close();
|
[AttributeUsage(AttributeTargets.Class)]
public class TableMapAttribute : Attribute
{
private string tableName;
private string[] primaryKeys;
public TableMapAttribute(string tableName,params string[] primaryKeys)
{
this.tableName = tableName;
this.primaryKeys = primaryKeys;
}
public string TableName
{
get{return tableName;}
set{tableName = value;}
}
public string[] PrimaryKeys
{
get{return primaryKeys;}
set{primaryKeys = value;}
}
}
|
[AttributeUsage(AttributeTargets.Property)]
public class ColumnMapAttribute : Attribute
{
private string columnName;
private DbType dbtype;
private object defaultValue;
public ColumnMapAttribute(string columnName,DbType dbtype)
{
this.columnName = columnName;
this.dbtype = dbtype;
}
public ColumnMapAttribute(string columnName,DbType dbtype,object defaultValue)
{
this.columnName = columnName;
this.dbtype = dbtype;
this.defaultValue = defaultValue;
}
public string ColumnName
{
get{return columnName;}
set{columnName = value;}
}
public DbType DbType
{
get{return dbtype;}
set{dbtype = value;}
}
public object DefaultValue
{
get{return defaultValue;}
set{defaultValue = value;}
}
}
|
[AttributeUsage(AttributeTargets.Property)]
public class ReferenceObjectAttribute : Attribute
{
private Type referenceType;
private string primaryKey;
private string foreignKey;
public ReferenceObjectAttribute(Type referenceType,string primaryKey,string foreignKey)
{
this.referenceType = referenceType;
this.primaryKey = primaryKey;
this.foreignKey = foreignKey;
}
public ReferenceObjectAttribute(){}
public Type ReferenceType
{
get{return referenceType;}
set{referenceType = value;}
}
public string PrimaryKey
{
get{return primaryKey;}
set{primaryKey = value;}
}
public string ForeignKey
{
get{return foreignKey;}
set{foreignKey = value;}
}
}
|
[AttributeUsage(AttributeTargets.Property)]
public class SubObjectAttribute : Attribute
{
private Type subObjectType;
private string primaryKey;
private string foreignKey;
public SubObjectAttribute(Type subObjectType, string primaryKey, string foreignKey)
{
this.subObjectType = subObjectType;
this.primaryKey = primaryKey;
this.foreignKey = foreignKey;
}
public SubObjectAttribute(){}
public Type SubObjectType
{
get { return subObjectType; }
set { subObjectType = value; }
}
public string PrimaryKey
{
get{return primaryKey;}
set{primaryKey = value;}
}
public string ForeignKey
{
get{return foreignKey;}
set{foreignKey = value;}
}
}
|
[AttributeUsage(AttributeTargets.Property)]
public class AutoIncreaseAttribute : Attribute
{
private int step = 1;
public AutoIncreaseAttribute(){}
public AutoIncreaseAttribute(int step)
{
this.step = step;
}
public int Step
{
get{return step;}
set{step = value;}
}
}
|
//订单类别
[TableMap("OrderType","ID")]
public class OrderType
{
private int m_ID;
private string m_Name;
[ColumnMap("ID",DbType.Int32)]
public int ID
{
get { return m_ID; }
set { m_ID = value; }
}
[ColumnMap("Name", DbType.String)]
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
}
//订单
[TableMap("Order", "OrderID")]
public class Order
{
private int m_OrderID;
private OrderType m_OrderType;
private string m_Title;
private DateTime m_AddTime;
private bool m_IsSigned;
private List<OrderDetail> m_Details;
[ColumnMap("OrderID",DbType.Int32)]
[AutoIncrease]
public int OrderID
{
get { return m_OrderID; }
set { m_OrderID = value; }
}
[ReferenceObject(typeof(OrderType),"ID","TypeID")]
[ColumnMap("TypeID",DbType.String)]
public OrderType OrderType
{
get { return m_OrderType; }
set { m_OrderType = value; }
}
[ColumnMap("Title", DbType.String)]
public string Title
{
get { return m_Title; }
set { m_Title = value; }
}
[ColumnMap("AddTime", DbType.DateTime)]
public DateTime AddTime
{
get { return m_AddTime; }
set { m_AddTime = value; }
}
[ColumnMap("AddTime", DbType.Boolean)]
public bool IsDigned
{
get { return m_IsSigned; }
set { m_IsSigned = value; }
}
[SubObject(typeof(OrderDetail),"OrderID","OrderID")]
public List<OrderDetail> Details
{
get { return m_Details; }
set { m_Details = value; }
}
}
//订单明细
public class OrderDetail
{
private int m_DetailID;
private int m_OrderID;
private string m_ProductName;
private int m_Amount;
[ColumnMap("ID", DbType.Int32)]
[AutoIncrease]
public int DetailID
{
get { return m_DetailID; }
set { m_DetailID = value; }
}
[ColumnMap("OrderID", DbType.Int32)]
public int OrderID
{
get { return m_OrderID; }
set { m_OrderID = value; }
}
[ColumnMap("ProductName", DbType.String)]
public string ProductName
{
get { return m_ProductName; }
set { m_ProductName = value; }
}
[ColumnMap("Amount", DbType.Int32)]
public int Amount
{
get { return m_Amount; }
set { m_Amount = value; }
}
}
|
[ReferenceObject(typeof(OrderType),"ID","TypeID")]
[ColumnMap("TypeID",DbType.String)]
public OrderType OrderType
{
get { return m_OrderType; }
set { m_OrderType = value; }
}
|
[SubObject(typeof(OrderDetail),"OrderID","OrderID")]
public List<OrderDetail> Details
{
get { return m_Details; }
set { m_Details = value; }
}
|
OrderType:
INSERT INTO OrderType(ID,Name) VALUES(@ID,@NAME)
UPDATE OrderType SET Name=@Name Where ID=@ID
DELETE FROM OrderType Where ID=@ID
|
Order:
INSERT INTO Order(TypeID,Title,AddTime,IsSigned) VALUES (@TypeID, @Title, @AddTime, @IsSigned) ; SELECT @OrderID=@@IDENTITY ‘其中@OrderID为传出参数
UPDATE Order SET TypeID=@TypeID, Title=@Title, AddTime=@AddTime, IsSigned=@IsSigned WHERE OrderID=@OrderID
DELETE FROM Order WHERE OrderID=@OrderID
|
OederDetail:
INSERT INTO OederDetail(OrderID,ProductName,Amount) VALUES (@OrderID, @ProductName, @Amount); SELECT @ID=@@IDENTITY ‘其中@ID为传出参数
UPDATE OederDetail SET OrderID=@OrderID, ProductName=@ProductName, Amount=@Amount WHERE ID=@ID
DELETE FROM OederDetail WHERE ID=@ID
|
[TableMap("Table1", "Property1")]
public class Parent
{
private string property1;
private string property2;
[ColumnMap("Column1", DbType.String)]
public string Property1
{
get { return property1; }
set { property1=value; }
}
[ColumnMap("Column2", DbType.String)]
public string Property2
{
get { return property2; }
set { property2 = value; }
}
}
[TableMap("Table1", "Property1")]
public class Child1 : Parent
{
private string property3;
[ColumnMap("Column3", DbType.String)]
public string Property3
{
get { return property3; }
set { property3 = value; }
}
}
[TableMap("Table1", "Property1")]
public class Child2 : Parent
{
private string property4;
[ColumnMap("Column4", DbType.String)]
public string Property4
{
get { return property4; }
set { property4 = value; }
}
}
|
Child1 c1 = new Child1();
c1.Property1 = "P11";
c1.Property2 = "P12";
c1.Property3 = "P13";
|
Column1
|
Column2
|
Column3
|
Column4
|
P11
|
P12
|
P13
|
NULL
|
Child2 c1 = new Child2();
c2.Property1 = "P21";
c2.Property2 = "P22";
c2.Property4 = "P24";
|
Column1
|
Column2
|
Column3
|
Column4
|
P21
|
P22
|
NULL
|
P24
|
[TableMap(null, "Property1")]
public class Parent
{
private string property1;
private string property2;
[ColumnMap("Column1", DbType.String)]
public string Property1
{
get { return property1; }
set { property1=value; }
}
[ColumnMap("Column2", DbType.String)]
public string Property2
{
get { return property2; }
set { property2 = value; }
}
}
[TableMap("Child1", "Property1")]
public class Child1 : Parent
{
private string property3;
[ColumnMap("Column3", DbType.String)]
public string Property3
{
get { return property3; }
set { property3 = value; }
}
}
[TableMap("Child2", "Property1")]
public class Child2 : Parent
{
private string property4;
[ColumnMap("Column4", DbType.String)]
public string Property4
{
get { return property4; }
set { property4 = value; }
}
}
|
Child1 c1 = new Child1();
c1.Property1 = "P11";
c1.Property2 = "P12";
c1.Property3 = "P13";
|
Column1
|
Column2
|
Column3
|
P11
|
P12
|
P13
|
[TableMap("Parent", "Property1")]
public class Parent
{
private string property1;
private string property2;
[ColumnMap("Column1", DbType.String)]
public string Property1
{
get { return property1; }
set { property1=value; }
}
[ColumnMap("Column2", DbType.String)]
public string Property2
{
get { return property2; }
set { property2 = value; }
}
}
[TableMap("Child1", "Property1")]
public class Child1 : Parent
{
private string property3;
[ColumnMap("Column3", DbType.String)]
public string Property3
{
get { return property3; }
set { property3 = value; }
}
}
[TableMap("Child2", "Property1")]
public class Child2 : Parent
{
private string property4;
[ColumnMap("Column4", DbType.String)]
public string Property4
{
get { return property4; }
set { property4 = value; }
}
}
|
Child1 c1 = new Child1();
c1.Property1 = "P11";
c1.Property2 = "P12";
c1.Property3 = "P13";
|
Column1
|
Column2
|
P11
|
P12
|
Column1
|
Column3
|
P11
|
P13
|
public enum EntityState{Transient,New,Persistent,Deleted}
|
public enum PersistOptions{SelfOnly,IncludeChildren,IncludeReference,Full}
public interface PersistenceManager : IDisposable
{
void Close();
bool IsClosed{get;}
Transaction CurrentTransaction{ get;}
bool IgnoreCache{get;set;}
void PersistNew(object entity);
void PersistNew(object entity,PersistOptions options);
void Persist(object entity);
void Persist(object entity,PersistOptions options);
void Persist(object entity,params string[] properties);
void Persist(object entity,PersistOptions options,params string[] properties);
void Delete(object entity);
void Delete(object entity,PersistOptions options);
void Attach(object entity);
void Attach(object entity,PersistOptions options);
void Reload(object entity);
void Reload(object entity,PersistOptions options);
void Evict (object entity);
void EvictAll (object[] pcs);
void EvictAll (ICollection pcs);
void EvictAll ();
object FindByPrimaryKey(Type entityType,object id);
object FindByPrimaryKey(Type entityType,object id,PersistOptions options);
T FindByPrimaryKey<T>(object id);
T FindByPrimaryKey<T>(object id, PersistOptions options);
object GetReference(object entity);
object GetReference(object entity,Type[] parents);
object GetChildren(object entity);
object GetChildren(object entity,Type[] children);
EntityState GetState(object entity);
ICollection GetManagedEntities();
bool Flush();
Query NewQuery();
Query NewQuery(Type entityType);
Query NewQuery(Type entityType,string filter);
Query NewQuery(Type entityType,string filter,QueryParameterCollection paramColletion);
Query<T> NewQuery<T>();
Query<T> NewQuery<T>(string filter);
Query<T> NewQuery<T>(string filter, QueryParameterCollection paramColletion);
}
|
public interface Query
{
Type EntityType{get;set;}
string EntityTypeName{get;set;}
string Filter{get;set;}
QueryParameterCollection Parameters{get;set;}
string Ordering{get;set;}
bool IgnoreCache{get;set;}
PersistOptions Options { get;set;}
ICollection QueryObjects();
DataSet QueryDataSet();
object GetChildren(object entity);
object GetChildren(DataSet dst);
object GetChildren(object entity, Type[] children);
object GetChildren(DataSet entity, Type[] children);
object GetReference(object entity);
object GetReference(DataSet entity);
object GetReference(object entity, Type[] parents);
object GetReference(DataSet entity, Type[] parents);
PersistenceManager PersistenceManager{get;}
bool IsClosed{get;}
void Close ();
void Open();
}
public interface Query<T> : Query
{
new ICollection<T> QueryObjects();
}
|
public interface Transaction
{
void Begin();
void Commit();
void Rollback();
PersistenceManager PersistenceManager{get;}
}
|
DatabaseProperty dbp = new DatabaseProperty();
dbp.DatabaseType = DatabaseType.MSSQLServer;
dbp.ConnectionString = "Server=127.0.0.1;UID=sa;PWD=sa;Database=WebsharpTest;";
PersistenceManager pm = PersistenceManagerFactory.Instance().Create(dbp);
Order o = new Order();
o.OrderType = new OrderType(3, "音响");
o.OrderID = 3;
o.Title = "SecondOrder";
o.IsDigned = false;
o.AddTime = DateTime.Now;
o.Details = new List<OrderDetail>(2);
for (int j = 1; j < 3; j++)
{
OrderDetail od= new OrderDetail();
od.OrderID = 3;
od.ProductID = j;
od.Amount = j;
o.Details.Add(od);
}
pm.PersistNew(o, PersistOptions.IncludeChildren);
pm.Flush();
pm.Close();
|
private static MetaData ParseMetaData(Type t, DatabaseType dbType)
{
MetaData m = new MetaData();
m.ClassName = t.Name; //类名
m.EntityType = t; //实体类的类型
m.MapTable = GetMappedTableName(t); //实体类映射的表
m.PrimaryKeys = GetKeyColumns(t); //主键
if (m.PrimaryKeys.Length > 1)
m.IsMultiPrimaryKey = true;
else
m.IsMultiPrimaryKey = false;
……
}
|
PropertyInfo[] pinfos = t.GetProperties();
m.FieldMetaDatas = new Dictionary<string,FieldMetadata>(pinfos.Length);
foreach (PropertyInfo pinfo in pinfos)
{
FieldMetadata fd = new FieldMetadata();
fd.PropertyName = pinfo.Name;
ColumnMapAttribute cattr = Attribute.GetCustomAttribute(pinfo, typeof(ColumnMapAttribute)) as ColumnMapAttribute;
if(!Object.Equals(null,cattr))
{
fd.ColumnName = cattr.ColumnName;
fd.DbType = cattr.DbType;
fd.DefaultValue = cattr.DefaultValue;
}
else
{
fd.ColumnName = fd.PropertyName ;
fd.DbType = DbType.String;
fd.DefaultValue = String.Empty;
}
……
}
|
SqlGenerator sg = SqlGenerator.Instance(dbType);
m.SelectSql = sg.GenerateSql(t, OperationType.SelectByKey);
|
private SqlStruct GenerateInsertSql(Type entityType)
{
string autoP;
bool autoInscrease = MetaDataManager.GetAutoInscreaseProperty(entityType, out autoP);
List<string> lcolumns = MetaDataManager.GetDbColumns(entityType);
string[] parameters = new string[lcolumns.Count];
ParamField[] paramField = new ParamField[lcolumns.Count];
if (autoInscrease)
{
lcolumns.Remove(autoP);
}
string[] columns = lcolumns.ToArray();
for (int i = 0; i < columns.Length; i++)
{
parameters[i] = "@" + columns[i];
paramField[i] = new ParamField(parameters[i], columns[i]);
}
if (autoInscrease)
{
parameters[parameters.Length-1] = "@" + autoP;
paramField[parameters.Length-1] = new ParamField(parameters[parameters.Length - 1], autoP);
}
string tableName = MetaDataManager.GetMappedTableName(entityType);
StringBuilder strSql = new StringBuilder("INSERT INTO ").Append(tableName).Append("(").Append(string.Join(",", columns)).Append(") VALUES(").Append(string.Join(",", parameters)).Append(")");
if (autoInscrease)
{
strSql.Append(";SELECT @").Append(autoP).Append("=@@IDENTITY");
}
return new SqlStruct(strSql.ToString(),paramField);
}
|
public enum EntityState{Transient,New,Persistent,Deleted}
|
public class StateManager
{
public StateManager(object entity)
{
this.m_Entity = entity;
}
public StateManager(object entity,EntityState state)
{
this.m_Entity = entity;
this.m_State = state;
}
private object m_Entity;
public object Entity
{
get { return m_Entity; }
set { m_Entity = value; }
}
private EntityState m_State;
public EntityState State
{
get { return m_State; }
set { m_State = value; }
}
}
|
public void PersistNew(object entity, PersistOptions options)
{
//首先,检查这个对象是否已经是受管理的对象
StateManager smanager;
if (IsManagedBySelf(entity,out smanager))
{
throw new EntityIsPersistentException();
}
//将对象标记为受管理的,并且状态是EntityState.New
smanager = new StateManager(entity,EntityState.New);
stateManagers.Add(smanager);
//添加到操作列表中
opEntityList.Add(new OperationInfo(smanager,options));
}
|
foreach (OperationInfo opInfo in opEntityList)
{
IEntityOperator op = EntityOperatorFactory.CreateEntityOperator(dao, opInfo.StateManager.State);
op.Execute(opInfo.StateManager.Entity, dao);
CacheProxy.CacheEntity(opInfo.StateManager.Entity);
}
|
图5.1
public class Security
{
public bool CheckRight(User currentUser , Model accessModel , OperationType operation)
{
……//校验权限
}
}
|
public class BusinessClass
{
public void BusinessMethod()
{
Security s = new Security();
if (!s. CheckRight(……))
{
return ;
}
……//执行业务逻辑
}
}
|
[AspectManaged(true)]
public class BusinessClass : AspectObject
{
public void BusinessMethod()
{
……//执行业务逻辑
}
}
……//执行业务逻辑
|
public class SecurityAspect : IAspect
{
public void Execute(object[] paramList)
{
if(!Security.CheckRight(......))
{
throw new SecurityException("你没有权限!");
}
}
}
|
<Websharp.Aspects>
<Aspect type="MyAPP.SecurityAspect, MyAPP" deploy-model="Singleton"
pointcut-type="Method" action-position="before" match="*,*" />
</Websharp.Aspects>
|
public abstract class AspectObject : ContextBoundObject
|
[AspectManaged(true)]
public class BusinessClass : AspectObject
{
……
}
|
public interface IAspect
{
void PreProcess(IMessage msg);
void PostProcess(IMessage msg);
}
|
[AttributeUsage(AttributeTargets.Class)]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.Infrastructure)]
public class AspectManagedAttribute : ProxyAttribute
{
private bool aspectManaged;
public AspectManagedAttribute()
{
aspectManaged=true;
}
public AspectManagedAttribute(bool AspectManaged)
{
aspectManaged=AspectManaged;
}
}
|
public override MarshalByRefObject CreateInstance(Type serverType)
{
MarshalByRefObject mobj= base.CreateInstance(serverType);
if(aspectManaged)
{
RealProxy realProxy = new AspectProxy(serverType,mobj);
MarshalByRefObject retobj = realProxy.GetTransparentProxy() as MarshalByRefObject;
return retobj;
}
else
{
return mobj;
}
}
|
public class AspectProxy : RealProxy
|
public override IMessage Invoke(IMessage msg)
{
PreProcess(msg);
IMessage retMsg;
if (msg is IConstructionCallMessage)
{
IConstructionCallMessage ccm = (IConstructionCallMessage)msg; RemotingServices.GetRealProxy(target).InitializeServerObject(ccm);
ObjRef oRef = RemotingServices.Marshal(target);
RemotingServices.Unmarshal(oRef);
retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage
(ccm,(MarshalByRefObject)this.GetTransparentProxy());
}
else
{
IMethodCallMessage mcm = (IMethodCallMessage) msg;
retMsg = RemotingServices.ExecuteMessage(target, mcm);
}
PostProcess(msg);
return retMsg;
}
|
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Websharp.Aspects" type="Websharp.Aspect.AspectConfigHandler,Websharp.Aspect" />
</configSections>
<Websharp.Aspects>
<Aspect type="WeaveTest.FirstAspect,WeaveTest" deploy-model="None"
pointcut-type="Method|Construction|Property" action-position="Both" match="*,Get*" />
</Websharp.Aspects>
</configuration>
|
public class SetCharacterEncodingFilter implements Filter
{
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException, ServletException
{
request.setCharacterEncoding(“gb2312”);
chain.doFilter(request, response);
}
}
|
BEGIN TRANSACTION
--进行处理
如果在处理的过程中发生错误,ROLLBACK TRANSACTION
如果一切正常,COMMIT TRANSACTION
END TRANSACTION
|
CREATE TRIGGER TestTrig ON TestTab FOR UPDATE AS
BEGIN TRANSACTION
INSERT INTO TrigTarget
SELECT * FROM inserted
IF (@@error <> 0)
BEGIN
ROLLBACK TRANSACTION
END
ELSE BEGIN
COMMIT TRANSACTION
END
|
字段名称
|
数据类型
|
AccountID
|
int
|
Balance
|
Double
|
CREATE TABLE Account(
AccountID int,
Balance double,
Check (Balance>=0)
)
|
AccountID
|
Balance
|
1
|
300
|
2
|
1000
|
public boolean transferFunds(int fromAccount,int toAccount,double amount) throws SQLException
{
const String withdrawSql = "UPDATE Account SET Balance=Balance-"+amount+" WHERE AccountID="+fromAccount;
const String depositSql = "UPDATE Account SET Balance=Balance+"+amount+" WHERE AccountID="+toAccount;
//首先获取数据库连接
Connection conn;
try
{
Context initCtx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) initCtx.lookup(dataSourceName);
Connection cn = ds.getConnection();
}
catch(Exception e)
{
return false;
}
boolean success = false;
try
{
conn.setAutoCommit(false); //开始启动事务
Statement stmt = conn.createStatement();
stmt.executeUpdate(withdrawSql); //取钱
stmt.executeUpdate(depositSql); //存钱
conn.commit();
success = true;
}
catch (SQLException e)
{
conn.rollback();
success = false;
}
finally
{
conn.close();
}
return success;
}
|
AccountID
|
Balance
|
1
|
100
|
2
|
1200
|
public bool TransferFunds(int fromAccount,int toAccount,double amount)
{
const string connString = "......";//设定数据库连接字符串
const string withdrawSql = "UPDATE Account SET Balance=Balance-" + amount + " WHERE AccountID=" + fromAccount;
const string depositSql = "UPDATE Account SET Balance=Balance+" + amount + " WHERE AccountID=" + toAccount;
//首先获取数据库连接
IDbConnection conn = null;
IDbTransaction trans = null;
try
{
conn = new GetConnection(connString); //得到数据库连接
conn.Open();
}
catch (Exception e)
{
return false;
}
boolean success = false;
try
{
trans = conn.BeginTransaction();
IDbCommand cmd = conn.CreateCommand();
cmd.ExecuteNonQuery(withdrawSql); //取钱
cmd.ExecuteNonQuery(depositSql); //存钱
trans.Commit();
success = true;
}
catch (SQLException e)
{
trans.Rollback();
success = false;
}
finally
{
conn.Close();
}
return success;
}
}
|
X/Open 分布式事务(DTP)模型
public void persistAndSend(String data) throws Exception {
try {
DataSource oracleDS = getDataSource("java:comp/env/jdbc/OracleXADS");
persist(data, oracleDS);
DataSource db2DS = getDataSource("java:comp/env/jdbc/DB2XADS");
persist(data, db2DS);
QueueConnectionFactory factory =
getQueueConnectionFactory("java:comp/env/jms/XAExampleQCF");
Queue queue = getQueue("java:comp/env/jms/XAExampleQ");
send(data, factory, queue);
}
catch (Exception e) {
e.printStackTrace();
this.getSessionContext().setRollbackOnly();
throw e;
}
}
|
private void persist(String data, DataSource datasource) throws SQLException {
System.out.println("Adding a new database row containing: " + data);
Connection connection = null;
try {
connection = datasource.getConnection();
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO XA_EXAMPLE (TEXT) VALUES (?)");
statement.setString(1, data);
statement.execute();
System.out.println("Successfully added row: " + data);
}
finally {
if (connection != null)
connection.close();
}
}
private void send(String data, QueueConnectionFactory factory, Queue queue)
throws JMSException {
System.out.println("Sending a message containing: " + data);
QueueConnection connection = null;
try{
connection = factory.createQueueConnection();
QueueSession session = connection.createQueueSession(
false, Session.AUTO_ACKNOWLEDGE);
QueueSender sender = session.createSender(queue);
TextMessage message = session.createTextMessage(data);
sender.send(message);
System.out.println("Successfully sent message: " + data);
}
finally {
if (connection != null)
connection.close();
}
}
private DataSource getDataSource(String jndiName) throws NamingException {
return (DataSource) this.getJNDIObject(jndiName);
}
private QueueConnectionFactory getQueueConnectionFactory(String jndiName)
throws NamingException {
return (QueueConnectionFactory) this.getJNDIObject(jndiName);
}
private Queue getQueue(String jndiName) throws NamingException {
return (Queue) this.getJNDIObject(jndiName);
}
private Object getJNDIObject(String jndiName) throws NamingException {
Context root = new InitialContext();
return root.lookup(jndiName);
}
|
public interface Transaction
{
void Begin();
void Commit();
void Rollback();
PersistenceManager PersistenceManager{get;}
}
|
DatabaseProperty dbp = new DatabaseProperty();
dbp.DatabaseType = DatabaseType.MSSQLServer;
dbp.ConnectionString = "Server=127.0.0.1;UID=sa;PWD=sa;Database=WebsharpTest;";
PersistenceManager pm = PersistenceManagerFactory.Instance().Create(dbp);
Order o = new Order();
o.OrderType = new OrderType(3, "音响");
o.OrderID = 3;
o.Title = "SecondOrder";
o.IsDigned = false;
o.AddTime = DateTime.Now;
o.Details = new List<OrderDetail>(2);
for (int j = 1; j < 3; j++)
{
OrderDetail od = new OrderDetail();
od.OrderID = 3;
od.ProductID = j;
od.Amount = j;
o.Details.Add(od);
}
Transaction t = pm.CurrentTransaction;
t.Begin(); //开始一个事务
try
{
pm.PersistNew(o, PersistOptions.IncludeChildren);
pm.Flush();
t.Commit();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
t.Rollback();
}
finally
{
pm.Close();
}
|
using System.EnterpriseServices;
namespace ESExample
{
[Transaction(TransactionOption.Required)]
public classMyCfgClass :ServicedComponent
{
[AutoComplete]
static void Main(){}
}
}
|
using System.EnterpriseServices;
using System.Reflection;
[assembly:ApplicationName("MyApp")]
[assembly:ApplicationActivation(ActivationOption.Library)]
// AssemblyKeyFile attribute references keyfile generated
// by sn.exe - assembly will have strong name
[assembly:AssemblyKeyFile("keyfile")]
namespace ESExample
{……}
|
sn -k keyfile csc /out:ESExample.dll
/t:library/r:System.EnterpriseServices.dll MyCfgClass.cs
|
using ESExample;
public class Client
{
public static void Main(string[] args)
{
MyTxCfgClass tcc = new MyTxCfgClass();
... // use object as desired
}
}
|
年级
|
一年级
|
二年级
|
三年级
|
四年级
|
五年级
|
六年级
|
人数
|
251
|
233
|
260
|
248
|
228
|
265
|
using System;
namespace Sample
{
public class DemoClass
{
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
}
|
public void GenerateCode()
{
//生成一个可编译的单元,这是最根部的东西
CodeCompileUnit compunit = new CodeCompileUnit();
//定义一个名为Sample的命名空间
CodeNamespace sample = new CodeNamespace("Sample");
compunit.Namespaces.Add(sample);
sample.Imports.Add(new CodeNamespaceImport("System"));//导入System命名空间
//定义一个名为DemoClass的类
CodeTypeDeclaration MyClass = new CodeTypeDeclaration("DemoClass");
sample.Types.Add(MyClass);
//定义程序入口点,就是Main()
CodeEntryPointMethod Start = new CodeEntryPointMethod();
MyClass.Members.Add(Start);
//下面产生调用方法的语句,//这句会产生如下的C#代码System.Console.WriteLine("Hello World!");
CodeMethodInvokeExpression cs = new CodeMethodInvokeExpression
(new CodeTypeReferenceExpression("System.Console"),
"WriteLine", new CodePrimitiveExpression("Hello World!"));
Start.Statements.Add(cs);
//根据CodeDOM产生程序代码,代码文件就是DemoClass.cs,这里生成C#代码
CSharpCodeProvider cprovider = new CSharpCodeProvider();
ICodeGenerator gen = cprovider.CreateGenerator();
StreamWriter sw = new StreamWriter("DemoClass.cs", false);
gen.GenerateCodeFromCompileUnit(compunit, sw, new CodeGeneratorOptions());
sw.Close();
//编译源代码
ICodeCompiler compiler = cprovider.CreateCompiler();
//编译参数
CompilerParameters cp = new CompilerParameters(new string[] { "System.dll" },
filepath.Substring(0, filepath.LastIndexOf(".") + 1) + "exe", false);
cp.GenerateExecutable = true;//生成EXE,不是DLL
CompilerResults cr = compiler.CompileAssemblyFromDom(cp, compunit);
}
|
public abstract class ServiceLocator
{
public static object FindService(string serviceName,Type clientInterface)
}
|
public interface IServiceLocator
{
object FindService(string serviceName,Type clientInterface);
}
|
<configSections>
<section name="Websharp.Enterprise"
type="Websharp.Enterprise.EnterpriseConfigHandler,Websharp" />
</configSections>
|
<Websharp.Enterprise>
<ServiceTypes>
<ServiceType name="LocalAssembly"
locator="Websharp.Enterprise.LocalAssemblyLocator,Websharp" />
<ServiceType name="WebService"
locator="Websharp.Enterprise.WebServiceLocator,Websharp" />
<ServiceType name="DotNetRemoting"
locator="Websharp.Enterprise.DotNetRemotingLocator,Websharp" />
</ServiceTypes>
</Websharp.Enterprise>
|
<Websharp.Enterprise>
<ServiceTypes>
<ServiceType name="LocalAssembly"
locator="Websharp.Enterprise.LocalAssemblyLocator,Websharp" />
<ServiceType name="WebService"
locator="Websharp.Enterprise.WebServiceLocator,Websharp" />
<ServiceType name="DotNetRemoting"
locator="Websharp.Enterprise.DotNetRemotingLocator,Websharp" />
</ServiceTypes>
<Services>
<Service name="HelloWorld" service-type="LocalAssembly" deploy-model="Singleton"
type="EnterpriseClient.HelloWorld,EnterpriseClient" />
<Service name="HelloWorldWebService" service-type="WebService"
deploy-model="Singleton"
url="http://localhost/webservicetest/hello.asmx"
namespace="http://www.websharp.org/webservices/" />
</Services>
</Websharp.Enterprise>
|
public class HelloWorld
{
public string GetHello(string hello)
{
return hello;
}
}
|
public interface IHelloWorld
{
string GetHello(string hello);
[ServiceMethodName("GetHello")]
string GetHello2(string hello);
}
|
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Websharp.Enterprise"
type="Websharp.Enterprise.EnterpriseConfigHandler,Websharp" />
</configSections>
<Websharp.Enterprise>
<ServiceTypes>
<ServiceType name="LocalAssembly"
locator="Websharp.Enterprise.LocalAssemblyLocator,Websharp" />
<ServiceType name="WebService"
locator="Websharp.Enterprise.WebServiceLocator,Websharp" />
</ServiceTypes>
<Services>
<Service name="HelloWorld" service-type="LocalAssembly"
deploy-model="SSingleton"
type="EnterpriseClient.HelloWorld,EnterpriseClient" />
</Services>
</Websharp.Enterprise>
</configuration>
|
public static void Main(string[] args)
{
IHelloWorld hello= ServiceLocator.FindService("HelloWorld",typeof(IHelloWorld)) as IHelloWorld;
Console.WriteLine(hello.GetHello("Hello World"));
Console.WriteLine(hello.GetHello2("Hello again"));
Console.ReadLine();
}
|
[WebService(Namespace="http://www.websharp.org/webservices/")]
public class Hello : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
|
public interface IHello
{
string HelloWorld();
}
|
<Service name="HelloWorldWebService" service-type="WebService" deploy-model="SSingleton"
url="http://localhost/webservicetest/hello.asmx"
namespace="http://www.websharp.org/webservices/" />
|
public static void Main(string[] args)
{
IHello hello1= ServiceLocator.FindService
("HelloWorldWebService",typeof(IHello)) as IHello;
Console.WriteLine(hello1.HelloWorld());
Console.ReadLine();
}
|
子系统
|
说明
|
连接状态管理
|
“连 接状态管理”检测应用程序是处于联机状态还是脱机状态。有两种方法可以判断连接状态:手动判断或通过自动过程判断。如果选择自动判断,则连接状态表示为包 括网络层和应用程序连接的多层连接性(请注意,应用程序连接检测并不是在该应用程序块中实现的)。应用程序的行为会根据连接状态而变化。
|
服务代理管理
|
“服务代理管理”与 Offline Application Block 的这些元素(“消息数据管理”、“参考数据管理”)以及服务器进行交互。它会进行协调,以便将任务完成通知返回到应用程序。
|
参考数据管理
|
“参 考数据管理”与“服务代理管理”和“消息数据管理”配合工作,以下载存储在本地计算机上的参考数据。在大多数情况下,参考数据是用于完成工作流的只读数 据。“参考数据管理”可使参考数据与服务器上的数据保持一致。它将消息存储在“队列”中以下载参考数据。然后,“执行程序”将使用消息服务请求与服务连 接,以下载参考数据。
|
消息数据管理
|
消息数据是在工作流过程中创建的数据。当应用程序处于脱机状态时,该数据将存储在一个本地队列中。当应用程序联机后,“执行程序”会从“队列”中删除消息,发出与服务器同步数据的“服务请求”,然后数据就会与服务器进行同步。
|
名称。名称无疑应该表明用户的意图或用例的用途,如“研究班招生”。
标识符 [可选]。唯一标识符,如 "UC1701",在项目的其他元素(如类模型)中可用它来引用这个用例。
说明。概述用例的几句话。
参与者 [可选]。与此用例相关的参与者列表。尽管这则信息包含在用例本身中,但在没有用例图时,它有助于增加对该用例的理解。
状态 [可选]。指示用例的状态,通常为以下几种之一:进行中、等待审查、通过审查或未通过审查。
频率。参与者访问此用例的频率。这是一个自由式问题,如用户每次录访问一次或每月一次。
前置条件。一个条件列表,如果其中包含条件,则这些条件必须在访问用例之前得到满足。
后置条件。一个条件列表,如果其中包含条件,则这些条件将在用例成功完成以后得到满足。
被 扩展的用例 [可选]。此用例所扩展的用例(如果存在)。扩展关联是一种广义关系,其中扩展用例接续基用例的行为。这是通过扩展用例向基用例的操作序列中插入附加的操 作序列来实现的。这总是使用带有 <<extend>> 的用例关联来建模的。
被包含的用例 [可选]。此用例所包含用例的列表。包含关联是一种广义关系,它表明对处于另一个用例之中的用例所描述的行为的包含关系。这总是使用带有 <<include>> 的用例关联来建模的。也称为使用或具有 (has-a) 关系。
假设 [可选]。对编写此用例时所创建的域的任何重要假设。您应该在一定的时候检验这些假设,或者将它们变为决策的一部分,或者将它们添加到操作的基本流程或可选流程中。
基本操作流程。参与者在用例中所遵循的主逻辑路径。因为它描述了当各项工作都正常进行时用例的工作方式,所以通常称其为适当路径 (happy path) 或主路径 (main path) 。
可选操作流程。用例中很少使用的逻辑路径,那些在变更工作方式、出现异常或发生错误的情况下所遵循的路径。
修改历史记录 [可选]。关于用例的修改时间、修改原因和修改人的详细信息。
问题 [可选]。如果存在,则为与此用例的开发相关的问题或操作项目的列表。
决策。关键决策的列表,这些决策通常由您的 SME 作出,并属于用例的内容。将这些决策记录下来对于维护团体记忆库 (group memory) 是相当重要的。
|
构建面向对象的应用软件系统框架相关推荐
- 构建面向对象的应用软件系统框架【转】
构建面向对象的应用软件系统框架 孙亚民 目录 第一部分 综述 4 第1章 本书会讨论什么内容 5 第2章 系统的分层结构 8 2.1.简述 8 2.2.设计的原则和评判标准 9 ...
- 达芬奇 - 构建数据查询API的框架
达芬奇 - 基于"Serverless"的数据查询API框架 此文背景 我们要解决什么样的问题? 系统要求 系统设计 访问控制列表及其使用 过滤器以及其语法 Serverless ...
- C语言实现OOP——轻量级的面向对象 C 语言编程框架 LW_OOPC 介绍(二)
轻量级的面向对象 C 语言编程框架 LW_OOPC 介绍 下面,再举一个稍微复杂的例子,它的覆盖面是足够全面的,足以一瞥面向对象编程的3个要素:数据抽象.继承和多态.通过这个例子,我们期望展现出LW_ ...
- python PyQt5 QMainWindow类(Qt主窗口框架,主窗口提供了用于构建应用程序用户界面的框架)
https://doc.qt.io/qtforpython/PySide2/QtWidgets/QMainWindow.html?highlight=qmainwindow#PySide2.QtWid ...
- Docker监控:基于阿里云容器服务构建自己的Docker监控框架
微服务架构通过将一个复杂系统分解成一系列独立开发.部署和运维的服务,提升了整个系统的敏捷性,可以灵活的响应业务和规模的变化.而Docker技术则将服务的部署和环境完全解耦,利用Docker的可移植性和 ...
- buildroot:Linux平台构建嵌入式Linux系统的框架
buildroot是Linux平台上一个构建嵌入式Linux系统的框架.整个Buildroot是由Makefile脚本和Kconfig配置文件构成的.你可以和编译Linux内核一样,通过buildro ...
- halcon机器视觉软件系统框架源码visi onpro
机器视觉软件系统框架源码visi onpro
- 21年1.9c#halcon机器视觉软件系统框架源码visi onpro
21年1.9c#halcon机器视觉软件系统框架源码visi onpro
- 【基础导航软件架构】无人驾驶车/机器人的基本导航软件系统框架(自己总结)
系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 TODO:写完再整理 文章目录 系列文章目录 前言 一.感知模块的理解 1.环境感知 传感器sensor 目标检测det ...
最新文章
- 分类器评价与在R中的实现:ROC图与AUC
- 成功解决xgboost.core.XGBoostError: b'[20:58:45] C:\\Users\\Administrator\\Desktop\\xgboost\\dmlc-core\\s
- 2021年度邵逸夫数学科学奖
- 不同格式的json解析
- poj3252Round Numbers
- 基于Eureka的服务治理
- jquery中的class函数addClass,removeClass,toggle,hasClass
- vue父子组件间传值(props)
- Metro程序部署到Surface调试
- ASP.NET中EnableViewState
- Pr导入ass字幕的解决方案——将ass字幕转为mov视频格式
- linux安装vim
- 单片机需要数电模电基础吗?单片机要多少模电数电知识 ?
- 出大问题!苹果硅或许意味着Wintel时代的终结……
- kettle连接access问题总结
- ImportError:cannot import name ‘save_state_warning‘和解决torch1.7.1报分布式错误No rendezvous handler for env:
- 如何查看win10电脑系统盘是哪个盘?
- python棋盘格_python实现张正友棋盘格标定法
- Python基础(十八):学员管理系统应用
- 【一步步学OpenGL 19】 -《镜面反射光》
热门文章
- C++ lower_bound 与 upper_bound 函数
- 分区表理论解析(下):SQL Server 2k52k8系列(二)
- Excel 导入数据库中java.lang.StringIndexOutOfBoundsException: String index out of range: -50提示解决原因...
- 工厂方法与抽象工厂模式的区别
- java volatile详解,互联网 面试官 如何面试
- python经典书籍推荐:Python核心编程
- postgresql 增量备份
- (转)Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例
- IntelliJ IDEA 2017.3-2018.1 全系列汉化包
- (转)淘淘商城系列——实现图片上传功能