Модераторы: Partizan, gambit

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Application Architecture for .NET 
:(
    Опции темы
Medved
Дата 18.1.2006, 07:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Application Architecture for .NET

1. Application Architecture for .NET: Designing Applications and Services
2. Smart Client Definition
3. Enterprise Library for .NET Framework 2.0 – December 2005
4. Composite User Interface (UI) Application Block



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 08:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Application Architecture for .NET:
Designing Applications and Services

http://msdn.microsoft.com/practices/compca.../apparchch1.asp


The following diagram shows these two layers in the architecture of a .NET-based distributed application.
user posted image

Figure 1.1: Component layers found in distributed applications and services built with .NET

Services and Service Integration

Components and Tiers in Applications and Services

user posted image

Figure 1.2. A service-based solution

Figure 1.3 shows a simplified view of one application and its layers.
user posted image

Figure 1.3. Components separated into layers according to their roles

A Sample Scenario

The proposed solution for this scenario is a component-based design that consists of a number of components, as shown in Figure 1.4.
user posted image
Figure 1.4. The retail application as a set of components and related services

user posted image

Figure 2.1. Component types in the retail sample scenario

The component types identified in the sample scenario design are: Component Types


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 08:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Designing the Components of an Application or Service
http://msdn.microsoft.com/practices/compca.../apparchch2.asp

user posted image

General Design Recommendations for Applications and Services


Designing Presentation Layers
http://msdn.microsoft.com/practices/compca...rchch2_section3

Figure 2.2 shows the component types in the presentation layer.
user posted image

Figure 2.2. Presentation layer

Designing User Interface Components
Figure 2.3 shows the design of a user interface.
user posted image

Figure 2.3. User interface design

Designing User Process Components
Figure 2.4 shows how the user interface and user process can be abstracted from one another.
user posted image

Figure 2.4. User interfaces and user process components

User Process Component Interface
The interface of your user process components can expose the following kinds of functionality, as shown in Figure 2.5.
user posted image

Figure 2.5. User process component design


Designing Business Layers
http://msdn.microsoft.com/practices/compca...rchch2_section4

Figure 2.6 shows the business layers of an application.
user posted image

Figure 2.6. Business component layers

Business Components and Workflows

Business components are called by the following consumers:
  • Service interfaces
  • User process components
  • Business workflows
  • Other business components
Figure 2.7 shows a typical business component interacting with data access logic components, service interfaces, service agents, and other business components.
user posted image

Figure 2.7. Business components

Figure 2.8 shows how an orchestrated business process interacts with service interfaces, service agents, and business components.
user posted image

Figure 2.8. An orchestrated business process

Figure 2.10 shows a business facade used in this manner.
user posted image

Figure 2.10. Using a business facade with service interfaces


Designing Data Layers
http://msdn.microsoft.com/practices/compca...rchch2_section5

Almost all applications and services need to store and access some kind of data. For example, the retail application discussed in this guide needs to store product, customer, and order data.
When working with data, you need to determine:
  • The data store you are using.
  • The design of the components used to access the data store.
  • The format of the data passed between components, and the programming model it requires.
Figure 2.11 shows how the logical data layer of an application consists of one or more data stores, and depicts a layer of data access logic components that are used to retrieve and manipulate the data in those data stores.
user posted image

Figure 2.11. Data components

Data Stores
Common types of stores include:
  • Relational databases
  • Messaging databases
  • File system
Data Access Logic Components
Figure 2.12 shows the use of data access logic components to access data.
user posted image

Figure 2.12. Data access logic components


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 09:11 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Security, Operational Management, and Communications Policies
http://msdn.microsoft.com/practices/compca.../apparchch3.asp

Organizational policies define the rules that govern how an application is secured, how it is managed, and how the different components of the application communicate with one another and with external services. The policies affect the design of each layer of the application or service, as shown in Figure 3.1.
user posted image

Figure 3.1. The effect of organizational policies on the application design


Designing the Security Policy
http://msdn.microsoft.com/practices/compca...rchch3_section1

The security policy is concerned with authentication, authorization, secure communication, auditing, and profile management, as shown in Figure 3.2.
user posted image

Figure 3.2. Aspects of the security policy

Security:

Authentication
  • Authentication in the Presentation Layer
  • Authentication in Business Components
  • Authentication in Data Access Components
  • Authentication in Business Entity Components
Authorization
  • User permissions and rights
  • Code access security
You need to incorporate the results in the following matrix into your access control design:
user posted image
  • Authorization in User Interface Components
  • Authorization in User Process Components
  • Authorization in Business Components
  • Authorization in Service Agents and Service Interfaces
  • Authorization in Data Access Components
  • Authorization in Business Entity Components
Secure Communication
  • Secure Communication in User Interface Components
  • Secure Communication in Service Agents and Service Interfaces
  • Secure Communication in Data Access Components
Profile Management

Auditing
  • Auditing in User Interface and User Process Components
  • Auditing in Business Process Components
  • Auditing in Data Access Components


Designing the Operational Management Policy
http://msdn.microsoft.com/practices/compca...rchch3_section2

The operational management policy is concerned with the ongoing, day-to-day running of the application, and covers issues such as exception management, monitoring, business monitoring, metadata, configuration, and service location, as shown in Figure 3.3.
user posted image
Figure 3.3. Aspects of the operational management policy

Operational Management:
  • Exception Management
  • Monitoring
  • Configuration
  • Metadata
  • Service Location


Designing the Communications Policy
http://msdn.microsoft.com/practices/compca...rchch3_section3

The communications policy defines how the components in your application will communicate with each other. The communications policy covers such issues such communication synchronicity, format, and protocol, as shown in Figure 3.4.
user posted image

Figure 3.4. Aspects of the communications policy

Communication:
  • Synchronicity
  • Format, Schema
  • Protocol
Separating Inter- and Intra-Application Communication

user posted image

Figure 3.5. Implementing communication between the presentation and business tiers using the message bus

user posted image

Figure 3.6. Using the message bus for integration purposes only


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 09:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Physical Deployment and Operational Requirements
http://msdn.microsoft.com/practices/compca.../apparchch4.asp


Deploying Application Components
http://msdn.microsoft.com/practices/compca...rchch4_section1

Physical Deployment Environments:
  • Web Farms. A Web farm is a load-balanced array of Web servers.
  • Application Farms. Applications farms are conceptually similar to Web farms, but they are used to load balance requests for business components across multiple application servers.
  • Database Clusters. Database clusters are used to provide high availability of a database server.
  • EAI Clusters. Microsoft BizTalk® Server relies on four SQL Server databases to store its messaging and orchestration data. These databases can benefit from Windows Clustering for high availability.
  • Rich Clients. In most enterprises, using rich clients implies:
    • The ability to authenticate users through Microsoft Active Directory® directory service (thus having access to a Windows Identity and Principal).
    • Access to richer state management options, including maintaining session-related state in memory. (In high scalability and availability scenarios, it is not a good idea to keep in-memory state on the server.)
    • The ability to work offline.
    • Rich clients are also better targets for the user interface of complex operations.
  • Thin Clients. Thin clients usually manage HTML or even simpler UI models, so they are not typically considered a deployment target for your components. You can include .NET controls in HTML pages, but in that case you are simply using the browser as a deployment vehicle, and should consider your user interface to be rich.


Common Deployment Patterns
http://msdn.microsoft.com/practices/compca...loymentpatterns

Web-Based User Interface Scenarios
The two deployment scenarios outlined in the following discussion are common variations found when working with Web-based user interfaces.

Web Farm with Local Business Logic
user posted image

Figure 4.2. Web farm with local business logic

Web Farm with Remote Business Logic
Figure 4.3 illustrates this deployment pattern.
user posted image

Figure 4.3. Web farm with remote business logic


Rich Client User Interface Scenarios
The following two scenarios assume a rich client.

Rich Client with Remote Components
user posted image

Figure 4.4. Rich client with remote components

Rich Client with Web Service Access
Figure 4.5 illustrates the rich client with Web access pattern.
user posted image

Figure 4.5. Rich client with Web service access


Service Integration Scenarios

Service Agents and Interfaces Deployed with Business Components
user posted image

Figure 4.6. A service with local business logic

Business Components Separated from Service Agents and Interfaces
user posted image

Figure 4.7. Isolating service agents in a separate farm

EAI Clusters and Application Components
user posted image

Figure 4.8. Separating EAI components from business components

Figure 4.8 shows user interface components on a Web farm (1) calling business components on an application farm (2), which in turn work with the application data source (3). The EAI cluster (4) has its own business components needed to perform the steps in its business workflows, and accesses other services (in this example, only internal services) through a firewall (5).


Operational Requirements

Appendices


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 10:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Smart Client Definition
http://msdn.microsoft.com/smartclient/unde...on/default.aspx

Smart client (n) Definition: Smart clients are easily deployed and managed client applications that provide an adaptive, responsive and rich interactive experience by leveraging local resources and intelligently connecting to distributed data sources.

user posted image

A smart client application combines the following ingredients to provide a responsive, rich, and compelling experience to its end users.


Что такое Smart Client и почему будущее за ним?



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 10:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154




Модератор: Сообщение скрыто.



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 20:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Enterprise Library for .NET Framework 2.0 – December 2005
http://msdn.microsoft.com/library/?url=/li...tml/EntLib2.asp
http://forum.vingrad.ru/index.php?showtopic=76374

The application blocks that comprise the Enterprise Library are the following:
  • Caching Application Block. This application block allows developers to incorporate a local cache in their applications.
  • Data Access Application Block. This application block allows developers to incorporate standard database functionality in their applications.
  • Exception Handling Application Block. This application block allows developers and policy makers to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. This application block allows developers to incorporate standard logging functionality in their applications.
  • Security Application Block. This application block allows developers to incorporate authorization and security caching functionality in their applications.
The Enterprise Library Core

Figure 1 illustrates the interdependencies of the application blocks that make up the Enterprise Library.
user posted image

Figure 1: Interdependence of application blocks

Object Builder
The ObjectBuilder is a new subsystem that is shared between Enterprise Library and the Composite User Interface (UI) Application Block. Enterprise Library uses the ObjectBuilder subsystem for tasks such as injecting configuration into block classes and connecting instrumentation classes to application blocks.


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 21:11 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Caching Application Block
  • Selecting and configuring a cache store
  • Adding an item to the cache and setting its expiration date
  • Removing an item from the cache
  • Retrieving an item from the cache
  • Flushing the cache
The following illustration shows the interrelationships between the key classes in the Caching Application Block.
user posted image

Figure 2: Design of the Caching Application Block

QuickStarts

Walkthrough: Adding Items to the Cache
Код

private CacheManager primitivesCache;

Код

this.primitivesCache = CacheFactory.GetCacheManager();

Код

string id="ProductOneId";
string name = "ProductOneName";
int price = 50;

Product product = new Product(id, name, price);

Код

primitivesCache.Add(product.ProductID, product, CacheItemPriority.Normal(), null,
                     new SlidingTime(TimeSpan.FromMinutes(5)));


Walkthrough: Removing Items From the Cache
Код

// Prompt the user for the key of the item to be removed
if (this.selectItemForm.ShowDialog() == DialogResult.OK)
{
  // Request that the item be removed from the cache. 
  this.primitivesCache.Remove(selectItemForm.ItemKey);
}


Walkthrough: Retrieving Items From the Cache
Код

// Prompt the user for the key of the item to be read
if (this.selectItemForm.ShowDialog() == DialogResult.OK)
{
  // Read the item from the cache. If the item is not found in the cache, the
  // return value will be null.
  Product product = (Product) this.primitivesCache.GetData(selectItemForm.ItemKey);
}


Walkthrough: Flushing the Cache
Код

this.primitivesCache.Flush();


Walkthrough: Loading the Cache

The following diagram illustrates how the QuickStart retrieves data from the cache.
user posted image

Figure 3: Solution elements for loading the cache

Код

private CacheManager cache;

Код

cache = CacheFactory.GetCacheManager("Loading Scenario Cache Manager");

Loading the Cache Proactively
Код

List<Product> list = this.dataProvider.GetProductList();
for (int i = 0; i < list.Count; i++)
{
  Product product = list[i];
  cache.Add(product.ProductID, product);
}

Loading the Cache Reactively
Код

Product product = (Product)cache.GetData(productID);
// Does our cache already have the requested object?
if (product == null)
{
  // Requested object is not cached; therefore, retrieve it from
  // the data provider and cache it for more requests.
  product = this.dataProvider.GetProductByID(productID);
  if (product != null)
  {
    cache.Add(productID, product);
  }
}
return product;



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 21:43 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Data Access Application Block
  • Using a DataReader to retrieve multiple rows of data
  • Using a DataSet to retrieve multiple rows of data
  • Executing a command and retrieving the output parameters
  • Executing a command and retrieving a single-value item
  • Performing multiple operations within a transaction
  • Retrieving XML data from a SQL Server
  • Updating a database with data contained in a DataSet object
The following illustration shows the interrelationship between the key classes in the Data Access Application Block.
user posted image

Figure 4: Design of the Data Access Application Block

Example
Код

Database db = DatabaseFactory.CreateDatabase();

DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory"); 
db.AddInParameter(dbCommnad, "CategoryID", DbType.Int32, Category);

DataSet productDataSet = db.ExecuteDataSet(dbCommand);


QuickStarts

Walkthrough: Using a DataSet to Retrieve Multiple Rows
Код

CREATE Procedure GetProductsByCategory ( @CategoryID int ) 
AS 
  SELECT ProductID, ProductName, CategoryID, UnitPrice, LastUpdate 
  FROM Products 
  WHERE CategoryID = @CategoryID

Код

public DataSet GetProductsInCategory(int Category)
{
}

Код

Database db = DatabaseFactory.CreateDatabase();

string sqlCommand = "GetProductsByCategory";

DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); 
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category);

