30 Jul 2011

Using SAP Connector in .NET

Introduction
The SAP .Net Connector is a software component supplied by SAP that makes it possible to communicate between an SAP host and a .Net program. Any .Net language can be used with the SAP .Net Connector.
Where to Find It
You can download the SAP .Net Connector from http://service.sap.com/connectors. You will have to provide your SAP Marketplace user ID and password.
What it Does
The SAP .Net Connector gives a .Net program access to an SAP host. The .Net program can logon to an SAP host and issue SAP Remote Function Calls. Parameters can be passed in to an RFC, and results data can be passed back to the .Net program.
A .Net program can also establish a connection to an SAP IDOC Gateway. The .Net program uses the SAP .Net Connector to send and receive IDOCs. There is full support for transactional integrity for IDOCS moving back and forth between the SAP host and the .Net program.
With this functionality, a Microsoft .Net program has all that it needs to query SAP metadata, call ABAP functions, or send and receive IDOCs.
What it Doesn’t Do
While the SAP .Net Connector takes care of most of the heavy lifting in communicating with an SAP host, there is still considerable work to be done before you can get something useful from it.
In particular, there is no functionality built-in to the SAP .Net Connector for parsing the various data fields from an IDOC. It is up to the receiving program to know what the format of the IDOC is, and how to extract the data from the IDOC.
One other issue to deal with is that the SAP .Net Connector is built for Visual Studio 2003. There is a work around that is easy to use that enables you to use the SAP .Net Connector with newer versions of Visual Studio.

--------------------------------------------------------------------------------------------------------------

Introduction

We will use Visual Studio 2003 and create a Dynamic Link Library (DLL) that encapsulates the desired SAP .Net Connector functionality. We can use the DLL that we create in a Visual Studio 2008 project.
To illustrate the process, we will build up, over the course of several blog posts, a system that is capable of receiving an IDOC from an SAP host. This system will be known as the Three Letter Acronym system, or TLA.

Build an SAP Proxy

Our first task is to use the SAP .Net Connector to build a proxy that we can incorporate into Visual Studio 2008 projects.
The approach is to first add the SAP .Net Connector to a Visual Studio 2003 project. Then, we will attach to an SAP host to browse available functions. We will select the desired functions to be included in our SAP proxy.
Then, we will build the VS 2003 project into a DLL that can be used in Visual Studio 2008.

Start a Visual Studio 2003 Project

After you have installed the SAP .Net Connector, start a new Visual Studio for .Net 2003 project. Name the project “TlaSapProxy.” Choose the “Class Library” C# template.
Creating a new SAP Proxy project
Creating a new SAP Proxy project
We don’t need the default Class1.cs file that is created, so close the Class1.cs module that is displayed, and remove Class1.cs from the TlaSapProxy project.

Add a Reference to the SAP .Net Connector

Now we need to add a reference to the SAP .Net Connector. From the Solution Explorer view, expand TlaSapProxy / References. Right click on References and choose Add Reference. From the .Net tab, double-click both SAP.Connector.dll and SAP.Connector.Rfc. Click OK to add the reference to your project.
Adding References to SAP .Net Connector
Adding References to SAP .Net Connector

Establish a Connection to an SAP Host

We will use the Visual Studio design time environment to attach to an SAP Host. From the Visual Studio View menu, select Server Explorer. Expand the SAP node. Right click on Application Servers and select Add Application Server.
For Destination Type, select Custom Logon Settings from the drop down list. Enter a valid SAP Username, Client, and Password. For the AppServerHost, enter the SAP host name, or the IP address of the desired SAP host. Be sure to fill in the Language field.
SAP Server Connection Properties
SAP Server Connection Properties
If things go well, at this point you will have an SAP Application Server established. You should see two new nodes on the Server Explorer display: BOR and Functions. Under BOR, you can expand either the Alphabetical or Hierarchical nodes to see available object definitions.

Browse SAP Functions

To display an SAP function using the Server Explorer, you have to create a function ‘filter,’ which selects which functions from the SAP Host you want to display. To do this, right click on Functions and choose Add Function Filter. In our proxy, we are going to be using some RFC functions, so, in the NameFilter field, enter RFC* (the asterisk is a wild card). Click OK, then expand Functions, then expand Filter1. After a moment, the screen will display a list of SAP functions that match our filter.
Creating a New Function Filter
Creating a New Function Filter
SAP Function Filter Display
SAP Function Filter Display

