Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore dev4dxc-coursebook (1)

dev4dxc-coursebook (1)

Published by assurance123, 2020-07-15 16:29:35

Description: dev4dxc-coursebook (1)

Search

Read the Text Version

Episerver – Developing for DXC Service Module C – Development Considerations – App Service environment How DXC Service automatically warm ups your site It will automatically warm up your site if you have not defined your own <applicationInitialization>. For each hostname bound to the site, it searches for all links on its start page, and automatically adds them to <applicationInitialization>. If you only add the <applicationInitialization> section to your Production environment through configuration transform, you can use the following technique to remove the automatic behaviour. <system.webServer xdt:Transform=\"InsertIfMissing\"> <applicationInitialization xdt:Transform=\"Remove\" /> <applicationInitialization xdt:Transform=\"InsertIfMissing\"> <add initializationPage=\"/\" hostName=\"www.example.com\" xdt:Transform=\"InsertIfMissing\" /> <add initializationPage=\"/about-us\" hostName=\"www.example.com\" xdt:Transform=\"InsertIfMissing\" /> Episerver Avoiding 500 errors during warm up using a “delay page” When DXC Service builds this section automatically during deployments for customers who don't do it by themselves, it adds an ASPX initialization page like the one shown below to give the server instance an extra 90 seconds before being released into production. This helps when a site responds with errors for whatever reason during warmup. This “delay page” is only available from localhost, so the delay behavior does not interfere with external requests. <%@ Page Language=\"C#\" AutoEventWireup=\"true\" %> <%@ Import Namespace=\"System.Net\" %> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <% if (Request.IsLocal) { var WarmupDelay = 90000; var qWarmupDelay = Request.QueryString[\"WarmupDelay\"]; if (!string.IsNullOrEmpty(qWarmupDelay)) { WarmupDelay = int.Parse(qWarmupDelay); } System.Threading.Thread.Sleep(WarmupDelay); Response.StatusCode = 200; this.Title = \"Delay finished\"; } else { this.Title = \"Page not found\"; Response.StatusCode = 404; } %> <html xmlns=\"http://www.w3.org/1999/xhtml\"> <head runat=\"server\"> <title><%=this.Title %></title> </head> <body> </body> </html> Copyright © 2019 Episerver. All rights reserved. Page 132