// DataSet that will hold the returned results
DataSet productDataSet = null;
productDataSet = db.ExecuteDataSet(dbCommand);

resultsDataGrid.SetDataBinding(productDataSet, "Table");


Walkthrough: Using a DataReader to Retrieve Multiple Rows
Код

db = DatabaseFactory.CreateDatabase();

string sqlCommand = "Select CustomerID, Name, Address, City, Country, PostalCode " +
"From Customers";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);

Код

using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
  // Processing code 
}

Код

StringBuilder readerData = new StringBuilder();

while (dataReader.Read())
{
  // Get the value of the 'Name' column in the DataReader
  readerData.Append(dataReader["Name"]);
  readerData.Append(Environment.NewLine);
}

Код

// Close the reader, which will cause the connection to be closed as well
if (dataReader != null)
     dataReader.Close();


Walkthrough: Retrieving Multiple Rows as XML
Код

SqlDatabase dbSQL = DatabaseFactory.CreateDatabase() as SqlDatabase;

string sqlCommand = "Select ProductID, ProductName, CategoryID, UnitPrice, LastUpdate " +
    "From Products FOR XML AUTO";
DbCommand dbCommand = dbSQL.GetSqlStringCommand(sqlCommand);

XmlReader productsReader = null;
StringBuilder productList = new StringBuilder();