Select Desired SAP Functions

As you can see, there are many functions to choose from. When we build our SAP proxy, we will select just the functions we need.
For our TLA SAP Proxy we are building, we only need RFC_GET_SYSTEM_INFO. As with most SAP functions, RFC_GET_SYSTEM_INFO returns an object of a custom type that includes all of the results of the function call.
From the Visual Studio 2003 Solution Explorer, right click on the TlaSapProxy project and choose Add, then Add New Item. Scroll through the list of Templates and click on SAP Connector Proxy, then click OK to add the new item to the project.
Adding an SAP Connector Proxy Object
Adding an SAP Connector Proxy Object
What you have at that point is a Visual Studio design surface to which we can add SAP function definitions. The design surface is displayed as SAPProxy1.sapwsdl. We are basically creating a WSDL file that will be used to generate our desired DLL.
Adding SAP Functions to a Proxy
Adding SAP Functions to a Proxy
To include an SAP function, in our case RFC_GET_SYSTEM_INFO, display the Server Explorer. Expand the SAP Application Servers to the desired server, then click on RFC_GET_SYSTEM_INFO. Drag RFC_GET_SYSTEM_INFO to the SAPProxy1.sapwsdl and drop it there.
The screen will display ‘Retrieve Data.’ When it is done, you will see two things added to the WSDL. First is the function call definition (method). Second is a class definition for what is returned from the function. You can right click on these and select Properties to view details of what is contained therein.

Building the Project

Now that we have selected all of the desired SAP functions that we want to include in our proxy, we are ready to build the project.
Because we selected a Class Library as our starting project template, our project is already set to build a class module (DLL). To build the DLL, right click on the TlaSapProxy project and select Build.
This will compile our WSDL file into a DLL file that we will be able to use in Visual Studio 2008.

Summary

The SAP .Net Connector is built for Visual Studio 2003. By using Visual Studio 2003 to create a DLL, we can use the SAP .Net Connector in Visual Studio 2008 (or later).
We do this by establishing a connection to an SAP host, selecting the desired functions, and creating an SAP proxy object that contains the desired functions. When we build this project, the resulting DLL can be used in Visual Studio 2008.

--------------------------------------------------------------------------------------------------------------


Introduction

Our previous post described how to use Visual Studio 2003 and the SAP .Net Connector to create a Dynamic Link Library containing the desired SAP functionality. The DLL contains proxies for each SAP function that we want to utilize.
We will reference that DLL in a Visual Studio 2008, and use it to retrieve system information from an SAP host.
As a demonstration, we are creating the TLA System, which exists solely to demonstrate certain SAP .Net Connector programming techniques.

Using the SAP .Net Connector Proxy

Now we are ready to put our SAP .Net Connector Proxy to work. This will allow us to use the SAP .Net Connector in the modern Visual Studio environment.

Start a Visual Studio 2008 Project

Start a new Visual Studio 2008 Project. Use the Console Application template, and name the solution TlaSapRfcClient.
Creating a new console application
Creating a new console application

Add a Reference to the TLA SAP Proxy

Now we need to add a reference to the DLL we created earlier.
In the Solution Explorer, right click References and choose Add Reference. Using the Browse tab, find the TlaSapProxy.dll file from the TlaSapProxy project. Typically, this will be in the bin\debug folder of the TlaSapProxy folder. Click the OK button to add the reference to your project.
Adding a reference to the proxy
Adding a reference to the proxy

C# Code

Here is a Visual Studio 2008 C# program that uses the SAP .Net Connector proxy that we built earlier using Visual Studio 2003.
C# program listing
C# program listing
When we create an instance of the proxy in line 11, we pass in an SAP connection string. We create an object of type SAPProxy1 because that is what we named it in our Visual Studio 2003 project.
In line 20, we create an object of type RFCSI, because that is what our RFC call to Rfc_Get_System_Info will return. The type definition for RFCSI was also included in the proxy.
In line 22 we make the RFC call to the SAP host. We get full IntelliSense support that describes the parameters required.

Summary

The SAP .Net Connector is built for Visual Studio 2003. By using Visual Studio 2003 to create a DLL, we can use the SAP .Net Connector in Visual Studio 2008 (or later).
Here we have described how to use that DLL in a Visual Studio 2008 project.

