Deploying ASP.NET Applications

Tuesday, July 28, 2009

After creating and testing your ASP.NET application, the next step is to deploy the application. Deployment is the process of distributing the finished application to be installed on other computer. We can use the built-in deployment feature that comes with Visual studio .NET to create a Windows Installer file - a .msi file for the purpose of deploying applications.
Deploying Applications
To start, open the Web Application project you want to deploy. Say, you have a project named "Deploy" with ten Web pages in it. Select File->Add Project->New Project from the main menu. From the Project Types pane select Setup and Deployment Projects and from the Templates pane select Web Setup Project. Type WebSetup1 for name and specify a location in the location box and click OK. The New project dialogue box looks like the image below.

When you click OK on the above dialogue box, the project is added to the solution explorer window and also a File System Editor window appears as shown in the image below.

The File System Editor window has two panes. Select Web Application Folder in the left pane in this window. From the Action menu (on main menu), select Project Output to open the Add Project Output Group dialog box. It looks like the image below.

Make sure that Deploy is selected in the Project drop-down list and select Primary Output from the list and click OK. You also can select other options depending upon the users of your application.
Now, in the File System Editor window, select Web Application Folder and open its Properties window. The Properties window for the Web Application Folder looks like the image below.

In this window, set the VirtualDirectory property to any name, say FinishedApp. FinshedApp will be the folder on the target machine where you will install this application. The name you set for this VirtualDirectory property should not already exist on the target machine. If it does, the contents in the folder will be overwritten. Also, set the DefaultDocument property to any page in the application. The page you set in this property will be the default page for the Web Application. Once you are finished with the Properties window build the solution by selecting Build->Build WebSetup1 from the main menu. After the solution is built sucessfully, a WebSetup1.msi file is created in the Debug directory of the Web Setup project. The default path to the debug directory is as follows:
C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\deploy\WebSetup1\Debug.
Installing the Application
You can copy the WebSetup1.msi file to the target machine and double-click to install the Web Application. When you double-click the setup file the dialog that opens looks like the image below.

Click next and you will be taken to the next dialog which looks like the image below.

You can use the default Virtual Directory specified by the installer or you can specify one. Click next to install the application.

By Usama Wahab Khan and Atif Shahzad

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5 in C#

ASP.NET developers have faced the requirement of reading and writing images to the database. How to store images in the database and then display those images along with the other server controls.
First see how to upload an image and then display the uploaded image on the same page. First creating a sample database and adding a table to it. We will call the database ‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an image column along with some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to construct the database and the table.

Step 1: Create a new asp.net website. In the code-behind, add the following namespace
using System.Data.SqlClient;
Step 2:
Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button control to upload the selected image on button click.

Step 3: In the button click event, add the following code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}

}
In the code above, we are creating a byte array equal to the length of the file. The byte array will store the image. We then load the image data into the array. The record containing the Employee Name and Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage handler. The image will then be fetched against the EmployeeID (empid).
Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is then passed to the ‘ShowEmpImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}


}
Step 5: One final step. Add the following code in the button click (just above the catch block) to call the handler and display the newly inserted image from the database. In the code below, we pass the EmployeeID as a query string parameter to the Http Handler.
// Display the image from the database
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

By
Usama Wahab khan and Atif shahzad

Silverlight 3 Controls

New Controls

Global Calendar
Global Calendar provides an easy way to style individual days as well abstracting out calendar logic allowing the ability to define custom Gregorian calendars.
Same API as Calendar with two new properties: CalendarDayButtonStyleSelector and Calendar Info.
New: Hotkey Ctrl + Home selects the current date or extends the current selection when used in conjunction with Shift.
Rating
Represents a control that can be used to display or allow users to interactively select a rating value. Ratings can be whole or partial stars. By default the control displays stars but can be easily styled to use a different rating metaphor.
TreeMap
The TreeMap visualization displays a hierarchy of data as a set of nested rectangles, where the area of each rectangle represents a chosen metric from the data. Through the use of Interpolators, other properties such as background colour, font size and font color can be varied to represent other metrics. TemplateSelectors allow the control to be easily extended to have different layouts or color schemes for different levels or branches within the hierarchy.
New Extensions
ItemsControlExtensions
Provides useful extensions to ItemsControl:
Get various collections representing the items and their containers.
Get an items host or ScrollViewer.
ScrollViewerExtensions
Provides useful extensions to ScrollViewer to make basic scrolling tasks easier:
Enable mouse wheel scrolling in XAML!
Scroll by page or line.
Scroll to top, bottom, left or right.
Scroll items into view.
TreeViewExtensions
Provides useful extensions to TreeView and TreeViewItem to greatly simplify common TreeView tasks:
Set selected item
Easily add connecting lines and CheckBoxes
Expand and collapse items.
Get items and their containers for parents, siblings and descendants.
Get path.