try
{
  productsReader = dbSQL.ExecuteXmlReader(dbCommand);

  while (!productsReader.EOF)
  {
    if (productsReader.IsStartElement()) 
    {
      productList.Append(productsReader.ReadOuterXml());
      productList.Append(Environment.NewLine);
    }
  }   
}
finally
{
  // Close the Reader.
  if (productsReader != null)
  {
    productsReader.Close();
  }
 
  // Explicitly close the connection. The connection is not closed
  // when the XmlReader is closed.
  if (dbComman.Connection != null)
  {
    dbCommand.Connection.Close();
  }       
}


Walkthrough: Executing a Command and Accessing Output Parameters
Код

CREATE PROCEDURE GetProductDetails
@ProductID int,
@ProductName nvarchar(40) OUTPUT,
@UnitPrice money OUTPUT,
@QtyPerUnit nvarchar(20) OUTPUT
AS
SELECT @ProductName = ProductName, 
      @UnitPrice = UnitPrice,
      @QtyPerUnit = QuantityPerUnit
FROM Products 
WHERE ProductID = @ProductID

Код

Database db = DatabaseFactory.CreateDatabase();

string sqlCommand = "GetProductsDetails";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); 
db.AddInParameter(dbCommand, "ProductID", DbType.Int32, productID);
// Output parameters specify the size of the return data
db.AddOutParameter(dbCommand, "ProductName", DbType.String, 50);
db.AddOutParameter(dbCommand, "UnitPrice", DbType.Currency, 8);

db.ExecuteNonQuery(dbCommand);

string results = string.Format(CultureInfo.CurrentCulture, "{0}, {1}, {2:C} ",
  db.GetParameterValue(dbCommand, "@ProductID"),
  db.GetParameterValue(dbCommand, "@ProductName"),
  db.GetParameterValue(dbCommand, "@UnitPrice"));


Walkthrough: Executing a Command and Accessing a Single-Item Result
Код

CREATE PROCEDURE GetProductName
@ProductID int
AS
SELECT ProductName
FROM Products
WHERE ProductID = @ProductID

Код

Database db = DatabaseFactory.CreateDatabase();

string sqlCommand = "GetProductName";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, productID);

string productName = (string)db.ExecuteScalar(dbCommand);

Код

SELECT CAST(@@Identity AS INTEGER)


Walkthrough: Executing a Command and Accessing a Single-Item Result
Код

CREATE PROCEDURE credit 
@AccountNo CHAR(20),
@Amount SMALLMONEY
AS
INSERT Credits
VALUES
(@AccountNo, @Amount)
GO

