Модераторы: 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   Вверх
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

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


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

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


 




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


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

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