SQL SERVER – 2008 – Configure Database Mail – Send Email From SQL Database

In order to send mail using Database Mail in SQL Server, there are 3 basic steps that need to be carried out. 1) Create Profile and Account 2) Configure Email 3) Send Email.
Step 1) Create Profile and Account:
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings which are shown below:
Step 2) Configure Email:
After the Account and the Profile are created successfully, we need to configure the Database Mail. To configure it, we need to enable the Database Mail XPs parameter through the sp_configure stored procedure, as shown here:
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
Step 3) Send Email:
After all configurations are done, we are now ready to send an email. To send mail, we need to execute a stored procedure sp_send_dbmail and provide the required parameters as shown below:
USE msdb
GO
EXEC sp_send_dbmail @profile_name='PinalProfile',
@recipients='test@Example.com',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
After all validations of the parameters entered are done, certain stored procedures are executed and the mail is queued by Service Broker, read more at SQL SERVER – Introduction to Service Broker.
Database Mail keeps copies of outgoing e-mail messages and displays them in the sysmail_allitems, sysmail_sentitems, sysmail_unsentitems, sysmail_faileditems . The status of the mail sent can be seen in sysmail_mailitems table, when the mail is sent successfully the sent_status field of the sysmail_mailitems table is set to 1 which can again be seen in sysmail_sentitems table. The mails that are failed will have the sent_status field  value to 2 and those are unsent will have value 3.
The log can be checked in sysmail_log table as shown below:
SELECT *
FROM sysmail_mailitems
GO
SELECT *
FROM sysmail_log
GO
Status can be verified using sysmail_sentitems table.
After sending mail you can check the mail received in your inbox

29 Jul 2011

Getting SQL Server 2008 Database Schema

SELECT i_s.TABLE_NAME AS [Table Name], i_s.COLUMN_NAME AS [Column Name], i_s.DATA_TYPE AS [Data Type],
isnull(isnull(i_s.CHARACTER_MAXIMUM_LENGTH,i_s.NUMERIC_PRECISION),'') AS [Max Length], isnull(s.value,'') AS Description
FROM INFORMATION_SCHEMA.COLUMNS AS i_s LEFT OUTER JOIN
sys.extended_properties AS s ON s.major_id = OBJECT_ID(i_s.TABLE_SCHEMA + '.' + i_s.TABLE_NAME) AND
s.minor_id = i_s.ORDINAL_POSITION AND s.name = 'MS_Description'
WHERE (OBJECTPROPERTY(OBJECT_ID(i_s.TABLE_SCHEMA + '.' + i_s.TABLE_NAME), 'IsMsShipped') = 0) AND (i_s.TABLE_NAME = 'mroutes')
ORDER BY [Table Name], i_s.ORDINAL_POSITION

25 Jul 2011

Showing update progress when using AsyncPostbackTrigger of UpdatePanel

<script type="text/javascript" language="javascript">
<!--
var prm = Sys.WebForms.PageRequestManager.getInstance();
var postBackElement;
function CancelAsyncPostBack() {
  if (prm.get_isInAsyncPostBack()) {
    prm.abortPostBack();
  }
}
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

function InitializeRequest(sender, args) {
  if (prm.get_isInAsyncPostBack()) {
      args.set_cancel(true);
  }
  postBackElement = args.get_postBackElement();
  if (postBackElement.id == 'Button1') {
    $get('UpdateProgress1').style.display = 'block';
  }
}
function EndRequest(sender, args) {
  if (postBackElement.id == 'Button1') {
    $get('UpdateProgress1').style.display = 'none';
  }
}
// -->
</script>

22 Jul 2011

SQL String Functions

Example SQL String Function - ASCII
- Returns the ASCII code value of a keyboard button and the rest etc (@,R,9,*) .
Syntax - ASCII ( character)SELECT ASCII('a') -- Value = 97
SELECT ASCII('b') -- Value = 98
SELECT ASCII('c') -- Value = 99
SELECT ASCII('A') -- Value = 65
SELECT ASCII('B') -- Value = 66
SELECT ASCII('C') -- Value = 67
SELECT ASCII('1') -- Value = 49
SELECT ASCII('2') -- Value = 50
SELECT ASCII('3') -- Value = 51
SELECT ASCII('4') -- Value = 52
SELECT ASCII('5') -- Value = 53



Example SQL String Function - SPACE
-Returns spaces in your SQL query (you can specific the size of space).
Syntax - SPACE ( integer)
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')
-- Value = SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')
-- Value = SQL TUTORIALS



Example SQL String Function - CHARINDEX
-Returns the starting position of a character string.
Syntax - CHARINDEX ( string1, string2 [ , start_location ] )
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial')

-- Value = 27SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20)
-- Value = 27SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)
-- Value = 0 (Because the index is count from 30 and above)


Example SQL String Function - REPLACE
-Replaces all occurrences of the string2 in the string1 with string3.
Syntax - REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')
-- Value = SQL Function


Example SQL String Function - QUOTENAME
-Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax - QUOTENAME ( 'string' [ , 'quote_character' ] )
SELECT QUOTENAME('Sql[]String')
-- Value = [Sql[]]String]


Example SQL String Function - STUFF
- Deletes a specified length of characters and inserts string at a specified starting index.
Syntax - STUFF ( string1 , startindex , length , string2 )

SELECT STUFF('SqlTutorial', 4, 6, 'Function')
-- Value = SqlFunctional
SELECT STUFF('GoodMorning', 5, 3, 'good')
-- Value = Goodgoodning


Example SQL String Function - LEFT
-Returns left part of a string with the specified number of characters.
Syntax - LEFT ( string , integer)
SELECT LEFT('TravelYourself', 6)
-- Value = Travel
SELECT LEFT('BeautyCentury',6)
-- Value = Beauty


Example SQL String Function - RIGHT
-Returns right part of a string with the specified number of characters.
Syntax - RIGHT( string , integer)
SELECT RIGHT('TravelYourself', 6)-- Value = urself
SELECT RIGHT('BeautyCentury',6)-- Value =
Century


Example SQL String Function - REPLICATE
-Repeats string for a specified number of times.

Syntax - REPLICATE (string, integer)SELECT REPLICATE('Sql', 2)
-- Value = SqlSql


Example SQL String Function - SUBSTRING
-Returns part of a string.

Syntax - SUBSTRING ( string, startindex , length )
SELECT SUBSTRING('SQLServer', 4, 3)

-- Value = Ser


Example SQL String Function - LEN
-Returns number of characters in a string.
Syntax - LEN( string)
SELECT LEN('SQLServer')
-- Value =
9


Example SQL String Function - REVERSE
-Returns reverse a string.Syntax - REVERSE( string)SELECT REVERSE('SQLServer')

-- Value = revreSLQS


Example SQL String Function - UNICODE
-Returns Unicode standard integer value.
Syntax - UNICODE( char)
SELECT UNICODE('SqlServer')
-- Value = 83 (it take first character)
SELECT UNICODE('S')
-- Value =
83


Example SQL String Function - LOWER
-Convert string to lowercase.Syntax - LOWER( string )SELECT LOWER('SQLServer')

-- Value = sqlserver


Example SQL String Function - UPPER
-Convert string to Uppercase.
Syntax - UPPER( string )
SELECT UPPER('sqlserver')
-- Value = SQLSERVER


Example SQL String Function - LTRIM
-Returns a string after removing leading blanks on Left side.
Syntax - LTRIM( string )SELECT LTRIM(' sqlserver')-- Value = 'sqlserver' (Remove left side space or blanks)



Example SQL String Function - RTRIM
-Returns a string after removing leading blanks on Right side.

Syntax - RTRIM( string )SELECT RTRIM('SqlServer ')
-- Value = 'SqlServer' (Remove right side space or blanks)

19 Jul 2011

Devx AspxGridView Html Row Created Event

