ASP.NET Best Practices Dawit Wubshet Park University.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

PHP Form and File Handling
23-Aug-14 HTML/XHTML Forms. 2 What are forms? is just another kind of XHTML/HTML tag Forms are used to create (rather primitive) GUIs on Web pages Usually.
24-Aug-14 HTML Forms. 2 What are forms? is just another kind of HTML tag HTML forms are used to create (rather primitive) GUIs on Web pages Usually the.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
The Web Warrior Guide to Web Design Technologies
Chapter 31 Basic Form-Processing Techniques JavaServer Pages By Xue Bai.
Road Map Introduction to object oriented programming. Classes
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
ASP.NET 2.0 Chapter 6 Securing the ASP.NET Application.
ASP.NET Programming with C# and SQL Server First Edition
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
Microsoft ® Official Course Monitoring and Troubleshooting Custom SharePoint Solutions SharePoint Practice Microsoft SharePoint 2013.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
CST JavaScript Validating Form Data with JavaScript.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
4-Sep-15 HTML Forms Mrs. Goins Web Design Class. Parts of a Web Form A Form is an area that can contain Form Control/Elements. Each piece of information.
1 CS 3870/CS 5870 Static and Dynamic Web Pages ASP.NET and IIS.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Enabling Advanced Net8 Features. Configuring Advanced Network Address and Connect Data Information.
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
JavaScript is a client-side scripting language. Programs run in the web browser on the client's computer. (PHP, in contrast, is a server-side scripting.
Web Programming: Client/Server Applications Server sends the web pages to the client. –built into Visual Studio for development purposes Client displays.
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Chapter 8 Cookies And Security JavaScript, Third Edition.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CIS 451: ASP.NET Objects Dr. Ralph D. Westfall January, 2009.
Tracing 1www.tech.findforinfo.com. Contents Why Tracing Why Tracing Tracing in ASP.NET Tracing in ASP.NET Page Level tracing Page Level tracing Application.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Christopher M. Pascucci Basic Structural Concepts of.NET Managing State & Scope.
ASP.NET OPTIMIZATION. Why Optimize? $$$ Whether you build applications for customers or not, enhanced applications save money.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
7 Chapter Seven Client-side Scripts. 7 Chapter Objectives Create HTML forms Learn about client-side scripting languages Create a client-side script using.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
The Problem of State. We will look at… Sometimes web development is just plain weird! Internet / World Wide Web Aspects of their operation The role of.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
ICM – API Server & Forms Gary Ratcliffe.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
ASP-2-1 SERVER AND CLIENT SIDE SCRITPING Colorado Technical University IT420 Tim Peterson.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
Text INTRODUCTION TO ASP.NET. InterComm Campaign Guidelines CONFIDENTIAL Simply Server side language Simplified page development model Modular, well-factored,
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Introduction to ASP.NET, Second Edition2 Chapter Objectives.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 5 Validating Form Data with JavaScript
Chapter 23 – ASP.NET Outline 23.1 Introduction NET Overview
ASP.NET 4.0 State Management Improvements – Deep Dive
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Tutorial 10 Programming with JavaScript
Active server pages (ASP.NET)
Pre-assessment Questions
Presentation transcript:

ASP.NET Best Practices Dawit Wubshet Park University

StringBuilder The StringBuilder class starts with a default initial capacity of 16. Strings less than the initial capacity are stored in the StringBuilder object. The initial capacity of the buffer can be set by using the following overloaded constructor: public StringBuilder (int capacity); For example: StringBuilder sb = new StringBuilder(2000);

StringBuilder Use StringBuilder when you need to concatenate strings multiple times. // using String and '+' to append String str = "Some Text"; for (... loop several times to build the string...) { str = str + " additional text "; } // using String and.Append method to append StringBuilder strBuilder = new StringBuilder("Some Text "); for (... loop several times to build the string...) { strBuilder.Append(" additional text "); }

StringBuilder Use StringBuilder when the number of appends is unknown. Code sample: for (int i=0; i< Results.Count; i++) { StringBuilder.Append (Results[i]); }

StringBuilder Treat StringBuilder as an accumulator or reusable buffer. Avoids the allocations of temporary strings during multiple append iterations. Some of the scenarios where this helps are as follows: Concatenating strings: You should always prefer the following approach to string concatenation when using StringBuilder. StringBuilder sb; sb.Append(str1); sb.Append(str2); Use the preceding code rather than the following. sb.Append(str1+str2);

StringBuilder Concatenating strings from various functions. Example: StringBuilder sb; sb.Append(f1(...)); sb.Append(f2(...)); sb.Append(f3(...)); The preceding code snippet results in temporary string allocations for the return values by the functions f1 (...), f2 (...), f3 (...). This can be avoided by following this approach: void f1( sb,...); void f2( sb,...); void f3( sb,...);