CREATE PROCEDURE debit 
     @AccountNo CHAR(20),
     @Amount SMALLMONEY
AS
INSERT Debits
VALUES
(@AccountNo, @Amount)
GO

Код

Database db = DatabaseFactory.CreateDatabase();

DbCommand creditCommand = db.GetStoredProcCommand("CreditAccount");

db.AddInParameter(creditCommand, "AccountID", DbType.Int32, sourceAccount);
db.AddInParameter(creditCommand, "Amount", DbType.Int32, transactionAmount);

DbCommand debitCommand = db.GetStoredProcCommand("DebitAccount");

db.AddInParameter(debitCommand, "AccountID", DbType.Int32, destinationAccount);
db.AddInParameter(debitCommand, "Amount", DbType.Int32, transactionAmount);

Код

using (DbConnection connection = db.CreateConnection())
{
  connection.Open();
  DbTransaction transaction = connection.BeginTransaction();

  try
  {
    // Credit the first account
    db.ExecuteNonQuery(creditCommand, transaction);
    // Debit the second account
    db.ExecuteNonQuery(debitCommand, transaction);

    // Commit the transaction
    transaction.Commit();
                    
    result = true;
  }
  catch
  {
    // Rollback transaction 
    transaction.Rollback();
  }
  connection.Close();
                
  return result;
}


Walkthrough: Using a DataSet to Update a Database
Код

CREATE PROCEDURE AddProduct
(
    @ProductName nvarchar(50),
    @CategoryID int,
    @UnitPrice money
)
AS

INSERT INTO Products (ProductName, CategoryID, UnitPrice)
VALUES (@ProductName, @CategoryID, @UnitPrice)

SELECT ProductID, ProductName, CategoryID, UnitPrice
FROM Products
WHERE ProductID = SCOPE_IDENTITY()
GO

CREATE PROCEDURE DeleteProduct 
(
@ProductID int
)
AS

DELETE Products 
WHERE ProductID = @ProductID
GO

CREATE PROCEDURE UpdateProduct 
(
    @ProductID int,
    @ProductName nvarchar(50),
    @LastUpdate datetime
)
AS

UPDATE Products 
SET ProductName = @ProductName
WHERE ProductID = @ProductID AND LastUpdate = @LastUpdate
 
IF @@ROWCOUNT > 0
  -- This statement is used to update the DataSet 
  -- if changes are done on the updated record (identities, timestamps or triggers )
  SELECT ProductID, ProductName, CategoryID, UnitPrice
  FROM Products
  WHERE ProductID = @ProductID
GO

Код

Database db = DatabaseFactory.CreateDatabase();

DataSet productsDataSet = new DataSet();
string sqlCommand = "Select ProductID, ProductName, CategoryID, UnitPrice, LastUpdate " + 
  "From Products";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
string productsTable = "Products";
// Retrieve the initial data
db.LoadDataSet(dbCommand, productsDataSet, productsTable);

Код

// Get the table that will be modified
DataTable table = productsDataSet.Tables[productsTable];

// Add a new product to existing DataSet
DataRow addedRow = table.Rows.Add(new object[] {DBNull.Value, "New product", 11, 25});
    
// Modify an existing product
table.Rows[0]["ProductName"] = "Modified product";

Код

DbCommand insertCommand = db.GetStoredProcCommand("AddProduct");
db.AddInParameter(insertCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(insertCommand, "CategoryID", DbType.Int32, "CategoryID", DataRowVersion.Current);
db.AddInParameter(insertCommand, "UnitPrice", DbType.Currency, "UnitPrice", DataRowVersion.Current);

DbCommand deleteCommand = db.GetStoredProcCommand("DeleteProduct");
db.AddInParameter(deleteCommand, "ProductID", DbType.Int32, "ProductID", DataRowVersion.Current);

DbCommand updateCommand = db.GetStoredProcCommand("UpdateProduct");
db.AddInParameter(updateCommand, "ProductID", DbType.Int32, "ProductID", DataRowVersion.Current);
db.AddInParameter(updateCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(updateCommand, "LastUpdate", DbType.DateTime, "LastUpdate", DataRowVersion.Current);

Код

int rowsAffected = db.UpdateDataSet(productsDataSet, "Products", insertCommand, updateCommand,
  deleteCommand, Microsoft.Practices.EnterpriseLibrary.DataAccess.UpdateBehavior.Standard);



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 22:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Exception Handling Application Block
  • Logging an Exception
  • Wrapping an Exception
  • Replacing an Exception
  • Propagating an Exception
  • Displaying User-Friendly Messages
  • Notifying the User
  • Aiding Support Staff
Figure 8 shows the interrelationships between the key classes in the Exception Handling Application Block.
user posted image

Figure 8: Design of the Exception Handling Application Block

When to Use the Exception Handling Application Block
Figure 5 illustrates examples of cross-layer and single-application component exception handling.
user posted image

Figure 5: Examples of exception handling policies

Without the Exception Handling Application Block, typical exception handling code for a data access component might look like the following example.
Код

DataSet customersDataSet;
try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  string formattedInfo = FormatException(ex);
  Logging.Log(formattedInfo);
  throw new DataAccessException("Database access failure for query     GetAllCustomers",e);
}

Code similar to this would be repeated in all the routines that perform different data access queries. To change the behavior of the exception handling code, you must update each routine that contained this code.
On the other hand, with the Exception Handling Application Block, the same application would have the following code.
Код

DataSet customersDataSet;
try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Policy");
  if (rethrow)
    throw;
}


Exception Handling Process and the Exception Handling Application Block
Figure 6 illustrates the basic steps that your application should perform to handle an exception.
user posted image

Figure 6: Exception handling process

Exception Propagation
There are three main ways to propagate exceptions:
Let the exception propagate automatically. With this approach, you do nothing and deliberately ignore the exception. This causes the control to move immediately from the current code block up the call stack until a catch block with a filter that matches the exception type is found.
Catch and rethrow the exception. With this approach, you catch and react to the exception, and clean up or perform any other required processing within the scope of the current method. If you cannot recover from the exception, you rethrow the same exception to your caller.
Catch, wrap, and throw the wrapped exception. As an exception propagates up the call stack, the exception type becomes less relevant. When an exception is wrapped, a more relevant exception can be returned to the caller. This is illustrated in Figure 7.
user posted image

Figure 7: Propagating exceptions

QuickStarts

Exception Handling Basic QuickStart

Walkthrough: Propagating the Original Exception
This walkthrough demonstrates the steps to enable the original exception to propagate. The process is shown in Figure 9.
user posted image

Figure 9: Propagating the original exception

Walkthrough: Wrapping One Exception in Another
user posted image

Figure 17: Wrapping one exception in another

Walkthrough: Replacing One Exception with Another
This walkthrough demonstrates the steps to replace one exception with another before propagating the exception. The process is shown in Figure 10.
user posted image

Figure 10: Replacing one exception with another

Walkthrough: Processing and Resuming Execution
This walkthrough demonstrates the steps to run a series of exception handlers before resuming execution in the application. This process is shown in the Figure 11.
user posted image

Figure 11: Processing and resuming execution

Exception Handling with Logging QuickStart

Walkthrough: Logging an Exception
This walkthrough demonstrates the steps to log exception information. This process is shown in Figure 12.
user posted image

Figure 12: Logging an exception

Walkthrough: Notifying the User
This walkthrough demonstrates the steps to send a friendly exception message to the user and still allow support staff to access information regarding the originating exception. This process is shown in Figure 13.
user posted image

Figure 13: Notifying the user


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 23:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Logging Application Block
  • Populating and raising events from code
  • Populating a log message with additional context information
  • Tracing activities and propagating context information
  • Checking filter status before constructing log messages.
  • Configuring options for trace listeners
  • Directing different event types to different trace listeners
  • Configuring log filters
  • Configure logging to be performed from a central location
  • Creating a custom trace listener
Figure 14 illustrates the design of the Logging Application Block.
user posted image

Figure 14: Design of the Logging Application Block

QuickStarts

Walkthrough: Populating and Raising an Event from Code
Код

LogEntry log = new LogEntry();
log.EventId = 300;
log.Message = "Sample message";
logEntry.Categories.Add("UI Events");
logEntry.Severity = TraceEventType.Information;
log.Priority = 5;

Код

Logger.Write(log);


Walkthrough: Populating a Log Message with Additional Context Information
Код

Hashtable dictionary = new Hashtable();

ManagedSecurityContextInformationProvider informationHelper = 
  new ManagedSecurityContextInformationProvider();    
  
informationHelper.PopulateDictionary(dictionary);

int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height;
string resolution = String.Format("{0}x{1}", width, height);
  
dictionary.Add("Screen resolution", resolution);  

Logger.Write("Log entry with extra information", dictionary);


Walkthrough: Tracing Activities and Propagating Context Information
This walkthrough demonstrates the steps to trace activities and propagate context information from code. The sequence of method calls with tracing information is shown in Figure 15.
user posted image

Код

using (new Tracer("UI Events"))
{
  DoDataAccess();  
}


Код

private void DoDataAccess()
{
  using (new Tracer("Data Access Events"))
  {
    DoTroubleShooting();
  }
}

Код

private void DoTroubleShooting()
{
  string logMessage = "Simulated troubleshooting message for Logging QuickStart. " +
    "Current activity=\"" + Trace.CorrelationManager.ActivityId + "\"";

  LogEntry logEntry = new LogEntry();

  logEntry.Categories.Clear();
  logEntry.Categories.Add("Troubleshooting");
  logEntry.Priority = 5;
  logEntry.Severity = TraceEventType.Error;
  logEntry.Message = logMessage;

  Logger.Write(logEntry);
}


Walkthrough: Creating a Custom Trace Listener
Код

public class DebugTraceListener : CustomTraceListener

Код

public override void TraceData(TraceEventCache eventCache, string source, 
  TraceEventType eventType, int id, object data)
{
  if (data is LogEntry && this.Formatter != null) 
  {
    this.WriteLine(this.Formatter.Format(data as LogEntry));
  }
  else
  {
    this.WriteLine(data.ToString());
  }
}

Код

public override void Write(string message)
{
  Debug.Write(message);
}

public override void WriteLine(string message)
{
  Debug.WriteLine(message);
}



--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 18.1.2006, 23:33 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Security Application Block
  • Obtaining a temporary token for an authenticated user
  • Authenticating a user using a token
  • Ending a user session (expire a token)
  • Determining if a user is authorized to perform a task
The Security Application Block is designed to externalize the implementation of the authorization and caching provider from a running application. This design lets you change implementations without changing the code of the application. The following illustration shows the interrelationship between the key classes in the Security Application Block.
user posted image

Figure 16: Design of the Security Application Block

QuickStarts

Walkthrough: Obtain a Temporary Token for an Authenticated User
Код

ISecurityCacheProvider cache;
cache = SecurityCacheFactory.GetSecurityCacheProvider("Caching Store Provider");

Код

IIdentity identity = null;
if (Membership.ValidateUser("username", "password"))
{
  identity = new GenericIdentity("username", Membership.Provider.Name);
}

Код

IToken token = null; 
if (identity != null)
{
token = cache.SaveIdentity(identity);
}


Walkthrough: Authenticate a User Using a Token
Код

IIdentity identity = null;
if (Membership.ValidateUser("username", "password"))
{
  identity = new GenericIdentity("username", Membership.Provider.Name);
}
ISecurityCacheProvider cache;
cache = SecurityCacheFactory.GetSecurityCacheProvider("Caching Store Provider");
IToken token = null; 
if (identity != null)
{
  token = cache.SaveIdentity(identity);
  IIdentity savedIdentity = cache.GetIdentity(token);
}


Walkthrough: Terminate a User Session
Код

IIdentity identity = null;
if (Membership.ValidateUser("username", "password"))
{
  identity = new GenericIdentity("username", Membership.Provider.Name);
}

Код

ISecurityCacheProvider cache;
cache = SecurityCacheFactory.GetSecurityCacheProvider("Caching Store Provider");

Код

IToken token = null; 
if (identity != null)
{
token = cache.SaveIdentity(identity);
}

Код

cache.ExpireIdentity(token);


Walkthrough: Determine Whether a User is Authorized to Perform a Task
Код

IPrincipal principal = new GenericPrincipal(new GenericIdentity("tim"), new string[]{"Manager"});
bool authorized = ruleProvider.Authorize(principal, "Submit Order");




--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
arilou
Дата 19.1.2006, 13:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Великий МунаБудвин
****


Профиль
Группа: Экс. модератор
Сообщений: 2646
Регистрация: 15.7.2004
Где: город-герой Минск

Репутация: 21
Всего: 61



Pegas
Слабо перевести и в ФАК положить? Цены б тебе не было smile


--------------------
user posted imageuser posted image
PM WWW ICQ   Вверх
VisualProgrammerNET
Дата 19.1.2006, 13:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Почётный халявщик
**


Профиль
Группа: Участник
Сообщений: 461
Регистрация: 30.10.2005
Где: Зеленоград

Репутация: 4
Всего: 6



Занятная штука...
-------------

2arilou
Чё там переводить-то? Словарик в руки - и сам себе переводчик smile


--------------------
3 ГОДА НА user posted image 
PM MAIL ICQ   Вверх
Medved
Дата 19.1.2006, 14:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Буду рад любой помощи в переводе изложенного материала на русский язык.


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
VisualProgrammerNET
Дата 19.1.2006, 14:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Почётный халявщик
**


Профиль
Группа: Участник
Сообщений: 461
Регистрация: 30.10.2005
Где: Зеленоград

Репутация: 4
Всего: 6



А переводить надо и все те материалы, что под ссылками? Или картинки и подписи только?


--------------------
3 ГОДА НА user posted image 
PM MAIL ICQ   Вверх
Medved
Дата 19.1.2006, 14:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Да что угодно. Когда я делал выборку, старался использовать минимум английского текста. Было бы неплохо, если бы кто-нибудь что-нибудь дополнил.


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 19.1.2006, 21:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



Smart Client - Composite UI Application Block
http://msdn.microsoft.com/library/en-us/dn....asp?frame=true

The following diagram shows these two layers in the architecture of a .NET-based distributed application.
user posted image

Figure 1: Component layers found in distributed applications and services built with .NET

Figure 2 shows an example of the kind of rich user interface applications that the Composite UI Application Block can help you to produce. Meanwhile, the QuickStarts and a simple walkthrough example that demonstrates the fundamentals of the framework will help you to understand the structure and principles of the Composite UI Application Block. These examples and the related documentation are installed with the CAB framework.

user posted image

Figure 2: Sample call center application


Design of the Composite UI Application Block

Model-View-Controller (MVC)
http://msdn.microsoft.com/library/default....html/DesMVC.asp

Дополнительный материал:
Java библиотека - Триада MVC в действии
Delphi. Практика применения паттернов проектирования
  • Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
  • View. The view manages the display of information.
  • Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.
Figure 3 depicts the structural relationship between the three objects.
user posted image

Figure 3: MVC class structure


MVP patterns

user posted image

Figure 4: Comparison of the MVC and MVP patterns


Design for Modularity

Figure 5 shows how these components interoperate.
user posted image

Figure 5: Components typically found in a Composite UI Application Block application


Design of the WorkItem

The design of the Composite UI Application Block primarily supports applications built using a consistent set of patterns. One of the default patterns is the Model-View-Controller (MVC) pattern. These types of applications generally consist of:
  • Initialization code.
  • State shared between components in the use case.
  • Controller classes that act on the state and other resources.
  • View classes that interact with their controller and read state.
  • Disposal code.
Figure 6 shows how the WorkItem supports the other components and interactions that generally form the basis for a Composite UI Application Block application.

user posted image

Figure 6: Composite UI Application Block application


Event Broker

user posted image

Figure 7: The Event Broker System


Threat Model

user posted image

Figure 8: The CAB start-up and service loading sequence


user posted image

Figure 9: Asynchronous execution of event subscriptions


Subsystems of the Composite UI Application Block

The Composite UI Application Block consists of a number of subsystems that interoperate to provide the functionality that the application block provides. Figure 10 shows the grouping of these subsystems.

user posted image

Figure 10: Subsystems of the Composite UI Application Block


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Medved
Дата 19.1.2006, 22:51 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 7209
Регистрация: 15.9.2002
Где: Kazakhstan, Astan a

Репутация: 3
Всего: 154



"Hello World"

The sample application used in this walkthrough implements the common "Hello World" scenario, which allows you to focus on the application's design and architecture.

Physical Architecture

In this example, simple code in a separate module implements the model. In response to the view loading, the presenter within this module obtains the results from the model, and updates the view.
Communication between the view and the presenter is through a defined interface. Using interfaces establishes a contract between the participants, which forces the appropriate separation and reduces dependency.

user posted image

Figure 17 The result of running the completed application
    There are two projects in the completed Visual Studio solution:
  • ShellApplication is the main shell for the application. It contains the form that acts as the container for all the use cases in the application. This form includes the container controls that define the overall layout of the SmartParts. The SmartParts are implemented in and displayed by the separate module.
  • MyModule is the module that contains the WorkItem that represents the use case, and the SmartPart that represents the view part of the MVP pattern. It also contains the presenter that updates the view within the shell where it is displayed. In this simple case, where the module locally generates the data to display, it also acts as the model.

user posted image

Figure 11: The components in the completed example application


Stage 1: Creating the Shell and the Form

Your first task is to create the project that acts as the main shell for the application.

Figure 12 shows the architecture of the application you have created so far. As the application starts and you call the Run method in your Main routine, the CAB creates the ShellForm form and the root ShellWorkItem.

user posted image

Figure 12: The components at the end of Stage 1

