logging in or signing up 5 Mee12 Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINTLite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 346 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: October 25, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... Premium member Presentation Transcript .NET Application BlocksPresented by:Steven Borg: .NET Application Blocks Presented by: Steven Borg Slide2: Special Thanks to: Shannon Braun & Jeff Kryzer (Born Consulting) Ron Jacobs (Microsoft – Patterns & Practices) Avi Ben-Menahem (Microsoft – Israel) (All of which contributed (voluntarily or not) to this presentation.) Contact information: Contact information Jeff Kryzer jeff.kryzer@born.com Shannon Braun shannon.braun@born.com More information about BORN’s Microsoft Services and Solutions Jay Lendl – jay.lendl@born.com 952.258.7593 http://www.born.comToday’s Roadmap: Today’s Roadmap Benefits of application blocks How the blocks fit into the recommended application architecture Overview of several application blocks Summary The Problem: The ProblemThe Problem: The ProblemThe Problem: The ProblemSound familiar?: Sound familiar? Writing a component to make it simpler to call stored procedures Building a framework component that allows you to log errors to different sources Building framework / infrastructure components to generally simplify app development …wishing Microsoft had done some of this for you?Application Blocks for .NETBeyond ‘sample code’: Application Blocks for .NET Beyond ‘sample code’ Reusable Code – C# and VB.NET Documentation Quick Start samples patterns & practices …showcasing best practices Tested & reviewed: Security, Performance, etc. Considering future direction in design …better solutions, faster! Benefits of using the blocks: Benefits of using the blocks Designed around common implementations for new projects Allows concentration on business code rather then plumbing Creates consistent plumbing across projects Tested & reviewed for best practices Architecture GuidanceMicrosoft patterns & practices: Architecture Guidance Microsoft patterns & practices Proven Based on field and partner experience Authoritative Best advice available Accurate Technically validated and tested Actionable Provide the steps to success Relevant Address real world scenarios Available online http://www.microsoft.com/practices Books available from http://shop.microsoft.com/practicesEULA and Support ModelWhat about licensing & support?: EULA and Support Model What about licensing & support? Source Code only – VB.NET and C# No binaries - ‘As is’ EULA Customizations OK Redistribution & repackaging OK GotDotNet Community Support PSS sign-off PSS Training Consistency in recommendations Escalation procedures, bug reportingTypical application: Typical applicationHow the blocks fit: How the blocks fit Data Access AB Data Aggregation AB Asynchronous AB Caching AB UI Process AB Exception Mgmt AB Configuration AB Updater ABData Access Application Block: Data Access Application BlockData application block: Data application block What is it? Implements a data access helper component, SqlHelper, which helps execute statements against SQL Server 7.0 and higher by exposing a set of static methods and reduces the amount of data access code you have to write. V2.0 supports the .NET Framework v1.1. Why use it? Use it if you are using SQL Server as the database and wish to reduce the amount of data access code you write. Can use it internally in your own data access classes. (Versions of SqlHelper for OleDb and Oracle written in C# are included in the Nile 3.0 sample application.)Data application block: Data application block One of the oldest blocks (current V2) Purpose: Simplified model for calling ADO.NET SqlClient Problems solved: Prescribed best practices for high performance, scalable data access Encapsulates the most common data access tasks Issues: As deployed, only supports SQL Server 7.0 and higher Versions for OleDb and Oracle written in C# are included in the Nile 3.0 sample application.DAAB V2 supports: DAAB V2 supports Returning many formats: Get DataSets, DataReaders, Scalars, XmlReaders and execute query without results – all in one line of code Simplifies calling with many sources Connections, Conn. Strings, SQL Transactions Support for strongly typed DataSets with the FillDataset method Support for committing updates to a DataSet back to the database Additional helper methods with support for DataRow type parameters Data Access Application Block: Data Access Application Block SqlHelper static methods ExecuteNonQuery – do not return rows ExecuteDataset – get a dataset from TSQL or sproc ExecuteReader – get a DataReader ExecuteScalar - retrieve a single value resultset from a Transact-SQL statement or stored procedure ExecuteXMLReader - retrieve XML data Choosing a DAAB Method: SqlHelper SqlHelper.ExecuteDataset( SqlHelper.ExecuteDataset(“connectionstring” First, choose the response format Int DataSet SqlDataReader Object XmlReader Then choose target data source Connection String SqlConnection SqlTransaction …and finally, what type of parameters you want to send Value Array SqlParameter Arrays No Parameters Choosing a DAAB Method SqlHelper.ExecuteDataset(“connectionstring”, CommandType.StoredProcedure, ”CustomersGetByPlanet”, “Earth”);Example SqlHelper method: SQL Server Data Access Application Block Business Layer UI Layer Example SqlHelper method SqlHelper ExecuteReader SqlDataReader dr = SqlHelper.ExecuteReader( CONN_STRING,“GetProductsByCat", <categoryID>); Typical ADO.NET Code: Typical ADO.NET Code public void AddLink(int moduleId, String userName, String title, String url, String mobileUrl, int viewOrder, String description,int parentId, int moduleLinkId) { SqlConnection myConnection = new SqlConnection(m_connStr); SqlCommand myCommand = new SqlCommand("AddLink", myConnection); myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleId; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); ... try { myConnection.Open(); myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } }Typical DAAB Code: Typical DAAB Code public void AddLink(int moduleId, String userName, String title, String url, String mobileUrl, int viewOrder, String description,int parentId, int moduleLinkId) { SqlHelper.ExecuteNonQuery( connStr, // connection string “AddLink", // Stored Proc or query moduleId, // parameters userName, title, url, mobileUrl, viewOrder, description, parentId, moduleLinkId); }What else you might need: What else you might need Batch Updates Connection String Management Exception Management Monitoring / Logging Async SupportResources for DAAB: Resources for DAAB .NET Data Access Architecture Guide http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp Data Access GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=c20d12b0-af52-402b-9b7c-aaeb21d1f431 Exception Management Application Block: Exception Management Application BlockException block: Exception block What is it? Provides a simple and flexible mechanism for publishing exception information through an ExceptionManager class. Also supports filtering and creating your own exception publishers to publish data to sources other than files and event logs using text and XML. Also provides a BaseApplicationException class from which to derive, which collects additional environmental information. Why use it? Use it as the basis for your exception handling framework. Ideal for applications that use exception chaining or wrapping and pass exceptions up the call stack. Custom publishers can be used to log exception information to shared databases. Exception block: Exception block Purpose: Make it simple and powerful to report that an exception has occurred (1 line of code) Make it extensible and flexible to log errors however you want Problems solved: Often exception code is unique and repeated in every application Changing how your exceptions are logged meant changing your code Difficult to pass context information up the stackException block: Exception block Your Application Publisher (event log) Exception Manager Exception Publisher (database) Publisher (text file) Publisher (email)Exception block: Exception block Publishing an exception: try {…} catch (Exception ex) { ExceptionManager.Publish(ex); or ExceptionManager.Publish(ex, nameValueCollection); } Exception block: Exception block The exception block provides a base application exception class to inherit all your exceptions from Has contextual information like MachineName, Thread, Login, DateTime, AppDomain Has additional information collection for inserting custom pieces of data class HeartAttackException : BaseApplicationException { ... } Exception block: Exception block Throwing an exception Your custom exceptions now have additional information passed up the stack: HeartAttackException ex; ex = new HeartAttackException(); ex.AdditionalInformation.Add("BloodPressure", "120/300"); ex.AdditionalInformation.Add("Pulse", 85); ex.AdditionalInformation.Add("WhiteCount", 1000); throw ex; Exception block: Exception block Publishers are config file driven <exceptionManagement mode="on"> <publisher mode="on" assembly="MyPublishers" type="PublishToTextFile" FileName="C:\Errors.log" /> <publisher mode="on" assembly="MyPublishers" type="PublishToEmail" Server="mail.ABC.com" User="Jeff" Password="XYZ" /> </exceptionManagement> Tips for exception blocks: Tips for exception blocks Remember to publish your exception if you are at the top of the stack—Do not re-throw it. If you choose to ignore the above tip, at least add exception handling into the Thread_UnhandledException event (winforms) Application_Error event (webforms) To display an exception to the user, you still need a MessageBox call. ExceptionManager.Publish just records it.Resources: Resources Exception Management / Instrumentation AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=c1146b3a-3f9b-47b8-899e-f42e667cdccf Caching Application Block: Caching Application BlockCaching block: Caching block Purpose: Cache data that is expensive to retrieve Increase performance and scalability Problems solved: Data that changes every 10 seconds doesn’t have to be fetched 50 times per second. Web applications already have the System.Web.Caching.Cache object, but there is no equivalent caching object for WinForm, Console, NTService, or CompactFramework applications.Caching block: Caching block SLOW SLOW Cache CacheCaching block: Caching block Before you get started, read this guide on caching practices: http://msdn.microsoft.com/library/en-us/dnbda/html/CachingArchch5.asp Caching block closely parallels the guide This guide is referenced many times from the online help documentCaching block: Caching block Your Application CacheService “CacheScavenger” CacheManager Config fileCaching block: Caching block The DataStore can be any class which implements the ICacheStorage interface There are 3 implementations which come with the block: Memory-mapped file Singleton object SQL Server 2000 database (comes with SQL script)Caching block: Caching block CacheService class Its job is to remove items when they expire Expiration can be determined by any class which implements ICacheItemExpiration The following come with the block: AbsoluteTime (expire at 1:30) ExtendedFormatTime (expire every hour) FileDependency (expire when file changes) SlidingTime (expire in 10 seconds)Caching block: Caching block Supports scavenging Process for removing items from the cache when resources become low To write your own class for this, simply implement the IScavengingAlgorithm interface The block comes with a default “scavenger” which uses a LRU algorithm Note: A CacheItem can optionally have a callback delegate for when it gets removed by the CacheService (via expiration or scavenging)Caching block: Caching block Checking cache obj = cacheManager.GetData(key); If (obj == null) { //not in cache, fetch it and add to cache obj = GetExpensiveObjectByKey(key); cacheManager.Add(key, obj); } obj.DoSomething(); Caching block: Caching block Setting an expiration on an item ICacheItemExpiration[2] exp; //expire item 8 hours from now exp[0] = new SlidingTime(new TimeSpan(8, 0, 0)); //or expire when file changes, whichever comes first exp[1] = new FileDependency(@"C:\MyData.xml"); cacheManager.GetItem(key).Expirations = exp; Resources: Resources Caching AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=853bb349-ebc1-44c1-b3be-9c72c49a000c User Interface Application Block: User Interface Application BlockUser interface process block: User interface process block Purpose: Decouple UI and navigation/workflow Maintain state between UI components and across processes Problems Solved: Navigation/workflow code bound to UI Extensibility issues with tightly coupled UI/workflow Platform independent model for Windows, Web and device applications UIP block implementation: UIP block implementation DALC DALC Biz Components Biz Components Data Access MyFunc() { //do cool code //more good stuff } Persistence Providers: - SQL Server - Encrypted SQL Server - Memory - ASP.NET Session - CustomA user interface process: A user interface process cart browsecatalog error checkout congrats addItem fail resume resume resume passCheckout failCheckout checkout failA user interface process: A user interface process cart browsecatalog error checkout congrats addItem fail resume resume resume passCheckout failCheckout checkout fail The UIP block uses XML config to manage flowPutting UIP to work: Putting UIP to work Starting the task… Driving the UIP manager…Putting it together: Putting it together Starting the task… Driving the UIP manager… Navigation and persisting state . . .Other things you may need: Other things you may need Support for multi-pane application by creating a ViewManager for Windows Controls CMAB for multi-process/multi-developer workResources: Resources Multi-pane example application http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=c92b944e-a7e7-434d-9dd4-5e0281145a73 User Interface AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=0af2b0ef-b049-401a-a2f2-f55a070c1572 Updater Application Block: Updater Application BlockUpdater block: Updater block Purpose: Update your application after it has been deployed. Uses a “pull” technique. No user interaction required Problems solved: Users don’t always know when to update the app manually or how Pushing updates using SMS scripts or group policies or login scripts is complicated and has a slow turn-around time Plus you have to go through the IT network administrators instead of doing it yourself Typical design of an updater block: Typical design of an updater block Update Controller Downloader Validator Post Processor (optional) Your Application User starts this Controller starts your app ServerAlternate design: Alternate design Downloader Validator Post Processor (optional) Server Your Application (also the Update Controller) User starts this DLL DLL DLL AppDomain using ShadowCopyUpdater block: Updater block The Downloader can be any class that implements the IDownloader interface There is one implementation that comes with the block: BITSDownloader - uses the Background Intelligent Transfer Service (BITS) to copy files Uses HTTP or HTTPS If download is interrupted, it continues from where it left off BITS only works on Windows 2000, XP and 2003 Note: A UNC downloader class implementation is listed in the help document.Updater block: Updater block The Validator can be any class that implements the IValidator interface There are two implementations that come with the block: KeyValidator - uses symmetric key Must ship password along with client RSAValidator – uses private/public keys This is more secure than KeyValidatorUpdater block: Updater block Also comes with: Sample AppStarter (the Update Controller) Manifest creation utility Updater block: Updater block Why should you use the updater block instead of simply downloading Windows Forms applications through a browser? Downloading WinForm applications through a browser runs the application within a security "sandbox.” Restricts you from Registry, File IO, etc. Some “browser download” applications require you to be connected to the server just to run Resources: Resources Updater AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=83c68646-befb-4586-ba9f-fdf1301902f5 Configuration Management Application Block: Configuration Management Application BlockConfiguration management application block (CMAB): Configuration management application block (CMAB) Purpose: Standard interface Read/Write of application configuration data with an independent data store Problems solved: Ability to write to configuration file Caching support Increased data security/integrity Supports complex in memory data structures CMAB implementation: CMAB implementation Your Application Application XML Configuration File (holds config for config) Configuration Storage Providers: - XML File - SQL Server - Registry - Custom Data Protection Providers: - DPAPI - BCL - Custom Configuration Section Handlers Configuration Section Handlers Configuration Section HandlersCMAB up and running: CMAB up and running In the app.config / web.config Define Configuration Section Handler Define Configuration Storage Provider Define Data Protection Provider Define Cache parametersCMAB configuration: CMAB configuration <configuration> <configSections> <section name="applicationConfigurationManagement" type=“MS.AppBlocks.CMAB" /> <section name="ApplConfig1" type=“MS.AppBlocks.CMAB.XmlHashtableSectionHandler" /> </configSections> <applicationConfigurationManagement > <configSection name="ApplConfig1"> <configCache enabled="true" refresh="1 * * * *" /> <configProvider assembly=“MS.AppBlocks.CMAB" type=“MS.AppBlocks.CMAB.Storage.XmlFileStorage” encrypted="false" /> <protectionProvider assembly=“MS.AppBlocks.CMAB" type=“MS.AppBlocks.CMAB.DataProtection.BCLDataProtection" </configSection> </applicationConfigurationManagement> </configuration>CMAB implementation: CMAB implementation //Create you own hash table for key/val pairs Hashtable values = new Hashtable(); // Pass it to the ConfigManager for writing ConfigurationManager.Write(values); // Now write items into that storage ConfigurationManager.Items["connStr"] = "MyCnStr"; Results in…Powerful custom configuration: Powerful custom configuration XmlSerializer Section Handler is not limited to: Key/Value pair Read only access Allows for serialization of object graphs for describing configuration //create your custom config class DBConfig dbc = new DBConfig("sblap","sbraun","password"); //persist to the config file ConfigurationManager.Write("XmlSerializer",dbc);Resources: Resources Xml Serialization Stack http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlserializationhierarchy.asp XML Serialization in the .NET Framework http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnexxml/html/xml01202003.asp Configuration Management AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=01875f69-9358-437b-a8ae-fa4bf2e3080f Aggregation Application Block: Aggregation Application BlockAggregation block: Aggregation block Purpose: Retrieve data from a provider (e.g. web service or database) without the caller knowing where data is coming from Allows you to fetch data from multiple providers and combine into one set Executes multiple provider calls simultaneously Problems solved: Sometimes changing the backend provider requires you to change the calling code Result is in XML so changing from 3 to 4 providers won’t necessarily change your calling codeAggregation block: Aggregation block Your Application Aggregation Request Config file Request Processor Service Agent 1 Service Agent 2 Service Agent 3 Web Service Web ServiceAggregation block: Aggregation block Your Application Aggregation Request Request object is constructed (including parameters) and passed into AggregationRequest Result is XMLDocument or DataSet formatted according to XSD Aggregation block: Aggregation block Request processor uses thread pool to run agents simultaneously Each agent can have a timeout - processor will kill the thread Write your own agents by implementing IServiceAgent interface Request Processor Service Agent 1 Service Agent 2 Service Agent 3 Web Service Web ServiceAggregation block: Aggregation block Config settings for Agents: <ServiceAgent SAID="YahooStocks"> <ClassName>MyAgents.YahooStocks</ClassName> <Transformation>YahooOutput.xslt</Transformation> </ServiceAgent> <ServiceAgent SAID="ETradeStocks"> <ClassName>MyAgents.ETradeStocks</ClassName> <Transformation>ETradeOutput.xslt</Transformation> </ServiceAgent>Aggregation block: Aggregation block Configuration settings for requests: <Request> <RequestType Type="GetStockQuotes"> <ServiceAgents> <SAID>YahooStocks</SAID> <SAID>ETradeStocks</SAID> </ServiceAgents> <TimeToLive>5</TimeToLive> <TransformationSchema>StockOutput.xsd</TransformationSchema> </RequestType>Resources: Resources Aggregation AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=005c405e-b892-44b0-a742-96ff286e3bd1 Asynchronous Management Application Block: Asynchronous Management Application BlockAsync invocation block: Async invocation block Purpose Simplify development of asynchronous operations in your system Improve responsiveness Streamline processing Problems solved Problem with high-latency synchronous processes Async invocation blocksupport components: Async invocation block support components ROHService Responsible for picking up requests from the database and invoking the appropriate service agent MonitorService Recovers service agent requests Garbage collects old requests Requires installation using the InstallUtil.exe utilityAsync invocation blockimplementation: Async invocation block implementation Create service agent classes and add entries to the database for each agent Create an AsyncBatchRequest object Call AddRequest() for each service agent, passing in any parameters Use AsyncRequestProcessor to submit the batch by calling SubmitRequest() Use ResultsManager to get request results Resources: Resources Asynchronous Management AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=1358f932-bba0-490e-968c-cd55281442c2 Other blocks: Other blocks Authorization/Profile Application Block Instrumentation Block (extension to Exception Management Block for WMI) Smart Client Offline Application BlockWhere to find blocks(besides Google): Where to find blocks (besides Google) Application Updater Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/updater.asp Asynchronous Invocation Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/paiblock.asp Caching Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/Cachingblock.asp Configuration Management Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/cmab.asp Data Access Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp Exception Management Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/emab-rm.asp Service Aggregation Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/serviceagg.asp User Interface Process Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/uip.asp You do not have the permission to view this presentation. In order to view it, please contact the author of the presentation.
5 Mee12 Download Post to : URL : Related Presentations : Share Add to Flag Embed Email Send to Blogs and Networks Add to Channel Uploaded from authorPOINTLite Insert YouTube videos in PowerPont slides with aS Desktop Copy embed code: (To copy code, click on the text box) Embed: URL: Thumbnail: WordPress Embed Customize Embed The presentation is successfully added In Your Favorites. Views: 346 Category: Entertainment License: All Rights Reserved Like it (0) Dislike it (0) Added: October 25, 2007 This Presentation is Public Favorites: 0 Presentation Description No description available. Comments Posting comment... Premium member Presentation Transcript .NET Application BlocksPresented by:Steven Borg: .NET Application Blocks Presented by: Steven Borg Slide2: Special Thanks to: Shannon Braun & Jeff Kryzer (Born Consulting) Ron Jacobs (Microsoft – Patterns & Practices) Avi Ben-Menahem (Microsoft – Israel) (All of which contributed (voluntarily or not) to this presentation.) Contact information: Contact information Jeff Kryzer jeff.kryzer@born.com Shannon Braun shannon.braun@born.com More information about BORN’s Microsoft Services and Solutions Jay Lendl – jay.lendl@born.com 952.258.7593 http://www.born.comToday’s Roadmap: Today’s Roadmap Benefits of application blocks How the blocks fit into the recommended application architecture Overview of several application blocks Summary The Problem: The ProblemThe Problem: The ProblemThe Problem: The ProblemSound familiar?: Sound familiar? Writing a component to make it simpler to call stored procedures Building a framework component that allows you to log errors to different sources Building framework / infrastructure components to generally simplify app development …wishing Microsoft had done some of this for you?Application Blocks for .NETBeyond ‘sample code’: Application Blocks for .NET Beyond ‘sample code’ Reusable Code – C# and VB.NET Documentation Quick Start samples patterns & practices …showcasing best practices Tested & reviewed: Security, Performance, etc. Considering future direction in design …better solutions, faster! Benefits of using the blocks: Benefits of using the blocks Designed around common implementations for new projects Allows concentration on business code rather then plumbing Creates consistent plumbing across projects Tested & reviewed for best practices Architecture GuidanceMicrosoft patterns & practices: Architecture Guidance Microsoft patterns & practices Proven Based on field and partner experience Authoritative Best advice available Accurate Technically validated and tested Actionable Provide the steps to success Relevant Address real world scenarios Available online http://www.microsoft.com/practices Books available from http://shop.microsoft.com/practicesEULA and Support ModelWhat about licensing & support?: EULA and Support Model What about licensing & support? Source Code only – VB.NET and C# No binaries - ‘As is’ EULA Customizations OK Redistribution & repackaging OK GotDotNet Community Support PSS sign-off PSS Training Consistency in recommendations Escalation procedures, bug reportingTypical application: Typical applicationHow the blocks fit: How the blocks fit Data Access AB Data Aggregation AB Asynchronous AB Caching AB UI Process AB Exception Mgmt AB Configuration AB Updater ABData Access Application Block: Data Access Application BlockData application block: Data application block What is it? Implements a data access helper component, SqlHelper, which helps execute statements against SQL Server 7.0 and higher by exposing a set of static methods and reduces the amount of data access code you have to write. V2.0 supports the .NET Framework v1.1. Why use it? Use it if you are using SQL Server as the database and wish to reduce the amount of data access code you write. Can use it internally in your own data access classes. (Versions of SqlHelper for OleDb and Oracle written in C# are included in the Nile 3.0 sample application.)Data application block: Data application block One of the oldest blocks (current V2) Purpose: Simplified model for calling ADO.NET SqlClient Problems solved: Prescribed best practices for high performance, scalable data access Encapsulates the most common data access tasks Issues: As deployed, only supports SQL Server 7.0 and higher Versions for OleDb and Oracle written in C# are included in the Nile 3.0 sample application.DAAB V2 supports: DAAB V2 supports Returning many formats: Get DataSets, DataReaders, Scalars, XmlReaders and execute query without results – all in one line of code Simplifies calling with many sources Connections, Conn. Strings, SQL Transactions Support for strongly typed DataSets with the FillDataset method Support for committing updates to a DataSet back to the database Additional helper methods with support for DataRow type parameters Data Access Application Block: Data Access Application Block SqlHelper static methods ExecuteNonQuery – do not return rows ExecuteDataset – get a dataset from TSQL or sproc ExecuteReader – get a DataReader ExecuteScalar - retrieve a single value resultset from a Transact-SQL statement or stored procedure ExecuteXMLReader - retrieve XML data Choosing a DAAB Method: SqlHelper SqlHelper.ExecuteDataset( SqlHelper.ExecuteDataset(“connectionstring” First, choose the response format Int DataSet SqlDataReader Object XmlReader Then choose target data source Connection String SqlConnection SqlTransaction …and finally, what type of parameters you want to send Value Array SqlParameter Arrays No Parameters Choosing a DAAB Method SqlHelper.ExecuteDataset(“connectionstring”, CommandType.StoredProcedure, ”CustomersGetByPlanet”, “Earth”);Example SqlHelper method: SQL Server Data Access Application Block Business Layer UI Layer Example SqlHelper method SqlHelper ExecuteReader SqlDataReader dr = SqlHelper.ExecuteReader( CONN_STRING,“GetProductsByCat", <categoryID>); Typical ADO.NET Code: Typical ADO.NET Code public void AddLink(int moduleId, String userName, String title, String url, String mobileUrl, int viewOrder, String description,int parentId, int moduleLinkId) { SqlConnection myConnection = new SqlConnection(m_connStr); SqlCommand myCommand = new SqlCommand("AddLink", myConnection); myCommand.CommandType = CommandType.StoredProcedure; SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleId; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); ... try { myConnection.Open(); myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } }Typical DAAB Code: Typical DAAB Code public void AddLink(int moduleId, String userName, String title, String url, String mobileUrl, int viewOrder, String description,int parentId, int moduleLinkId) { SqlHelper.ExecuteNonQuery( connStr, // connection string “AddLink", // Stored Proc or query moduleId, // parameters userName, title, url, mobileUrl, viewOrder, description, parentId, moduleLinkId); }What else you might need: What else you might need Batch Updates Connection String Management Exception Management Monitoring / Logging Async SupportResources for DAAB: Resources for DAAB .NET Data Access Architecture Guide http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp Data Access GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=c20d12b0-af52-402b-9b7c-aaeb21d1f431 Exception Management Application Block: Exception Management Application BlockException block: Exception block What is it? Provides a simple and flexible mechanism for publishing exception information through an ExceptionManager class. Also supports filtering and creating your own exception publishers to publish data to sources other than files and event logs using text and XML. Also provides a BaseApplicationException class from which to derive, which collects additional environmental information. Why use it? Use it as the basis for your exception handling framework. Ideal for applications that use exception chaining or wrapping and pass exceptions up the call stack. Custom publishers can be used to log exception information to shared databases. Exception block: Exception block Purpose: Make it simple and powerful to report that an exception has occurred (1 line of code) Make it extensible and flexible to log errors however you want Problems solved: Often exception code is unique and repeated in every application Changing how your exceptions are logged meant changing your code Difficult to pass context information up the stackException block: Exception block Your Application Publisher (event log) Exception Manager Exception Publisher (database) Publisher (text file) Publisher (email)Exception block: Exception block Publishing an exception: try {…} catch (Exception ex) { ExceptionManager.Publish(ex); or ExceptionManager.Publish(ex, nameValueCollection); } Exception block: Exception block The exception block provides a base application exception class to inherit all your exceptions from Has contextual information like MachineName, Thread, Login, DateTime, AppDomain Has additional information collection for inserting custom pieces of data class HeartAttackException : BaseApplicationException { ... } Exception block: Exception block Throwing an exception Your custom exceptions now have additional information passed up the stack: HeartAttackException ex; ex = new HeartAttackException(); ex.AdditionalInformation.Add("BloodPressure", "120/300"); ex.AdditionalInformation.Add("Pulse", 85); ex.AdditionalInformation.Add("WhiteCount", 1000); throw ex; Exception block: Exception block Publishers are config file driven <exceptionManagement mode="on"> <publisher mode="on" assembly="MyPublishers" type="PublishToTextFile" FileName="C:\Errors.log" /> <publisher mode="on" assembly="MyPublishers" type="PublishToEmail" Server="mail.ABC.com" User="Jeff" Password="XYZ" /> </exceptionManagement> Tips for exception blocks: Tips for exception blocks Remember to publish your exception if you are at the top of the stack—Do not re-throw it. If you choose to ignore the above tip, at least add exception handling into the Thread_UnhandledException event (winforms) Application_Error event (webforms) To display an exception to the user, you still need a MessageBox call. ExceptionManager.Publish just records it.Resources: Resources Exception Management / Instrumentation AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=c1146b3a-3f9b-47b8-899e-f42e667cdccf Caching Application Block: Caching Application BlockCaching block: Caching block Purpose: Cache data that is expensive to retrieve Increase performance and scalability Problems solved: Data that changes every 10 seconds doesn’t have to be fetched 50 times per second. Web applications already have the System.Web.Caching.Cache object, but there is no equivalent caching object for WinForm, Console, NTService, or CompactFramework applications.Caching block: Caching block SLOW SLOW Cache CacheCaching block: Caching block Before you get started, read this guide on caching practices: http://msdn.microsoft.com/library/en-us/dnbda/html/CachingArchch5.asp Caching block closely parallels the guide This guide is referenced many times from the online help documentCaching block: Caching block Your Application CacheService “CacheScavenger” CacheManager Config fileCaching block: Caching block The DataStore can be any class which implements the ICacheStorage interface There are 3 implementations which come with the block: Memory-mapped file Singleton object SQL Server 2000 database (comes with SQL script)Caching block: Caching block CacheService class Its job is to remove items when they expire Expiration can be determined by any class which implements ICacheItemExpiration The following come with the block: AbsoluteTime (expire at 1:30) ExtendedFormatTime (expire every hour) FileDependency (expire when file changes) SlidingTime (expire in 10 seconds)Caching block: Caching block Supports scavenging Process for removing items from the cache when resources become low To write your own class for this, simply implement the IScavengingAlgorithm interface The block comes with a default “scavenger” which uses a LRU algorithm Note: A CacheItem can optionally have a callback delegate for when it gets removed by the CacheService (via expiration or scavenging)Caching block: Caching block Checking cache obj = cacheManager.GetData(key); If (obj == null) { //not in cache, fetch it and add to cache obj = GetExpensiveObjectByKey(key); cacheManager.Add(key, obj); } obj.DoSomething(); Caching block: Caching block Setting an expiration on an item ICacheItemExpiration[2] exp; //expire item 8 hours from now exp[0] = new SlidingTime(new TimeSpan(8, 0, 0)); //or expire when file changes, whichever comes first exp[1] = new FileDependency(@"C:\MyData.xml"); cacheManager.GetItem(key).Expirations = exp; Resources: Resources Caching AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=853bb349-ebc1-44c1-b3be-9c72c49a000c User Interface Application Block: User Interface Application BlockUser interface process block: User interface process block Purpose: Decouple UI and navigation/workflow Maintain state between UI components and across processes Problems Solved: Navigation/workflow code bound to UI Extensibility issues with tightly coupled UI/workflow Platform independent model for Windows, Web and device applications UIP block implementation: UIP block implementation DALC DALC Biz Components Biz Components Data Access MyFunc() { //do cool code //more good stuff } Persistence Providers: - SQL Server - Encrypted SQL Server - Memory - ASP.NET Session - CustomA user interface process: A user interface process cart browsecatalog error checkout congrats addItem fail resume resume resume passCheckout failCheckout checkout failA user interface process: A user interface process cart browsecatalog error checkout congrats addItem fail resume resume resume passCheckout failCheckout checkout fail The UIP block uses XML config to manage flowPutting UIP to work: Putting UIP to work Starting the task… Driving the UIP manager…Putting it together: Putting it together Starting the task… Driving the UIP manager… Navigation and persisting state . . .Other things you may need: Other things you may need Support for multi-pane application by creating a ViewManager for Windows Controls CMAB for multi-process/multi-developer workResources: Resources Multi-pane example application http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=c92b944e-a7e7-434d-9dd4-5e0281145a73 User Interface AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=0af2b0ef-b049-401a-a2f2-f55a070c1572 Updater Application Block: Updater Application BlockUpdater block: Updater block Purpose: Update your application after it has been deployed. Uses a “pull” technique. No user interaction required Problems solved: Users don’t always know when to update the app manually or how Pushing updates using SMS scripts or group policies or login scripts is complicated and has a slow turn-around time Plus you have to go through the IT network administrators instead of doing it yourself Typical design of an updater block: Typical design of an updater block Update Controller Downloader Validator Post Processor (optional) Your Application User starts this Controller starts your app ServerAlternate design: Alternate design Downloader Validator Post Processor (optional) Server Your Application (also the Update Controller) User starts this DLL DLL DLL AppDomain using ShadowCopyUpdater block: Updater block The Downloader can be any class that implements the IDownloader interface There is one implementation that comes with the block: BITSDownloader - uses the Background Intelligent Transfer Service (BITS) to copy files Uses HTTP or HTTPS If download is interrupted, it continues from where it left off BITS only works on Windows 2000, XP and 2003 Note: A UNC downloader class implementation is listed in the help document.Updater block: Updater block The Validator can be any class that implements the IValidator interface There are two implementations that come with the block: KeyValidator - uses symmetric key Must ship password along with client RSAValidator – uses private/public keys This is more secure than KeyValidatorUpdater block: Updater block Also comes with: Sample AppStarter (the Update Controller) Manifest creation utility Updater block: Updater block Why should you use the updater block instead of simply downloading Windows Forms applications through a browser? Downloading WinForm applications through a browser runs the application within a security "sandbox.” Restricts you from Registry, File IO, etc. Some “browser download” applications require you to be connected to the server just to run Resources: Resources Updater AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=83c68646-befb-4586-ba9f-fdf1301902f5 Configuration Management Application Block: Configuration Management Application BlockConfiguration management application block (CMAB): Configuration management application block (CMAB) Purpose: Standard interface Read/Write of application configuration data with an independent data store Problems solved: Ability to write to configuration file Caching support Increased data security/integrity Supports complex in memory data structures CMAB implementation: CMAB implementation Your Application Application XML Configuration File (holds config for config) Configuration Storage Providers: - XML File - SQL Server - Registry - Custom Data Protection Providers: - DPAPI - BCL - Custom Configuration Section Handlers Configuration Section Handlers Configuration Section HandlersCMAB up and running: CMAB up and running In the app.config / web.config Define Configuration Section Handler Define Configuration Storage Provider Define Data Protection Provider Define Cache parametersCMAB configuration: CMAB configuration <configuration> <configSections> <section name="applicationConfigurationManagement" type=“MS.AppBlocks.CMAB" /> <section name="ApplConfig1" type=“MS.AppBlocks.CMAB.XmlHashtableSectionHandler" /> </configSections> <applicationConfigurationManagement > <configSection name="ApplConfig1"> <configCache enabled="true" refresh="1 * * * *" /> <configProvider assembly=“MS.AppBlocks.CMAB" type=“MS.AppBlocks.CMAB.Storage.XmlFileStorage” encrypted="false" /> <protectionProvider assembly=“MS.AppBlocks.CMAB" type=“MS.AppBlocks.CMAB.DataProtection.BCLDataProtection" </configSection> </applicationConfigurationManagement> </configuration>CMAB implementation: CMAB implementation //Create you own hash table for key/val pairs Hashtable values = new Hashtable(); // Pass it to the ConfigManager for writing ConfigurationManager.Write(values); // Now write items into that storage ConfigurationManager.Items["connStr"] = "MyCnStr"; Results in…Powerful custom configuration: Powerful custom configuration XmlSerializer Section Handler is not limited to: Key/Value pair Read only access Allows for serialization of object graphs for describing configuration //create your custom config class DBConfig dbc = new DBConfig("sblap","sbraun","password"); //persist to the config file ConfigurationManager.Write("XmlSerializer",dbc);Resources: Resources Xml Serialization Stack http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlserializationhierarchy.asp XML Serialization in the .NET Framework http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnexxml/html/xml01202003.asp Configuration Management AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=01875f69-9358-437b-a8ae-fa4bf2e3080f Aggregation Application Block: Aggregation Application BlockAggregation block: Aggregation block Purpose: Retrieve data from a provider (e.g. web service or database) without the caller knowing where data is coming from Allows you to fetch data from multiple providers and combine into one set Executes multiple provider calls simultaneously Problems solved: Sometimes changing the backend provider requires you to change the calling code Result is in XML so changing from 3 to 4 providers won’t necessarily change your calling codeAggregation block: Aggregation block Your Application Aggregation Request Config file Request Processor Service Agent 1 Service Agent 2 Service Agent 3 Web Service Web ServiceAggregation block: Aggregation block Your Application Aggregation Request Request object is constructed (including parameters) and passed into AggregationRequest Result is XMLDocument or DataSet formatted according to XSD Aggregation block: Aggregation block Request processor uses thread pool to run agents simultaneously Each agent can have a timeout - processor will kill the thread Write your own agents by implementing IServiceAgent interface Request Processor Service Agent 1 Service Agent 2 Service Agent 3 Web Service Web ServiceAggregation block: Aggregation block Config settings for Agents: <ServiceAgent SAID="YahooStocks"> <ClassName>MyAgents.YahooStocks</ClassName> <Transformation>YahooOutput.xslt</Transformation> </ServiceAgent> <ServiceAgent SAID="ETradeStocks"> <ClassName>MyAgents.ETradeStocks</ClassName> <Transformation>ETradeOutput.xslt</Transformation> </ServiceAgent>Aggregation block: Aggregation block Configuration settings for requests: <Request> <RequestType Type="GetStockQuotes"> <ServiceAgents> <SAID>YahooStocks</SAID> <SAID>ETradeStocks</SAID> </ServiceAgents> <TimeToLive>5</TimeToLive> <TransformationSchema>StockOutput.xsd</TransformationSchema> </RequestType>Resources: Resources Aggregation AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=005c405e-b892-44b0-a742-96ff286e3bd1 Asynchronous Management Application Block: Asynchronous Management Application BlockAsync invocation block: Async invocation block Purpose Simplify development of asynchronous operations in your system Improve responsiveness Streamline processing Problems solved Problem with high-latency synchronous processes Async invocation blocksupport components: Async invocation block support components ROHService Responsible for picking up requests from the database and invoking the appropriate service agent MonitorService Recovers service agent requests Garbage collects old requests Requires installation using the InstallUtil.exe utilityAsync invocation blockimplementation: Async invocation block implementation Create service agent classes and add entries to the database for each agent Create an AsyncBatchRequest object Call AddRequest() for each service agent, passing in any parameters Use AsyncRequestProcessor to submit the batch by calling SubmitRequest() Use ResultsManager to get request results Resources: Resources Asynchronous Management AB GotDotNet Workspace http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=1358f932-bba0-490e-968c-cd55281442c2 Other blocks: Other blocks Authorization/Profile Application Block Instrumentation Block (extension to Exception Management Block for WMI) Smart Client Offline Application BlockWhere to find blocks(besides Google): Where to find blocks (besides Google) Application Updater Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/updater.asp Asynchronous Invocation Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/paiblock.asp Caching Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/Cachingblock.asp Configuration Management Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/cmab.asp Data Access Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp Exception Management Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/emab-rm.asp Service Aggregation Application Block http://msdn.microsoft.com/library/en-us/dnpag/html/serviceagg.asp User Interface Process Application Block http://msdn.microsoft.com/library/en-us/dnbda/html/uip.asp