Round Trips to the Server Round trips to a server needs to be reduced by: Prevalidating data on the client-side. Use validation controls to implement client-side validation of user input. Example: Required. Required. Using AJAX, Javascript.

View State View state is turned on in ASP.NET by default. Disable view state if you do not need it. For example, you might not need view state because your page is output-only or because you explicitly reload data for each request. You do not need view state when the following conditions are true: ● Your page does not post back. ● You do not handle server control events. ● You repopulate controls with every page refresh.

View State Ways to disable view state at various levels: To disable view state for all applications on a Web server, configure the element in the Machine.config file as follows: To disable view state for a single control on a page, set the EnableViewState property of the control to false: //Run time yourControl.EnableViewState = false; //Design time To disable view state for a single page, use Page directive as follows:

Redirecting Between Pages Where possible, use the Server.Transfer method instead of the Response.Redirect method. If you need authentication and authorization checks during redirection, use Response.Redirect. When you use Response.Redirect, ensure you use the overloaded method that accepts a Boolean second parameter: Response.Redirect(“Adminlogin.aspx”, false); To transfer to pages in other applications, you must use Response.Redirect.

Resource Acquisition & Disposing Open critical, limited, and shared resources just before you need them, and release them as soon as you can. Critical, limited, and shared resources include resources such as database connections, network connections, and transactions. For example: conn.Open(); SqlCommand comm = new SqlCommand(“park_sp_GetAMember”, conn); Instead of: conn.Open(); restructureInput(); … SqlCommand comm = new SqlCommand(“park_sp_GetAMember”, conn);

Resource Acquisition & Disposing Use Try/Finally on disposable resources. To guarantee resources are cleaned up when an exception occurs, use a try/finally block. Close the resources in the finally clause: try { conn.Open();... } finally { if (null != conn) conn.close; }

Pages Trim your page size. Enable buffering. Ensure debug is set to false. Optimize expensive loops.

Pages To trim your page size, you can do one or all of the following: ● Use script includes for any static scripts in your page to enable the client to cache these scripts for subsequent requests: ● Remove characters such as tabs and spaces that create white space before you send a response to the client. // with white space hello world The following sample table does not contain white spaces. // without white space hello world

Pages If buffering is turned off, you can enable buffering by using the following methods: ● Enable buffering programmatically in a page. Response.BufferOutput = true; ● Enable buffering at the page level by using directive: ● Enable buffering at the application or computer level by using the element in the Web.config or Machine.config file:

Pages Ensure Debug is set to false: To set debug to false at the page level: When debug is set to true, the following occurs: ● Pages are not batch compiled. ● Pages do not time out. When a problem occurs, such as a problem with a Web service call, the Web server may start to queue requests and stop responding. ● Additional files are generated in the Temporary ASP.NET Files folder. ● The System.Diagnostics.DebuggableAttribute attribute is added to generated code. This causes the CLR to track extra information about generated code, and it also disables certain optimizations.

Iterating and Looping Avoid repetitive field or property access If you use data that is static for the duration of the loop, obtain it before the loop instead of repeatedly accessing a field or property. The following code shows a collection of orders being processed for a single customer. for ( int item = 0; item < Customer.Orders.Count ; item++ ){ CalculateTax ( Customer.State, Customer.Zip, Customer.Orders[item] ); } Instead: string state = Customer.State; string zip = Customer.Zip; int count = Customers.Orders.Count; for ( int item = 0; item < count ; item++ ) { CalculateTax (state, zip, Customer.Orders[item] ); }

Iterating and Looping Optimize or avoid expensive operations within loops Identify operations in your loop code that can be optimized. Look for code that causes boxing or allocations as a side effect. The following code causes side effect strings to be created for each pass through the loop. String str; Array arrOfStrings = GetStrings(); for(int i=0; i<10; i++) { str+= arrOfStrings[i]; } To avoid extra string allocations: StringBuilder sb = new StringBuilder(); Array arrOfStrings = GetStrings(); for(int i=0; i<10; i++) { sb.Append(arrOfStrings.GetValue(i)); }

Iterating and Looping Consider replacing recursion with looping since each recursive call adds data to the stack. Example: Array arr = GetArrayOfStrings(); int index = arr.Length-1; String finalStr= RecurStr(index); string RecurStr(int ind){ if (ind <= 0) return ""; else return (arr.GetValue(ind)+RecurStr(ind-1)); } Rewritten: string ConcString (Array array){ StringBuilder sb = new StringBuilder(); for (int i= array.Length; i>0; i--){ sb.Append(array.GetValue(i)); } return sb; }

Iterating and Looping Use for instead of foreach in performance-critical code paths since.NET uses an enumerator to provide enhanced navigation through arrays and collections. Instead of: for (int i=0; i<yourControl.Items.Count; i++){ …}Use: foreach (Control ctrl in yourControl) {…}

Additional Resources Microsoft Application Blocks: us/library/ms aspx FxCop: ASP.Net Analyzer: us/vstudio/aa aspx

Questions ???