To create the shell and form
1. Create a new C# Windows Forms application. Name the new application ShellApplication.
2. In the Solution Explorer window, rename Form1.cs to ShellForm.cs.

To add references to the core classes
1. In the Solution Explorer window, right-click References and then click Add Reference.
Цитата

Microsoft.Practices.CompositeUI.dll
Microsoft.Practices.CompositeUI.WinForms.dll
Microsoft.Practices.ObjectBuilder.dll

2. In the New Item dialog, select Class and name it ShellWorkItem.cs.
3. In the new class file, add the following using statement for the namespace:
Код

using Microsoft.Practices.CompositeUI;

4. Edit the ShellWorkItem class declaration so that it is public, and inherits from WorkItem:
Код

public class ShellWorkItem : WorkItem
{
}


To initialize and display the form from within the root WorkItem
1. In the Solution Explorer window, rename the file Program.cs to ShellApplication.cs and open it.
2. Edit the existing using statement for the WinForms namespace to use the CompositeUI.WinForms namespace classes:
Код

using Microsoft.Practices.CompositeUI.WinForms;

3. Replace the static class ShellApplication with a public class that inherits from FormShellApplication, and which instructs the CAB to load the ShellForm form into the ShellWorkItem:
Код

public class ShellApplication : FormShellApplication<ShellWorkItem, ShellForm>
{
}

4. Add the [STAThread] attribute to the static Main method in this class. This method executes when the application starts, and it must instantiate your ShellApplication class and call the Run method. The FormShellApplication class inherits from the CabApplication class, which contains the Run method implementation:
Код

[STAThread]
static void Main()
{
  new ShellApplication().Run();
}



Stage 2: Creating and Loading the Module

In this stage, you add the module that provides the view to display on the ShellForm form.

user posted image

Figure 13: The components at the end of Stage 2

To add the module that provide the view
1. Right-click the top-level Solution 'Shell Application' entry in the Solution Explorer window, click Add, then click New Project.
2. Select the Class Library project type and name it MyModule.

In this example, the new module contains a child WorkItem.

To add references to the core classes
1. Add Reference.
Цитата

Microsoft.Practices.CompositeUI.dll
Microsoft.Practices.CompositeUI.WinForms.dll
Microsoft.Practices.ObjectBuilder.dll

2. In the New Item dialog for the MyModule project, select Class and name it MyWorkItem.cs.
3. Add the following using statement for the namespace to your new class file:
Код

using Microsoft.Practices.CompositeUI;

4. Edit the MyWorkItem class declaration so that it is public and inherits from WorkItem:
Код

public class MyWorkItem : WorkItem { }


To add a class to your project
1. Rename the file Class1.cs to MyModuleInit.cs. This is the file Visual Studio added to your new project.
2. In the MyModuleInit.cs file, add the following using statements for the three namespaces you will reference classes from:
Код

using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Services;
using System.Windows.Forms;

3. Edit the class declaration to inherit from ModuleInit as shown here:
Код

public class MyModuleInit : ModuleInit

4. Add the following variable to reference the WorkItemTypeCatalogService (using the IWorkItemTypeCatalogService interface) so that you can access it to register your WorkItem:
Код

private IWorkItemTypeCatalogService myCatalogService;

5. Add the following public property to the class that sets the value of the myCatalogService variable. Use the [ServiceDependency] attribute on this property so that the dependency injection feature of the underlying ObjectBuilder utility will create an instance of the service and pass back a reference to it:
Код

[ServiceDependency]
public IWorkItemTypeCatalogService myWorkItemCatalog

  set { myCatalogService = value; }
}

6. Override the Load method of the ModuleInit class so that it registers your module's WorkItem. The code here calls the corresponding method of the base class first, as is usual practice, however the Load method of the ModuleInit class does nothing and so this line could be omitted:
Код

public override void Load()
{
  base.Load();
  myCatalogService.RegisterWorkItem<MyWorkItem>();
}

Note:
In Stage 4 of this walkthrough, you will change this code to use the RootWorkItem to add a child WorkItem. This illustrates some of the different techniques that you can use in CAB applications.

To instruct the CAB to load the new module
1. In the ShellApplication project, open the New Item dialog box and select XML File. Name it ProfileCatalog.xml.
Edit the file as shown in the following code to load the module named MyModule.dll:
Код

<?xml version="1.0" encoding="utf-8" ?>
<SolutionProfile xmlns="http://schemas.microsoft.com/pag/cab-profile">
  <Modules>
    <ModuleInfo AssemblyFile="MyModule.dll" />
  </Modules>
</SolutionProfile>



Stage 3: Adding the TabWorkspace

user posted image

Figure 15. The ShellForm form with the SplitContainer and TabWorkspace controls


user posted image

Figure 14. The components at the end of Stage 3

To add a TabWorkspace to the shell application
1. Open the file ShellForm.cs in the form designer, and resize it to 500 x 300 pixels by dragging the form edges, or by setting the Size property in the Properties window.
2. From the Containers section of the Toolbox, drag a SplitContainer control onto the form. Drag the center splitter so that the two panels are approximately the same width.
3. The CAB workspace controls, such as TabWorkspace and ZoneWorkspace do not appear in the Toolbox by default. Right-click the Toolbox, click Items..., and then click Browse.....
4. In the \Src\CS\CompositeUI.WinForms\bin\Debug\ subfolder of the folder where you installed the CAB files, select the file Microsoft.Practices.CompositeUI.WinForms.dll.
5. Drag a TabWorkspace onto the form and drop it onto the left-hand panel of the SplitContainer control.
6. Right-click the new TabWorkspace control and click Properties. In the Properties window, navigate to the Dock property and set it to Fill. This positions the workspace control to fill the panel, and adds two default tabs to it.
7. Right-click the TabWorkspace control and click Remove Tab. Then repeat this step to remove the second tab. Your form should now look like Figure 15.


Stage 4: Creating and Showing the SmartPart

user posted image

Figure 11: The components at the final stage of building the application