Accordion
Breaking Change: Removed HeaderTemplate on Accordion, use ItemTemplate.
New: Accordion introduces AccordionButtonStyle making the scenarios where you would like to set the ClickMode to hover on the AccordionItems easy.
Accordion reacts to size changes on both content and header and will trigger a new layout-pass.
AccordionItem will treat its content the same as Grid, making scrollbars visible on content that supports it. AccordionItem no longer has a ScrollViewer in its template.
AccordionItem makes content sizing easy by setting Horizontal/Vertical-ContentAlignment.
AccordionItem now exposes a TargetSize property, allowing you to do calculations of expected size versus current size.
Header is databound making databinding straightforward.
Accordion is able to work with duplicate items (using the SelectedIndices property)
Design-time experience is improved; allowing AccordionItems to open inside Blend.
Lots of layout improvements.
Charting
WPF is now an official platform for Charting!
Breaking Change: IRequireGlobalSeriesIndex's GlobalSeriesIndexChanged method takes a nullable int parameter.
Improved performance of internal data structures for many common scenarios.
Numerous bug fixes for animation inconsistencies between Silverlight and WPF.
Fixed handling of data objects with non-unique hash codes.
Corrected behavior of charts at very small sizes and during animations.
Proper RoutedEvent support for DataPointSeries.SelectionChangedEvent.
Better handling of non-double data by shared Series.
Addition of StrokeMiterLimit to the Polyline used by LineSeries.
Fixes for edge case scenarios when removing a Series.
Ability to set Series.Title with a Binding (on Silverlight 3 and WPF).
Automatic inheritance of the Foreground property by the Title control.
Visual improvements to the LegendItem DataPoint marker.
Significant BubbleSeries performance improvement.
Fixed: Removing a PieSeries from a Chart's Series collection causes a NullReferenceException
Fixed: Chart series title not binding
DataForm Breaking Changes
DataFormFields have all been removed and DataForm.Fields collection has been removed. They have been replaced with the new DataField control, which is a control that wraps content with a label and DescriptionViewer.
Must now explicitly specify Mode=TwoWay on bindings in the DataField.
FieldEditEnding and FieldEditEnded have been removed.
GetFieldElement() has been removed.
ItemEditEnding, ItemEditEnded, CommitItemEdit() have been changed to EditEnding, EditEnded, and CommitEdit() respectively.
CanMoveToXXXXItem have been removed, as they can be derived from the collection given to the DataForm.
CanUserAdd/DeleteItems have been removed, as they are implied through CommandButtonsVisibility.
IsEditing and IsAddingItem have been removed, as they are implied through Mode.
FieldLabelPosition and FieldLabelStyle have become LabelPosition and LabelStyle.
WrapAfter and Orientation have been removed.
The type names DataFormFieldLabelPosition and DataFormDescriptionViewerPosition have been changed to DataFieldLabelPosition and DataFieldDescriptionViewerPosition.
DomainUpDown
Space bar now moves the DomainUpDown into edit mode.
Better handling of mouse-events in edit mode.
Fixed: SL2 Input control DomainUpDown
Expander
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
HeaderedContentControl
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3.
Fixed: HeaderedContentControl throws exception when its content is replaced (under some condition)
Navigation (released as part of the SDK)
New: Pages can be “cached” so they can be re-used on subsequent navigation to the same URI.
TabControl
Fixed: Changing TabControl tabs causing TreeView.SelectionItemChanged event to fire on every node
Time Picker / TimeUpDown
Setting an initial value will be propagated correctly.
Full UI Automation hierarchy implemented.
Renamed the BalloonHint states to TimeHint.
Various minor bug fixes.
Fixed: TimePicker does not show initial Value set in Xaml
Fixed: Buttonspinner disabled state is unnecessary
Fixed: TimePicker - Not able to select a time in dropdown list that is already selected by clicking or with enter key
TransitioningContentControl
Changed the template to have two ContentPresenters instead of ContentControls.
Fixed bug where switching between content would raise exception in certain scenarios.
Handles setting the Transition to a transition that is not yet there (if template hasn’t been loaded yet).
Fixed: System.ArgumentException while using TransitioningContentControl
TreeView (released as part of the SDK)
Fixed: TreeView Scrolls when adding new TreeViewItem
Fixed: TreeView: The App crashes when we add a button as TreeViewItem content
Themes
Fixed: BureauBlueTheme PasswordBox Style always displays vertical scrollbar
ValidationSummary (released as part of the SDK)
The control formally known as ErrorSummary is now ValidationSummary.
Viewbox
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
WrapPanel
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
SilverLight 3 Categories:

Silverlight Controls
AutoCompleteBox
Represents a control that provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.

Represents a control that provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.

TreeView
Represents a control that displays hierarchical data in a tree structure that has items that can expand and collapse.

NumericUpDown
Represents a control that enables single value selection from a numeric range of values through a Spinner and TextBox.

Accordion
Represents a collection of collapsed and expanded AccordionItem controls.

TimeUpDown
Represents a control that uses a spinner and textbox to allow a user to input time.

TimePicker & ListTimePickerPopup
TimePicker represents a control that allows the user to select a time.
ListTimePickerPopup represents a time picker popup that allows choosing time from a ListBox.

TimePicker & RangeTimePickerPopup
TimePicker represents a control that allows the user to select a time.
RangeTimePickerPopup represents a time picker popup that allows choosing time through 3 sliders: Hours, Minutes and seconds.

DomainUpDown
Represents a control that enables single value selection from a domain of values through a Spinner and TextBox.

GlobalCalendar
Represents a control that enables a user to select a date by using a visual calendar display as well as providing extension points for representing modified Gregorian calendar systems.
Rating
Represents a control that can be used to display or allow users to interactively select a rating value.
TreeMap
Displays a hierarchy of data as a set of nested rectangles
Expander
Represents a control that displays a header and has a collapsible content window.

HeaderedContentControl
The base class for all controls that contain single content and have a header.

HeaderedItemsControl
Represents a control that contains multiple items and have a header.

Label
Represents the text label for a control.

Viewbox
Defines a content decorator that can stretch and scale a single child to fill the available space.

DockPanel
Defines an area where you can arrange child elements either horizontally or vertically, relative to each other.

WrapPanel
Positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box.

GridSplitter
Represents a control that redistributes space between the rows of columns of a Grid control.

TabControl
Represents a control that contains multiple items that share the same space on the screen.

DatePicker
Represents a control that allows the user to select a date.

Calendar
Represents a control that enables a user to select a date by using a visual calendar display.

LayoutTransformer
Represents a control that applies a layout transformation to its Content.

TransitioningContentControl
Represents a control with a single piece of content and when that content changes performs a transition animation.

Chart:
ColumnSeries
Represents a control that contains a data series to be rendered in column format.

PieSeries
Represents a control that contains a data series to be rendered in pie format.

AreaSeries
Represents a control that contains a data series to be rendered in X/Y line format.

BarSeries
Represents a control that contains a data series to be rendered in bar format.

LineSeries
Represents a control that contains a data series to be rendered in X/Y line format.

ScatterSeries
Represents a control that contains a data series to be rendered in X/Y scatter format.

BubbleSeries
Represents a control that contains a data series to be rendered in X/Y line format. A third axis binding determines the size of the data point.

DynamicSeries
Using a ObservableCollection (or INotifyCollectionChanged) as a Series.ItemSource causes the Chart to update once the underlying data source updates.

Theming

ImplicitStyleManager
Encapsulates an attached behavior that propagates styles in a framework element's associated resource dictionary to its children. The class also provides attached properties that allow the resource dictionary to be loaded from an external source.

ExpressionDarkTheme
Implicitly applies the Expression dark theme to all of its descendent FrameworkElements.

ExpressionLightTheme
Implicitly applies the Expression light theme to all of its descendent FrameworkElements.

RainierPurpleTheme
Implicitly applies the Rainier purple theme to all of its descendent FrameworkElements.

RainierOrangeTheme
Implicitly applies the Rainier orange theme to all of its descendent FrameworkElements.

ShinyBlueTheme
Implicitly applies the Shiny Blue theme to all of its descendent FrameworkElements

ShinyRedTheme
Implicitly applies the Shiny Red theme to all of its descendent FrameworkElements.

BureauBlackTheme
Implicitly applies the Bureau Black theme to all of its descendent FrameworkElements.

BureauBlueTheme
Implicitly applies the Bureau Blue theme to all of its descendent FrameworkElements

WhistlerBlueTheme
Implicitly applies the Whistler Blue theme to all of its descendent FrameworkElements.

TwilightBlueTheme
Implicitly applies the Twilight Blue theme to all of its descendent FrameworkElements.

BubbleCremeTheme
Implicitly applies the Bubble Creme theme to all of its descendent FrameworkElements.


By
Usama Wahab Khan and Atif Shahzad