If e.RowType = DevExpress.Web.ASPxGridView.GridViewRowType.Group Then
            Dim myText As Label = gvMenu.FindGroupRowTemplateControl(e.VisibleIndex, "Label1")
            Dim myLB As HyperLink = gvMenu.FindGroupRowTemplateControl(e.VisibleIndex, "hlAdd")

            If gvMenu.GetRowLevel(e.VisibleIndex) = 0 Then

                myText.Text = gvMenu.GetRowValues(e.VisibleIndex, "HR_MenuDesc")

                Dim hlEdit As HyperLink = gvMenu.FindGroupRowTemplateControl(e.VisibleIndex, "hlEdit")
                hlEdit.NavigateUrl = "frmEdit_Menu.aspx?" & Encryption.Base64Encryption("MenuId$" & gvMenu.GetRowValues(e.VisibleIndex, "KeyValue").ToString.Split("|")(0))

                If gvMenu.GetRowValues(e.VisibleIndex, "HR_URL") <> "" Then
                    myLB.Visible = False
                    e.Row.Cells(0).Controls(0).Visible = False
                Else
                    myLB.NavigateUrl = "frmEdit_Menu.aspx?" & Encryption.Base64Encryption("MenuId$" & gvMenu.GetRowValues(e.VisibleIndex, "KeyValue").ToString.Split("|")(0))
                End If

            ElseIf gvMenu.GetRowLevel(e.VisibleIndex) = 1 Then

                myText.Text = gvMenu.GetRowValues(e.VisibleIndex, "SM_Desc")

                Dim hlEdit As HyperLink = gvMenu.FindGroupRowTemplateControl(e.VisibleIndex, "hlEdit")

                If myText.Text = "" Then
                    myLB.Visible = False
                    hlEdit.Visible = False
                    e.Row.Cells(0).Controls(0).Visible = False
                Else
                    hlEdit.NavigateUrl = "frmEdit_Menu.aspx?" & Encryption.Base64Encryption("SubMenuId$" & gvMenu.GetRowValues(e.VisibleIndex, "KeyValue").ToString.Split("|")(1))
                    If gvMenu.GetRowValues(e.VisibleIndex, "SM_URL") <> "" Then
                        myLB.Visible = False
                    Else
                        myLB.NavigateUrl = "frmEdit_Menu.aspx?" & Encryption.Base64Encryption("SubMenuId$" & gvMenu.GetRowValues(e.VisibleIndex, "KeyValue").ToString.Split("|")(1))
                    End If
                End If

            End If

        ElseIf e.RowType = DevExpress.Web.ASPxGridView.GridViewRowType.Data Then

            Dim hlEdit As HyperLink = gvMenu.FindRowCellTemplateControl(e.VisibleIndex, gvMenu.Columns(3), "hlEditSS")

            If gvMenu.GetRowValues(e.VisibleIndex, "SSM_Desc") = "" Then
                hlEdit.Visible = False
            Else
                hlEdit.NavigateUrl = "frmEdit_Menu.aspx?" & Encryption.Base64Encryption("SubSubMenuId$" & gvMenu.GetRowValues(e.VisibleIndex, "KeyValue").ToString.Split("|")(2))
            End If

        End If

15 Jul 2011

Query to Find First and Last Day of Current Month

Following query will run respective to today’s date. It will return Last Day of Previous Month, First Day of Current Month, Today, Last Day of Previous Month and First Day of Next Month respective to current month.
DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)),@mydate),101) ,
'Last Day of Previous Month'
UNION
SELECT
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101) AS Date_Value,
'First Day of Current Month' AS Date_Type
UNION
SELECT
CONVERT(VARCHAR(25),@mydate,101) AS Date_Value, 'Today' AS Date_Type
UNION
SELECT
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)),101) ,
'Last Day of Current Month'
UNION
SELECT
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))-1),DATEADD(mm,1,@mydate)),101) ,
'First Day of Next Month'

13 Jul 2011

How to Improve ASP.Net Web Application Performance.

Introduction
Performance tuning can be tricky. It’s especially tough in Internet-related projects with lots of components running around, like HTML client, HTTP network, Web server, middle-tier components, database components, resource-management components, TCP/IP networks, and database servers. Performance tuning depends on a lot of parameters and sometimes, by changing a single parameter, performance can increase drastically.

This article lists out some tips for optimizing ASP.Net Web applications and many traps and pitfalls are discussed as follows : Tips For Web Application