Episerver – Developing for DXC Service Module C – Development Considerations – App Service environment Use appSettings for environment configurations Sometimes you want to use a different configuration or code execution in different environments. For example, if you have an e-commerce site with payment provider methods that you do not want to run in a test environment. The name of the current environment is stored as an AppSetting so can easily be read dynamically in your code: ConfigurationManager.AppSettings[\"episerver:EnvironmentName\"] The string value will be one of: • Integration, • Preproduction, or • Production Episerver Defining a DXC application context public enum DxcEnvironment using EPiServer.ServiceLocation; { using System; using System.Configuration; Integration, Preproduction, Production } [ServiceConfiguration(Lifecycle = ServiceInstanceScope.Singleton)] public class DxcApplicationContext { private DxcEnvironment environment; public DxcApplicationContext() { var setting = ConfigurationManager.AppSettings.Get(\"episerver:EnvironmentName\"); if (!Enum.TryParse(setting, true, out environment)) { environment = DxcEnvironment.Integration; // default } } public DxcEnvironment CurrentEnvironment { get { return environment; } } } Copyright © 2019 Episerver. All rights reserved. Page 133

Episerver – Developing for DXC Service Module C – Development Considerations – App Service environment Configuring environment-specific payments and shipping To use specific payment gateways and shipping methods for environments in an Digital Commerce solution, create a method to filter payments or shipping options: public IEnumerable<ShippingMethodDto.ShippingMethodRow> FilterShippingMethods(ShippingMethodDto dto) { var environment = ServiceLocator.Current .GetInstance<DxcApplicationContext>().CurrentEnvironment; return dto.ShippingMethod.Select().Where(c => c[\"Name\"].ToString() .StartsWith(environment.ToString(), StringComparison.OrdinalIgnoreCase)) .Select(c => (ShippingMethodDto.ShippingMethodRow)c); } Currently, the best way to separate payment gateways and shipping methods is to use a specific prefix for their system names. For example, you can set Integration- for the payment gateways and shipping methods used in Integration, Preproduction- for Preproduction and so on. Episerver Copyright © 2019 Episerver. All rights reserved. Page 134

Episerver – Developing for DXC Service Module C – Development Considerations – App Service environment Disable session state When session state is enabled, ASP.NET queues up each request from the same visitor so that objects stored in Session are synched between each request. Leaving session state enabled will have an impact on performance, deployment and scalability, so the recommendation is to disable session state on controllers that do not need it. If you need to use session state with DXC-S, beware that autoscaling means that a server could be shutdown at any time and you will lose the session state on that server. Store session state in SQL Server to prevent losing state works but at a performance cost. With EPiServer.Cms.Core 11.9 or later, Visitor Group personalization will auto-detect that session state is disabled and switch to use cookies. This is extendable so that you can provide your own custom storage. [SessionState(SessionStateBehavior.Disabled)] Episerver <sessionState mode=\"Off\" /> 135 Sticky sessions aka server affinity App Service Web Apps use Application Request Routing IIS Extension to distribute your connecting users between your active instances serving up the content. ARR identifies the user by assigning them an affinity cookie, which allows the service to choose the right instance the user was using to serve subsequent requests made by that user. This means a client will keep talking to the same instance until their session expires. The cookie named ARRAffinity holds the ID of a VM instance. Changing the value of the cookie makes it possible for a request to be directed to a specific server instance through the Azure Load Balancer. Copyright © 2019 Episerver. All rights reserved. Page 135

Episerver – Developing for DXC Service Module C – Development Considerations – Data storage Checking the database mode Before attempting to execute code that writes to the database, it is especially important with cloud sites to check if the database is in read-only mode, because this can happen more often. Episerver has a dependency service that implements IDatabaseMode that can be used to check. public class StartPageController : PageControllerBase<StartPage> { private readonly DatabaseMode DatabaseMode; public StartPageController(IDatabaseMode db) { this.DatabaseMode = db.DatabaseMode; Episerver if (this.DatabaseMode == DatabaseMode.ReadWrite) { // write to database Copyright © 2019 Episerver. All rights reserved. Page 137

Episerver – Developing for DXC Service Module C – Development Considerations – Data storage Use DDS, a NoSQL data store, or SQL Server schemas for custom data Although we do allow custom tables in the Episerver database, we recommend using the Dynamic Data Store (DDS) or a NoSQL data store if you do not need relationships. For example, Episerver Forms currently uses DDS to store form submissions, but may switch to a NoSQL data store in the future for better performance. If you need to add new tables to the Episerver database then you should complete three steps: 1. Use an initialization module with a dependency on EPiServer.Web.InitializationModule. 2. Use a database schema migration library such as Fluent Migrator https://github.com/schambers/fluentmigrator or Entity Framework Code First Migrations https://msdn.microsoft.com/en-us/data/jj591621.aspx 3. Ensure the new database objects are created in a schema so that they do not conflict with other database object names. A database object in SQL Server is referenced with a four-part name: servername.databasename.schemaname.objectname. Episerver Copyright © 2019 Episerver. All rights reserved. Page 138

Episerver – Developing for DXC Service Module C – Development Considerations – Data storage NoSQL choices for data storage Technology Description Microsoft Azure Storage Table “A NoSQL key-value store for rapid development using massive semi-structured datasets.” PRO: fast for inserts. CON: slow for queries on non-primary key. Microsoft Azure Cosmos DB https://azure.microsoft.com/en-gb/services/storage/tables/ MongoDB “Blazing fast, planet-scale NoSQL,” that builds on the older Azure DocumentDB. RavenDB Apache https://azure.microsoft.com/en-gb/services/cosmos-db/ Cassandra “Building on the Best of Relational with the Innovations of NoSQL.” MongoDB is currently used in some Episerver products such as Social, and some internal tools. https://www.mongodb.com/ Popular in .NET world. https://ravendb.net/ “…the right choice when you need scalability and high availability without compromising performance.” http://cassandra.apache.org/ Episerver Copyright © 2019 Episerver. All rights reserved. Page 139

Episerver – Developing for DXC Service Module C – Development Considerations – Transient fault handling Use transient fault handling for resilience In a cloud environment, retry policies become increasingly important. Transient errors may occur as infrastructure elements are replaced, and retry policies allow the application to recover from such errors without propagating the error to the end user. Microsoft Azure SDKs for BLOBs, Service Bus, and Entity Framework has a built-in implementation for transient faults handling and retry policies: http://www.asp.net/aspnet/overview/developing-apps-with- windows-azure/building-real-world-cloud-apps-with- windows-azure/transient-fault-handling Episerver Set an appropriate retry policy Retry mechanisms differ because each service has different characteristics and requirements, and so each retry mechanism is tuned to a specific service. For example, with Azure Storage you can specify a fall back geolocation as well as a retry policy: var options = new TableRequestOptions { RetryPolicy = new LinearRetry(TimeSpan.FromMilliseconds(500), 3), LocationMode = LocationMode.PrimaryThenSecondary, MaximumExecutionTime = TimeSpan.FromSeconds(2) }; Retry general and specific guidance https://azure.microsoft.com/en-gb/documentation/articles/best-practices-retry-general/ https://azure.microsoft.com/en-gb/documentation/articles/best-practices-retry-service-specific/ Copyright © 2019 Episerver. All rights reserved. Page 141

Episerver – Developing for DXC Service Module C – Development Considerations – Transient fault handling Microsoft’s Entity Framework transient fault handling With the rise of cloud-based database servers such as Azure SQL Database and connections over less reliable networks it is now more common for connection breaks to occur. This could be due to defensive techniques that cloud databases use to ensure fairness of service, such as connection throttling, or to instability in the network. To tell EF to use an execution strategy, call SetExecutionStrategy() in a DbConfiguration-derived class that is set in your configuration file: Episerver public class MembershipConfiguration : DbConfiguration { public MembershipConfiguration() { SetExecutionStrategy(\"System.Data.SqlClient\", () => new SqlAzureExecutionStrategy(maxRetryCount: 3, maxDelay: TimeSpan.FromSeconds(30))); Copyright © 2019 Episerver. All rights reserved. Page 142

Episerver – Developing for DXC Service Module C – Development Considerations – Transient fault handling Microsoft’s Transient Fault Handling Application Block For code without a built-in implementation, use Microsoft’s Transient Fault Handling Application Block: https://msdn.microsoft.com/en- us/library/dn440719(v=pandp.60).aspx At the Package Manager Console: Install-Package EnterpriseLibrary.TransientFaultHandling Episerver Copyright © 2019 Episerver. All rights reserved. Page 143

Episerver – Developing for DXC Service Module C – Development Considerations – Cloud design patterns Cloud design patterns from Microsoft’s patterns & practices Microsoft’s patterns & practices group have created a guide containing twenty-four design patterns and ten related guidance topics. This guide articulates the benefit of applying patterns by showing how each piece can fit into the big picture of cloud application architectures. It also discusses the benefits and considerations for each pattern. You will find code samples or snippets that show how to implement the patterns using the features of Microsoft Azure here: https://docs.microsoft.com/en-us/azure/architecture/patterns/ Episerver Azure Architecture Center https://docs.microsoft.com/en-us/azure/architecture/ Copyright © 2019 Episerver. All rights reserved. Page 145

Episerver – Developing for DXC Service Module C – Development Considerations – Cloud design patterns Queue-based cloud patterns to enable “zero downtime” Competing Consumers Pattern Multiple concurrent consumers process messages received on the same messaging channel. This enables a system to process multiple messages concurrently to optimize throughput, to improve scalability and availability, and to balance the workload. https://docs.microsoft.com/en-us/azure/architecture/patterns/competing-consumers Load Levelling Pattern Use a queue that acts as a buffer between a task and a service that it invokes in order to smooth intermittent heavy loads that may otherwise cause the service to fail or the task to time out. https://docs.microsoft.com/en-us/azure/architecture/patterns/queue-based-load- leveling Episerver Copyright © 2019 Episerver. All rights reserved. Page 146

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage Integrating Azure Storage Azure Storage (500TB per account, 100 accounts). • Table: schema-less entities (<1MB each), table (unlimited). • Blob: block for media (<200GB each) or page for VHDs (<1TB). • Queue: message exchange (<64KB each). • Files: permanent file system using SMB protocol (but cannot be used with App service, VMs and Cloud Services only). You can monitor your storage account from the Azure Portal. When you configure your storage account for monitoring through the portal, Azure Storage uses Storage Analytics to track metrics for your account and log request data. https://azure.microsoft.com/en-gb/documentation/articles/storage-monitor-storage-account/ Episerver Replication Choices for Azure Storage • Locally Redundant and Premium Locally Redundant replicate in the same data center. • Zone Redundant replicates in a secondary data center within the same region (if possible). • Geo-Redundant replicates in a secondary region. • Read-Access Geo-Redundant replicates in a secondary region; the replicas can be read from for extra scale. The secondary Read-Access endpoint is similar to the primary endpoint, but appends the suffix – secondary to the account name. Copyright © 2019 Episerver. All rights reserved. Page 148

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage Configure the Azure Storage account key and install the NuGet package Copy and paste your Azure Storage account key into a configuration file: <add key=\"StorageConnectionString\" value=\"DefaultEndpointsProtocol=https;AccountName=storagesample; AccountKey=nYV0gln9...==\" /> Or configure to use local storage: <add key=\"StorageConnectionString\" value=\"UseDevelopmentStorage=true;\" /> Install the NuGet package for the Azure Storage API. If you have installed EPiServer.Azure then this is already done because it is a dependency of our NuGet package: Install-Package –ProjectName DxcAlloy WindowsAzure.Storage Episerver Copyright © 2019 Episerver. All rights reserved. Page 149

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage Get a reference to the storage account • Use the local development account for debugging and testing: #if DEBUG var account = CloudStorageAccount.DevelopmentStorageAccount; #endif • Parse the Azure Storage account connection string from .config or .cscfg file for production: #if !DEBUG var account = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting(\"StorageConnectionString\")); #endif Alternatively, you could use Web.config transformations and always parse the connection string. Episerver Copyright © 2019 Episerver. All rights reserved. Page 150

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage – Queues Integrating Azure Storage queues using Microsoft.WindowsAzure.Storage.Queue; Queues provide reliable, low latency, high-throughput messaging that enable you to decouple your application components. For example, a Web App could put a message in an Azure Storage Queue indicating a Blob or Entity to process. A WebJob or Azure Function can process the message. This makes it possible for the application components to scale independently. https://azure.microsoft.com/en-gb/documentation/articles/storage-dotnet-how-to-use-queues/ var qclient = account.CreateCloudQueueClient(); // retrieve up to 32 messages var queue = qclient.GetQueueReference(\"muppets\"); IEnumerable<CloudQueueMessage> queue.CreateIfNotExists(); messages = queue.GetMessages(3); var msg1 = new CloudQueueMessage(\"kermit\"); queue.AddMessage(msg1); Console.WriteLine(queue.ApproximateMessageCount); var msg2 = queue.GetMessage(); Console.WriteLine(msg2.AsString); Episerver Copyright © 2019 Episerver. All rights reserved. Page 152

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage – Queues using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.RetryPolicies; Processing Azure Storage queue messages A message added to a queue expires after seven days unless an explicit time-to-live is set. var message = new CloudQueueMessage(\"kermit\"); queue.AddMessage(message, initialVisibilityDelay: TimeSpan.FromSeconds(0), timeToLive: TimeSpan.FromDays(1), // from 1 second up to 7 days options: new QueueRequestOptions { LocationMode = LocationMode.PrimaryThenSecondary }); When you dequeue a message using GetMessage() the message is invisible for 30 seconds by default. var message = queue.GetMessage(visibilityTimeout: TimeSpan.FromSeconds(30)); // process message and then delete it queue.DeleteMessage(message); Episerver Copyright © 2019 Episerver. All rights reserved. Page 153

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage – Tables Integrating Azure Storage Tables Azure Storage Tables are not suitable for general storage because they do not have secondary indexes. • Its write capabilities scale very, very well, which is why Microsoft uses them for logging. • Its querying and indexing capabilities are astonishingly limited. Entities must have three properties • PartitionKey, RowKey: both are strings of up to 1024 bytes (therefore about 500 characters). • Timestamp: DateTimeOffset includes time zone (can be auto-created but then you won’t be able to get the value assigned). Recommendation: Inherit from TableEntity or implement ITableEntity. Entities can only use the following types: • char, string, int, long, double, DateTime, byte[], bool, Guid Episerver Defining Azure Storage Table entities You can use [IgnoreProperty] and code a property to read/write from the PartitionKey/RowKey. public class Employee : TableEntity { public Employee(string department, string code) : base(department, code) { } [IgnoreProperty] public string Department { get { return PartitionKey; } set { PartitionKey = value; } } [IgnoreProperty] public string EmployeeCode { get { return RowKey; } set { RowKey = value; } } public string FirstName { get; set; } public string LastName { get; set; } public DateTime Hired { get; set; } } Copyright © 2019 Episerver. All rights reserved. Page 155

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage – Tables Inserting a single entity into a Storage Table To get a table: var tableClient = account.CreateCloudTableClient(); var table = tableClient.GetTableReference(\"employees\"); table.CreateIfNotExists(); To insert a single entity: Employee first = new Employee { PartitionKey = \"IT\", RowKey = \"ibahena\", YearsAtCompany = 7 }; TableOperation insertOperation = TableOperation.InsertOrReplace(first); table.Execute(insertOperation); Episerver Inserting batches of entities into a Storage Table To insert a batch of entities in a transaction, batches must be on the same partition and are limited to a maximum of 4 MB. Employee second = new Employee { PartitionKey = \"HR\", RowKey = \"rreeves\", YearsAtCompany = 12 }; Employee third = new Employee { PartitionKey = \"HR\", RowKey = \"rromani\", YearsAtCompany = 3 }; TableBatchOperation batchOperation = new TableBatchOperation(); batchOperation.InsertOrReplace(second); batchOperation.InsertOrReplace(third); table.ExecuteBatch(batchOperation); Copyright © 2019 Episerver. All rights reserved. Page 156

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating Azure Storage – Tables Retrieving entities from a Storage Table To retrieve a single entity TableOperation retrieveOp = TableOperation.Retrieve<Employee>(\"IT\", \"ibahena\"); TableResult result = table.Execute(retrieveOp); Employee itEmployee = (Employee)result.Result; To retrieve multiple entities (querying on non-key columns performs a table scan!) string queryFilter = TableQuery.GenerateFilterCondition( \"PartitionKey\", QueryComparisons.Equal, \"HR\"); // => \"PartitionKey eq 'HR'\" TableQuery<Employee> query = new TableQuery<Employee>().Where(queryFilter); foreach (Employee hrEmployee in table.ExecuteQuery<Employee>(query)) { Console.WriteLine(hrEmployee); } Episerver Copyright © 2019 Episerver. All rights reserved. Page 157

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating other Azure services Integrating Azure compute Microsoft Azure has four main options for executing code aka compute: • Virtual Machine, e.g. Windows or Linux • App service, e.g. app platforms • Service Fabric Cluster • Function App See the Notes section for a detailed comparison table. Episerver Feature or Benefit Virtual Machine App Service Service Fabric Function App Remote debugging ✓ ✓  ✓ Remote Desktop (RDP) ✓  ✓  Server startup tasks ✓  ✓  Auto-patch OS  ✓ ASP.NET built-in  Soon Soon Python/PHP/Node built-in  4.7/.NET Core   Install other platforms ✓ ✓  ✓ Web front-end ✓  ✓  Background processing ✓   Event-based triggers  Web App ✓ ✓ Side-by-side versions  WebJob  ✓ …as-a-Service ✓ ✓ Best for… Host (Server) ✓ Custom IaaS  Service Function IIS Clustered micro services Nano services Most PaaS scenarios Copyright © 2019 Episerver. All rights reserved. Page 159

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating other Azure services Azure pricing calculator and monitoring usage and costs If you choose to use additional Azure services beyond those included in DXC Service, then those will incur a charge from Microsoft. There is a useful pricing calculator for estimating cost: https://azure.microsoft.com/en-gb/pricing/calculator/ Episerver Monitoring usage and costs You can easily monitor costs by adding subscription panes to your Azure Dashboard. As you can see, when trying our Episerver CMS in Azure Marketplace, you can choose deployment options that give a free App service to host the code and a free tier of SQL database to store the content. Copyright © 2019 Episerver. All rights reserved. Page 160

Episerver – Developing for DXC Service Module C – Development Considerations – Integrating other Azure services Learning more about Azure services Microsoft Azure changes so fast that printed material are usually out-of-date. Read about Azure products and services: https://azure.microsoft.com/en-us/services/ You can download free e-books from Microsoft Virtual Academy: https://mva.microsoft.com/ebooks Episerver Microsoft guidance on building cloud apps Developers who are curious about developing for the cloud, are considering a move to the cloud, or are new to cloud development will find here a concise overview of the most important concepts and practices they need to know. The concepts are illustrated with concrete examples, and each chapter includes links to other resources that provide more in-depth information. The examples and the links to additional resources are for Microsoft frameworks and services, but the principles illustrated apply to other web development frameworks and cloud environments as well. https://blogs.msdn.microsoft.com/microsoft_press/2014/07/23/free-ebook- building-cloud-apps-with-microsoft-azure/ Microsoft Azure certification and training If you would like to become certified on Microsoft Azure, they have multiple Azure-related certifications that you can earn. https://www.microsoft.com/en-gb/learning/azure-certification.aspx Free online Azure training on Microsoft Virtual Academy. https://mva.microsoft.com/product-training/microsoft-azure Free online Azure training on edX. https://www.edx.org/school/microsoft Copyright © 2019 Episerver. All rights reserved. Page 161

Episerver – Developing for DXC Service Module C – Development Considerations Exercises for Module C (120 mins) Add code to the Alloy (MVC) sample site that demostrates good practice and cloud design patterns. Each is independent so you can complete them in any order. 1. Async (30 mins): async in a page controller. 2. Caching (30 mins): set cache-control headers. 3. Transient fault handling (30 mins): configure EF to handle transient faults and write code to handle an unreliable component. 4. Queue-based patterns (30 mins): implement a queue-based processing system to improve load scalability and provide ”zero downtime”. Episerver Copyright © 2019 Episerver. All rights reserved. Page 162

Episerver – Developing for DXC Service Developing for DXC Service Course Summary In this module, we will review what you learned and point you to additional resources for further learning. Episerver Copyright © 2019 Episerver. All rights reserved. Page 167

Episerver – Developing for DXC Service Developing for DXC Service – Course Summary What did you learn? • Introduction About the course. Prepare an Alloy (MVC) site and your Integration environment. • Module A: About DXC Service What is DXC Service? Package choices. Microsoft Azure services we use. Security features. • Module B: Deploying to DXC Service Deployment environments and technologies. Web.config transformations. Continuous integration. • Module C: Development Considerations Multi-sites. Caching. Controlling the environment. Transient fault handling. Queue design patterns. WARNING! Delete the Resource Group that you created to ensure that you will no longer be charged for the resources within it. Episerver Copyright © 2019 Episerver. All rights reserved. Page 168

Episerver – Developing for DXC Service Episerver Copyright © 2019 Episerver. All rights reserved. Page 169

Episerver – Developing for DXC Service Thank you! You will receive a email after the course asking for feedback. You will only receive your Certificate of Completion if you fill it in! Episerver Copyright © 2019 Episerver. All rights reserved. Page 170


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook