Monday 29 September 2014

ASP.NET - File Uploading

ASP.Net has two controls that allow the users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it or ignore it. The following controls allow the file uploading:
  • HtmlInputFile - an HTML server control
  • FileUpload - and ASP.Net web control
Both the controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.
In this tutorial, we will use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a Browse button and a text box for entering the filename.
Once, the user has entered the filename in the text box, by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax for using the FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />
The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:
PropertiesDescription
FileBytesReturns an array of the bytes in a file to be uploaded..
FileContentReturns the stream object pointing to the file to be uploaded.
FileNameReturns the name of the file to be uploaded.
HasFileSpecifies whether the control has a file to upload.
PostedFileReturns a reference to the uploaded file.
The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following important properties, which are much used:
PropertiesDescription
ContentLengthReturns the size of the uploaded file in bytes.
ContentTypeReturns the MIME type of the uploaded file
FileNameReturns the full filename.
InputStreamReturns a stream object pointing to the uploaded file.

Example:

The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type and file length.
In the design view, the form looks like:
File Upload
The content file:
<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
   <asp:FileUpload ID="FileUpload1" runat="server" />
   <br /><br />
   <asp:Button ID="btnsave" runat="server" 
               onclick="btnsave_Click" Text="Save" 
               style="width:85px" />
   <br /><br />
   <asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>
The code behind the save button:
protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   if (FileUpload1.HasFile)
   {
      try
      {
      sb.AppendFormat(" Uploading file: {0}", 
                                  FileUpload1.FileName);
      //saving the file
      FileUpload1.SaveAs("<c:\\SaveDirectory>" + 
                                  FileUpload1.FileName);
      //Showing the file information
      sb.AppendFormat("<br/> Save As: {0}", 
                         FileUpload1.PostedFile.FileName);
      sb.AppendFormat("<br/> File type: {0}",   
                         FileUpload1.PostedFile.ContentType);
      sb.AppendFormat("<br/> File length: {0}", 
                         FileUpload1.PostedFile.ContentLength);
      sb.AppendFormat("<br/> File name: {0}", 
                         FileUpload1.PostedFile.FileName);
      }
      catch (Exception ex)
      {
      sb.Append("<br/> Error <br/>");
      sb.AppendFormat("Unable to save file <br/> {0}", 
                         ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}
Note the following:
  • The StringBuilder class is derived from System.IO namespace, so it should be included.
  • The try and catch blocks are used for catching errors, and display the error message.

ASP.NET - Life Cycle

ASP.Net life cycle specifies, how:
  • ASP.Net processes pages to produce dynamic output
  • The application and its pages are instantiated and processed
  • ASP.Net compiles the pages dynamically
The ASP.Net life cycle could be divided into two groups:
  • Application Life Cycle
  • Page Life Cycle

ASP.Net Application Life Cycle:

The application life cycle has the following stages:
  • User makes a request for accessing application resource, a page. Browser sends this request to the web server.
  • A unified pipeline receives the first request and the following events take place:
    • An object of the ApplicationManager class is created.
    • An object of the HostingEnvironment class is created to provide information regarding the resources.
    • Top level items in the application are compiled.
  • Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.
  • An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:
  • Initialization
  • Instantiation of the controls on the page
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.Net page:
  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.
Following are the page life cycle events:
  • PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  • InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  • LoadViewState . LoadViewState event allows loading view state information into the controls.
  • LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.
  • PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  • Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  • LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
  • PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  • PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  • SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  • UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.


ASP.NET - Web Services

A web service is a web-based functionality accessed using the protocols of the web to be used by the web applications. There are three aspects of web service development:
  • Creating the web service
  • Creating a proxy
  • Consuming the web service

Creating the Web Sevice:

A web service is an web application which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture like the ASP.Net web pages, although it does not have an user interface.
To understand the concept let us create a web service that will provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This web service will have three methods:
  • A default HelloWorld method
  • A GetName Method
  • A GetPrice Method
Take the following steps to create the web service:
Step (1): Select File--> New --> Web Site in Visual Studio, and then select ASP.Net Web Service.
Step (2): A web service file called Service.asmx and its code behind file, Service.cs is created in the App_Code directory of the project.
Step (3): Change the names of the files to StockService.asmx and StockService.cs.
Step (4): The .asmx file has simply a WebService directive on it:
<%@ WebService Language="C#" 
                  CodeBehind="~/App_Code/StockService.cs" 
                  Class="StockService" %>
Step (5): Open the StockService.cs file, the code generated in it is the basic Hello World service. The default web service code behind file looks like the following:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace StockService
{
   /// <summary>
   /// Summary description for Service1
   /// <summary>
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   [ToolboxItem(false)]
   // To allow this Web Service to be called from script, 
   // using ASP.NET AJAX, uncomment the following line. 
   // [System.Web.Script.Services.ScriptService]
   public class Service1 : System.Web.Services.WebService
   {
     [WebMethod]
     public string HelloWorld()
     {
        return "Hello World";
     }
   }
}
Step (6): Change the code behind file to add the two dimensional array of strings for stock symbol, name and price and two web methods for getting the stock information.
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, 
// using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class StockService : System.Web.Services.WebService
{
   public StockService () {
     //Uncomment the following if using designed components 
     //InitializeComponent(); 
   }
   string[,] stocks =
   {
   {"RELIND", "Reliance Industries", "1060.15"},
   {"ICICI", "ICICI Bank", "911.55"},
   {"JSW", "JSW Steel", "1201.25"},
   {"WIPRO", "Wipro Limited", "1194.65"},
   {"SATYAM", "Satyam Computers", "91.10"}
   };

   [WebMethod]
   public string HelloWorld() {
      return "Hello World";
   }
   [WebMethod]
   public double GetPrice(string symbol)
   { 
      //it takes the symbol as parameter and returns price
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return Convert.ToDouble(stocks[i, 2]);
      }
      return 0;
   }
   [WebMethod]
   public string GetName(string symbol)
   {
      // It takes the symbol as parameter and 
      // returns name of the stock
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
           return stocks[i, 1];
      }
      return "Stock Not Found";
   }
}
Step (7) : Running the web service application gives a web service test page, which allows testing the service methods.
Stock Service
Step (8) : Click on a method name, and check whether it runs properly.
Get Name
Step (9): For testing the GetName method, provide one of the stock symbols, which are hard coded, it returns the name of the stock
the name of the stock