1) Turn off Tracing unless until required
Tracing is one of the wonderful features which enable us to track the application’s trace and the sequences. However, again it is useful only for developers and you can set this to “false” unless you require to monitor the trace logging.
How it affects performance:
Enabling tracing adds performance overhead and might expose private information, so it should be enabled only while an application is being actively analyzed.
Solution:
When not needed, tracing can be turned off using
<trace enabled=”false” requestLimit=”10” pageoutput=”false” traceMode=”SortByTime” localOnly=”true”>
2) Turn off Session State, if not required
One extremely powerful feature of ASP.NET is its ability to store session state for users, such as a shopping cart on an e-commerce site or a browser history.
How it affects performance:
Since ASP.NET Manages session state by default, you pay the cost in memory even if you don’t use it. I.e. whether you store your data in in-process or on state server or in a Sql Database, session state requires memory and it’s also time consuming when you store or retrieve data from it.
Solution:
You may not require session state when your pages are static or when you do not need to store information captured in the page.
In such cases where you need not use session state, disable it on your web form using the directive,
<@%Page EnableSessionState=”false”%>
In case you use the session state only to retrieve data from it and not to update it, make the session state read only by using the directive,
<@%Page EnableSessionState =”ReadOnly”%>
3) Disable View State of a Page if possible
View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page’s tree of controls.
View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data.
How it affects performance:
? There are a number of drawbacks to the use of view state, however.
? It increases the total payload of the page both when served and when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server.
? View state increases the memory allocations on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed.
Solution:
Pages that do not have any server postback events can have the view state turned off.
The default behavior of the ViewState property is enabled, but if you don’t need it, you can turn it off at the control or page level. Within a control, simply set the EnableViewState property to false, or set it globally within the page using this setting:
<%@ Page EnableViewState=”false” %>
If you turn view state off for a page or control, make sure you thoroughly test your pages to verify that they continue to function correctly.
4) Set debug=false in web.config
When you create the application, by default this attribute is set to “true” which is very useful while developing. However, when you are deploying your application, always set it to “false”.
How it affects performance:
Setting it to “true” requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.
Solution:
Therefore, always set debug=”false” before deployment.
5) Avoid Response.Redirect
Response.Redirect () method simply tells the browser to visit another page.
How it affects performance:
Redirects are also very chatty. They should only be used when you are transferring people to another physical web server.
Solution:
For any transfers within your server, use .transfer! You will save a lot of needless HTTP requests. Instead of telling the browser to redirect, it simply changes the “focus” on the Web server and transfers the request. This means you don’t get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.
Tradeoffs:
? “.transfer” process can work on only those sites running on the server. Only Response.Redirect can do that.
? Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging
5. A) To reduce CLR Exceptions count, Use Response.Redirect (“.aspx”, false) instead of response.redirect (“.aspx”).
6) Use the String builder to concatenate string
How it affects performance:
String is Evil when you want to append and concatenate text to your string. All the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.
i.e. When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive.
Solution:
Use String Builder when ever string concatenation is needed so that it only stores the value in the original string and no additional reference is created.
7) Avoid throwing exceptions
How it affects performance:
Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications.
Solution:
You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.
8) Use Finally Method to kill resources
?The finally method gets executed independent of the outcome of the Block.
?Always use the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.
9) Use Client Side Scripts for validations
User Input is Evil and it must be thoroughly validated before processing to avoid overhead and possible injections to your applications.
How It improves performance:
Client site validation can help reduce round trips that are required to process user’s request. In ASP.NET you can also use client side controls to validate user input. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.
10) Avoid unnecessary round trips to the server
How it affects performance:
Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
Solution:
? Keep round trips to an absolute minimum
? Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed
11) Use Page.ISPostBack
Make sure you don’t execute code needlessly. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is first time loaded and not in response to client postbacks.
12) Include Return Statements with in the Function/Method
How it improves performance
Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn’t change the semantics of the code at all, and it can help you get more speed from your application.
13) Use Foreach loop instead of For loop for String Iteration
Foreach is far more readable, and in the future it will become as fast as a For loop for special cases like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not be worth it.
14) Avoid Unnecessary Indirection
How it affects performance:
When you use byRef, you pass pointers instead of the actual object.
Many times this makes sense (side-effecting functions, for example), but you don’t always need it. Passing pointers results in more indirection, which is slower than accessing a value that is on the stack.
Solution:
When you don’t need to go through the heap, it is best to avoid it there by avoiding indirection.
15) Use “ArrayLists” in place of arrays
How it improves performance
An ArrayList as everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList interface.
Tradeoffs:
The downside of an ArrayList is the need to cast objects upon retrieval.
16) Always check Page.IsValid when using Validator Controls
Always make sure you check Page.IsValid before processing your forms when using Validator Controls.
17) Use Paging
Take advantage of paging’s simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster.
Tradeoffs:
Just be careful when you mix in caching. Don’t cache all the data in the grid.
18) Store your content by using caching
How it improves performance:
ASP.NET allows you to cache entire pages, fragment of pages or controls. You can cache also variable data by specifying the parameters that the data depends. By using caching you help ASP.NET engine to return data for repeated request for the same page much faster.
When and Why Use Caching:
A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.
Good candidate to use caching is if you have infrequent chance of data or static content of web page.
19) Use low cost authentication
Authentication can also have an impact over the performance of your application. For example passport authentication is slower than form-base authentication which in here turn is slower than Windows authentication.
20) Minimize the number of web server controls
How it affects performance:
The use of web server controls increases the response time of your application because they need time to be processed on the server side before they are rendered on the client side.
Solution:
One way to minimize the number of web server controls is to taking into consideration, the usage of HTML elements where they are suited, for example if you want to display static text.
21) Avoid using unmanaged code
How it affects performance:
Calls to unmanaged code are a costly marshaling operation.
Solution:
Try to reduce the number calls between the managed and unmanaged code. Consider to do more work in each call rather than making frequent calls to do small tasks.
22) Avoid making frequent calls across processes
If you are working with distributed applications, this involves additional overhead negotiating network and application level protocols. In this case network speed can also be a bottleneck. Try to do as much work as possible in fewer calls over the network.
23) Cleaning Up Style Sheets and Script Files
? A quick and easy way to improve your web application’s performance is by going back and cleaning up your CSS Style Sheets and Script Files of unnecessary code or old styles and functions. It is common for old styles and functions to still exist in your style sheets and script files during development cycles and when improvements are made to a website.
? Many websites use a single CSS Style Sheet or Script File for the entire website. Sometimes, just going through these files and cleaning them up can improve the performance of your site by reducing the page size. If you are referencing images in your style sheet that are no longer used on your website, it’s a waste of performance to leave them in there and have them loaded each time the style sheet is loaded.
? Run a web page analyzer against pages in your website so that you can see exactly what is being loaded and what takes the most time to load.
24) Design with ValueTypes
Use simple structs when you can, and when you don’t do a lot of boxing
and unboxing.
Tradeoffs:
ValueTypes are far less flexible than Objects, and end up hurting performance if used incorrectly. You need to be very careful about when you treat them like objects. This adds extra boxing and unboxing overhead to your program, and can end up costing you more than it would if you had stuck with objects.
25) Minimize assemblies
Minimize the number of assemblies you use to keep your working set small. If you load an entire assembly just to use one method, you’re paying a tremendous cost for very little benefit. See if you can duplicate that method’s functionality using code that you already have loaded.
26) Encode Using ASCII When You Don’t Need UTF
By default, ASP.NET comes configured to encode requests and responses as UTF-8.
If ASCII is all your application needs, eliminated the UTF overhead can give you back a few cycles. Note that this can only be done on a per-application basis.
27) Avoid Recursive Functions / Nested Loops
These are general things to adopt in any programming language, which consume lot of memory. Always avoid Nested Loops, Recursive functions, to improve performance.
28) Minimize the Use of Format ()
When you can, use toString () instead of format (). In most cases, it will provide you with the functionality you need, with much less overhead.
29) Place StyleSheets into the Header
Web developers who care about performance want browser to load whatever content it has as soon as possible. This fact is especially important for pages with a lot of content and for users with slow Internet connections. When the browser loads the page progressively the header, the logo, the navigation components serve as visual feedback for the user.
When we place style sheets near the bottom part of the html, most browsers stop rendering to avoid redrawing elements of the page if their styles change thus decreasing the performance of the page. So, always place StyleSheets into the Header
30) Put Scripts to the end of Document
Unlike StyleSheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all StyleSheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames.
So,always have scripts at the end of the document.
31) Make JavaScript and CSS External
Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number of HTTP requests thus improving the performance.
Tips For Database Operations
1) Return Multiple Resultsets
The database code if has request paths that go to the database more than once then, these round-trips decreases the number of requests per second your application can serve.
Solution:
Return multiple resultsets in a single database request, so that you can cut the total time spent communicating with the database. You’ll be making your system more scalable, too, as you’ll cut down on the work the database server is doing managing requests.
2) Connection Pooling and Object Pooling
Connection pooling is a useful way to reuse connections for multiple requests, rather than paying the overhead of opening and closing a connection for each request. It’s done implicitly, but you get one pool per unique connection string. Make sure you call Close or Dispose on a connection as soon as possible. When pooling is enabled, calling Close or Dispose returns the connection to the pool instead of closing the underlying database connection.
Account for the following issues when pooling is a part of your design:
? Share connections
? Avoid per-user logons to the database
? Do not vary connection strings
? Do not cache connections
3) Use SqlDataReader Instead of Dataset wherever it is possible
If you are reading a table sequentially you should use the DataReader rather than DataSet. DataReader object creates a read only stream of data that will increase your application performance because only one row is in memory at a time.
4) Keep Your Datasets Lean
Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.
Therefore Only put the records you need into the dataset.
5) Avoid Inefficient queries
How it affects performance:
Queries that process and then return more columns or rows than necessary, waste processing cycles that could best be used for servicing other requests.
Cause of Inefficient queries:
? Too much data in your results is usually the result of inefficient queries.
? The SELECT * query often causes this problem. You do not usually need to return all the columns in a row. Also, analyze the WHERE clause in your queries to ensure that you are not returning too many rows. Try to make the WHERE clause as specific as possible to ensure that the least number of rows are returned.
? Queries that do not take advantage of indexes may also cause poor performance.
6) Unnecessary round trips
How it affects performance:
Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
Solution:
Keep round trips to an absolute minimum.
7) Too many open connections
Connections are an expensive and scarce resource, which should be shared between callers by using connection pooling. Opening a connection for each caller limits scalability.
Solution:
To ensure the efficient use of connection pooling, avoid keeping connections open and avoid varying connection strings.
8) Avoid Transaction misuse
How it affects performance:
If you select the wrong type of transaction management, you may add latency to each operation. Additionally, if you keep transactions active for long periods of time, the active transactions may cause resource pressure.
Solution:
Transactions are necessary to ensure the integrity of your data, but you need to ensure that you use the appropriate type of transaction for the shortest duration possible and only where necessary.
9) Avoid Over Normalized tables
Over Normalized tables may require excessive joins for simple operations. These additional steps may significantly affect the performance and scalability of your application, especially as the number of users and requests increases.
10) Reduce Serialization
Dataset serialization is more efficiently implemented in .NET Framework version 1.1 than in version 1.0. However, Dataset serialization often introduces performance bottlenecks.
You can reduce the performance impact in a number of ways:
? Use column name aliasing
? Avoid serializing multiple versions of the same data
? Reduce the number of DataTable objects that are serialized
11) Do Not Use CommandBuilder at Run Time
How it affects performance:
CommandBuilder objects such as as SqlCommandBuilder and OleDbCommandBuilder are useful when you are designing and prototyping your application. However, you should not use them in production applications. The processing required to generate the commands affects performance.
Solution:
Manually create stored procedures for your commands, or use the Visual Studio® .NET design-time wizard and customize them later if necessary.
12) Use Stored Procedures Whenever Possible
?Stored procedures are highly optimized tools that result in excellent performance when used effectively.
?Set up stored procedures to handle inserts, updates, and deletes with the data adapter
?Stored procedures do not have to be interpreted, compiled or even transmitted from the client, and cut down on both network traffic and server overhead.
?Be sure to use CommandType.StoredProcedure instead of CommandType.Text
13) Avoid Auto-Generated Commands
When using a data adapter, avoid auto-generated commands. These require additional trips to the server to retrieve meta data, and give you a lower level of interaction control. While using auto-generated commands is convenient, it’s worth the effort to do it yourself in performance-critical applications.
14) Use Sequential Access as Often as Possible
With a data reader, use CommandBehavior.SequentialAccess. This is essential for dealing with blob data types since it allows data to be read off of the wire in small chunks. While you can only work with one piece of the data at a time, the latency for loading a large data type disappears. If you don’t need to work the whole object at once, using
Sequential Access will give you much better performance.
Summary
When we talk about ASP.Net performance, there are lots of factors in place.
Above discussed are the most critical of the speed improvements you can make in ASP.net that will have a dramatic impact on the user experience of your web application.