To create an interface for the view and the presenter to communicate
1. Right-click the MyModule project entry in Solution Explorer, click Add, and then click New Item. In the New Item dialog, click Interface and name it IMyView.cs.
Add the public keyword to the interface statement. Then declare the two members of this interface as an event named Load and a string property named Message as shown in the following code:
Код

public interface IMyView
{
  event EventHandler Load;
  string Message { get; set; }
}         

Now you can create the SmartPart user control. In this example, the SmartPart contains a Label control that displays a message in the shell.

user posted image

Figure 16. The completed MyView user control

To create a SmartPart user control
1. Right-click the MyModule project entry in Solution Explorer, and click Add, and then click New Item. In the New Item dialog box, select User Control and name it MyView.cs.
2. Resize the user control in the form designer window to 250 x 250 pixels.
3. Drag a Label control from the Toolbox onto the user control and drop it near the top left corner.
4. In the Properties window for the Label control, change the Font Size property to 10. Your user control should now look like Figure 16.

Within the user control, you must now implement the IMyView interface that you created earlier. This means that the user control must expose a property named Message. Internally, the user control sets the Text property of the Label control to the value of the Message property.

To implement the IMyView interface
1. Right-click the design surface and select View Code. Add the IMyView interface to the class declaration so that the user control class implements this interface:
Код

public partial class MyView : UserControl, IMyView    

2. Right-click IMyView and click Implement Interface, then click Implement Interface in the fly-out menu.
3. Replace the two throw statements that Visual Studio generates with two statements that get and set the value of the Message property:
Код

public string Message
{
  get
  {
    return this.label1.Text;
  }
  set
  {
    this.label1.Text = value;
  }
}    

The next step is to create the class that acts as the presenter in the MVP pattern. It manipulates the SmartPart you just created. The presenter hooks into the Load event of the view and exposes an event handler for this event. The event handler set the Message property of the view.

To create the presenter class
1. In the New Item dialog, select Class and name it MyPresenter.cs.
2. Edit the opening class declaration to make it public, and add a variable of type IMyView to the class to reference the view through the interface that you created for it:
Код

public class MyPresenter
{
  IMyView view;        

3. Create a constructor for the class. The constructor takes a reference to the view, sets it as the view for this presenter, and subscribes to the Load event of the view:
Код

public MyPresenter(IMyView view)
{
  this.view = view;
  view.Load += new EventHandler(view_Load);
}        

4. Create an event handler for the Load event. This sets the Message property of the Label control:
Код

void view_Load(object sender, EventArgs e)
{
  view.Message = "Hello World from a Module";
}         

In the next stage, you modify the ModuleInit class so that it gets a reference to the WorkItem in the module, and calls the Run method of this WorkItem.

To get a reference to the WorkItem
1. Open the MyModuleInit.cs file and add the following variable immediately after the existing myCatalogService variable declaration. The variable will contain a reference to the root ShellWorkItem:
Код

private WorkItem parentWorkItem;

2. Add a public property to the class. This property sets the value of the parentWorkItem variable. Use the [ServiceDependency] attribute on this property so that the dependency injection feature of the underlying ObjectBuilder utility references the existing WorkItem, and passes back a reference to it:
Код

[ServiceDependency]
public WorkItem ParentWorkItem

  set { parentWorkItem = value; }
}    

3. Modify the Load method that you added during Stage 2. This creates an instance of the module's WorkItem within the context of the root ShellWorkItem using the AddNew method, then calls the Run method of the new WorkItem. You retrieve the Workspace using its name and pass this Workspace to the Run method. In this example, the target is the TabWorkspace named tabWorkspace1 that you placed into the SplitContainer control on the form:
Код

public override void Load()
{
  base.Load();
  MyWorkItem myWorkItem = parentWorkItem.WorkItems.AddNew<MyWorkItem>();
  myWorkItem.Run(parentWorkItem.Workspaces["tabWorkspace1"]);
}         

In the final step, you implement the Run method in the module's WorkItem to create a new instance of the view, instantiate the presenter, and show the view within the TabWorkspace.

To create and show the view
1. Open the file MyWorkItem.cs, and add the following using statement for the namespace that contains the IWorkspace class you will use in your new code:
Код

using Microsoft.Practices.CompositeUI.SmartParts;

2. Create a public Run method that accepts as a parameter a reference to the TabWorkspace. It is a good idea to declare the parameter as of type IWorkspace instead of TabWorkspace. If in future you decide to change the type of workspace used in the shell form, you will not have to change the method declaration:
Код

 public void Run(IWorkspace TabWorkspace)
{
}     

3. Add statements to the Run method that create a new instance of the MyView class (using the AddNew method of the Items collection of this WorkItem), and a new instance of the MyPresenter class. Passing the view instance you just created to the presenter connects them together:
Код

IMyView view = this.Items.AddNew<MyView>();
MyPresenter presenter = new MyPresenter(view);    

4. Add statements to the Run method that add the new presenter to the current WorkItem, and call the Show method of the TabWorkspace to display the view:
Код

this.Items.Add(presenter);
TabWorkspace.Show(view);    




user posted image

Figure 11: The components in the completed example application

Figure 11 repeats the schematic that you saw near the start of this walkthrough. It shows all of the components in the completed application. At run time, the application initializes and loads the main form (ShellForm). It then loads the module (MyModule) that is specified in the ProfileCatalog.xml file. The module registers its WorkItem (MyWorkItem) with the RootWorkItem that is exposed by the shell, and calls the Run method.
The Run method of the module's WorkItem creates a new instance of the user control (MyView) and the presenter (MyPresenter). It adds the presenter to the module's WorkItem, and shows the MyView user control in the TabWorkspace. The module handles the Load event of the MyView user control and sets the Message property of the user control, which displays the message in the Label control.


--------------------
http://extreme.sport-express.ru/
...и неважно сколько падал, важно сколько ты вставал...
PM MAIL WWW ICQ Skype GTalk   Вверх
Страницы: (2) [Все] 1 2 
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.1985 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.