Consuming the Web Service:

For using the web service, create a web site under the same solution. This could be done by right clicking on the Solution name in the Solution Explorer. The web page calling the web service should have a label control to display the returned results and two button controls one for post back and another for calling the service.
The content file for the web application is as follows:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="wsclient._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
    <div>
    <h3>Using the Stock Service</h3>
    <br />
    <br />
    <asp:Label ID="lblmessage" runat="server"></asp:Label>
    <br />
    <br />
    <asp:Button ID="btnpostback" runat="server" 
                onclick="Button1_Click" 
                Text="Post Back" style="width:132px" />
       
    <asp:Button ID="btnservice" runat="server" 
                onclick="btnservice_Click" 
                Text="Get Stock" style="width:99px" />
    </div>
</form>
</body>
</html>
The code behind file for the web application is as follows:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

//this is the proxy
using localhost;

namespace wsclient
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
     {
        if (!IsPostBack)
           lblmessage.Text = "First Loading Time: " + 
           DateTime.Now.ToLongTimeString();
        else
           lblmessage.Text = "PostBack at: " + 
           DateTime.Now.ToLongTimeString();
     }
     protected void btnservice_Click(object sender, EventArgs e)
     {
       StockService proxy = new StockService();
       lblmessage.Text = String.Format("Current SATYAM Price:{0}",
       proxy.GetPrice("SATYAM").ToString());
     }
   }
}

Creating the Proxy:

A proxy is a stand-in for the web service codes. Before using the web service, a proxy must be created. The proxy is registered with the client application. Then the client application makes the calls to the web service as it were using a local method.
The proxy takes the calls, wraps it in proper format and sends it as a SOAP request to the server. SOAP stands for Simple Object Access Protocol. This protocol is used for exchanging web service data.
When the server returns the SOAP package to the client, the proxy decodes everything and presents it to the client application.
Before calling the web service using the btnservice_Click, a web reference should be added to the application. This creates a proxy class transparently, which is used by the btnservice_Click event.
protected void btnservice_Click(object sender, EventArgs e)
{
  StockService proxy = new StockService();
  lblmessage.Text = String.Format("Current SATYAM Price: {0}", 
  proxy.GetPrice("SATYAM").ToString());
}
Take the following steps for creating the proxy:
Step (1): Right click on the web application entry in the Solution Explorer and click on 'Add Web Reference'.
Add Web Reference
Step (2): Select 'Web Services in this solution'. It returns the StockService reference.
Select Web Services
Step (3): Clicking on the service opens the test web page. By default the proxy created is called 'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the client application.
Stock Service 2
Include the proxy in the code behind file by adding:
 using localhost;

ASP.NET - Ajax Control

AJAX stands for Asynchronous JavaScript and XML. This is a cross platform technology which speeds up response time. The AJAX server controls add script to the page which is executed and processed by the browser.
However like other ASP.Net server controls, these AJAX server controls also can have methods and event handlers associated with them, which are processed on the server side.
The control toolbox in the Visual Studio IDE contains a group of controls called the 'AJAX Extensions'
AJAX Extensions

The ScriptManager Control

The ScriptManager control is the most important control and must be present on the page for other controls to work.
It has the basic syntax:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web form automatically contains the script manager control. The ScriptManager control takes care of the client-side script for all the server side controls.

The UpdatePanel Control:

The UpdatePanel control is a container control and derives from the Control class. It acts as a container for the child controls within it and does not have its own interface. When a control inside it triggers a post back, the UpdatePanel intervenes to initiate the post asynchronously and update just that portion of the page.
For example, if a button control is inside the update panel and it is clicked, only the controls within the update panel will be affected, the controls on the other parts of the page will not be affected. This is called the partial post back or the asynchronous post back.

Example:

Add an AJAX web form in your application. It will contain the script manager control by default. Insert an update panel. Place a button control along with a label control within the update panel control. Place another set of button and label outside the panel.
The design view looks as follows:
ScriptManager
The source file is as follows:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnpartial" runat="server" 
            onclick="btnpartial_Click" Text="Partial PostBack"/>
<br />
<br />
<asp:Label ID="lblpartial" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<p>
 </p>
<p>
Outside the Update Panel</p>
<p>
<asp:Button ID="btntotal" runat="server" 
    onclick="btntotal_Click" Text="Total PostBack" />
</p>
<asp:Label ID="lbltotal" runat="server"></asp:Label>
</form>
Both the button controls have same code for the event handler:
string time = DateTime.Now.ToLongTimeString();
lblpartial.Text = "Showing time from panel" + time;
lbltotal.Text = "Showing time from outside" + time;
Observe that when the page is run, if the total post back button is clicked, it updates time in both the labels but if the partial post back button is clicked, it only updates the label within the update panel.
update panel
A page can contain more than one update panel with each panel containing other controls like a grid and displaying different part of data.
When a total post back occurs, the content of the update panel is updated by default. This default mode could be changed by changing the UpdateMode property of the control. Let us look at other properties of the update panel.

Properties of the UpdatePanel Control:

The following table shows the properties of the update panel control:
PropertiesDescription
ChildrenAsTriggersThis property indicates whether the post backs are coming from the child controls which will cause the update panel to refresh.
ContentTemplateIt is the content template and defines what appears in the update panel when it is rendered.
ContentTemplateContainerRetrieves the dynamically created template container object and used for adding child controls programmatically.
IsInPartialRenderingIndicates whether the panel is being updated as part of the partial post back.
RenderModeShows the render modes. The available modes are Block and Inline.
UpdateModeGets or sets the rendering mode by determining some conditions.
TriggersDefines the collection trigger objects each corresponding to an event causing the panel to refresh automatically.

Methods of the UpdatePanel Control:

The following table shows the methods of the update panel control:
MethodsDescription
CreateContentTemplateContainerCreates a Control object that acts as a container for child controls that define the UpdatePanel control's content.
CreateControlCollectionReturns the collection of all controls that are contained in the UpdatePanel control.
InitializeInitializes the UpdatePanel control trigger collection if partial-page rendering is enabled.
UpdateCauses an update of the content of an UpdatePanel control.
The behaviour of the update panel depends upon the values of the UpdateMode property and ChildrenAsTriggers property:
UpdateModeChildrenAsTriggersEffect
AlwaysFalseIllegal parameters.
AlwaysTrueUpdatePanel refreshes if whole page refreshes or a child control on it posts back.
ConditionalFalseUpdatePanel refreshes if whole page refreshes or a triggering control outside it initiates a refresh.
ConditionalTrueUpdatePanel refreshes if whole page refreshes or a child control on it posts back or a triggering control outside it initiates a refresh.

The UpdateProgress Control:

The UpdateProgress control provides a sort of feedback on the browser while one or more update panel controls are being updated. For example while a user logs in or waits for server response while performing some database oriented job.
It provides a visual acknowledgement like "Loading page...", indicating the work is in progress.
The syntax for the UpdateProgress control is:
<asp:UpdateProgress ID="UpdateProgress1" 
              runat="server" 
              DynamicLayout="true" 
              AssociatedUpdatePanelID="UpdatePanel1" >
<ProgressTemplate>
   Loading...
</ProgressTemplate>
</asp:UpdateProgress>
The above snippet shows a simple message within the ProgressTemplate tag, however it could be an image or other relevant controls. The UpdateProgress control will display for every asynchronous postback unless it is assigned to a single update panel using the AssociatedUpdatePanelID property.

Properties of the UpdateProgress Control

The following table shows the properties of the update progress control:
PropertiesDescription
AssociatedUpdatePanelIDGets and sets the ID of the update panel with which this control is associated.
AttributesGets or sets the cascading style sheet (CSS) attributes of the UpdateProgress control.
DisplayAfterGets and sets the time in milliseconds after which the progress template is displayed. The default is 500.
DynamicLayoutIndicates whether the progress template is dynamically rendered.
ProgressTemplateIndicates the template displayed during an asynchronous post back which takes more time than the DisplayAfter time.

Methods of the UpdateProgress Control

The following table shows the methods of the update progress control:
MethodsDescription
GetScriptDescriptorsReturns a list of components, behaviors, and client controls that are required for the UpdateProgress control's client functionality.
GetScriptReferencesReturns a list of client script library dependencies for the UpdateProgress control.

The Timer Control:

The timer control is used to initiate the post back automatically. This could be done in two ways:
(1) Setting the Triggers property of the UpdatePanel control:
<Triggers>
<asp:AsyncPostBackTrigger 
                ControlID="btnpanel2" 
                EventName="Click" />
</Triggers>
(2) Placing a timer control directly inside the UpdatePanel to act as a child control trigger. A single timer can be the trigger for multiple UpdatePanels.
<asp:UpdatePanel ID="UpdatePanel1" 
                 runat="server" 
                 UpdateMode="Always">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
<asp:Label ID="Label1" runat="server" 
           Height="101px" style="width:304px">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>

SAP HANA DB ANALYSIS AFTER ISSUES

To be able to further analyze your issue and environment please download the attached shell script you can get from KBA: 3218277 - Collectin...