ASP.NET – Security ”; Previous Next Implementing security in a site has the following aspects: Authentication : It is the process of ensuring the user”s identity and authenticity. ASP.NET allows four types of authentications: Windows Authentication Forms Authentication Passport Authentication Custom Authentication Authorization : It is the process of defining and allotting specific roles to specific users. Confidentiality : It involves encrypting the channel between the client browser and the web server. Integrity : It involves maintaining the integrity of data. For example, implementing digital signature. Forms-Based Authentication Traditionally, forms-based authentication involves editing the web.config file and adding a login page with appropriate authentication code. The web.config file could be edited and the following codes written on it: <configuration> <system.web> <authentication mode=”Forms”> <forms loginUrl =”login.aspx”/> </authentication> <authorization> <deny users=”?”/> </authorization> </system.web> … … </configuration> The login.aspx page mentioned in the above code snippet could have the following code behind file with the usernames and passwords for authentication hard coded into it. protected bool authenticate(String uname, String pass) { if(uname == “Tom”) { if(pass == “tom123”) return true; } if(uname == “Dick”) { if(pass == “dick123”) return true; } if(uname == “Harry”) { if(pass == “har123”) return true; } return false; } public void OnLogin(Object src, EventArgs e) { if (authenticate(txtuser.Text, txtpwd.Text)) { FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked); } else { Response.Write(“Invalid user name or password”); } } Observe that the FormsAuthentication class is responsible for the process of authentication. However, Visual Studio allows you to implement user creation, authentication, and authorization with seamless ease without writing any code, through the Web Site Administration tool. This tool allows creating users and roles. Apart from this, ASP.NET comes with readymade login controls set, which has controls performing all the jobs for you. Implementing Forms-Based Security To set up forms-based authentication, you need the following: A database of users to support the authentication process A website that uses the database User accounts Roles Restriction of users and group activities A default page, to display the login status of the users and other information. A login page, to allow users to log in, retrieve password, or change password To create users, take the following steps: Step (1) : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool. Step (2) : Click on the Security tab. Step (3) : Select the authentication type to ”Forms based authentication” by selecting the ”From the Internet” radio button. Step (4) : Click on ”Create Users” link to create some users. If you already had created roles, you could assign roles to the user, right at this stage. Step (5) : Create a web site and add the following pages: Welcome.aspx Login.aspx CreateAccount.aspx PasswordRecovery.aspx ChangePassword.aspx Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two templates: LoggedIn and LoggedOut. In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the control. You can change the login and logout text properties of the control from the Properties window. Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is logged in or not. This control has two view templates: Anonymous template and LoggedIn template. Select each view and write some text for the users to be displayed for each template. The text should be placed on the area marked red. Step (8) : The users for the application are created by the developer. You might want to allow a visitor to create a user account. For this, add a link beneath the LoginView control, which should link to the CreateAccount.aspx page. Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl property of this control to Welcome.aspx. Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links to the Login.aspx. To change this default, make the following changes in the web.config file. For example, if you want to name your log in page as signup.aspx, add the following lines to the <authentication> section of the web.config: <configuration> <system.web> <authentication mode=”Forms”> <forms loginUrl =”signup.aspx” defaultUrl = “Welcome.aspx†/> </authentication> </system.web> </configuration> Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the account. Select the Login control. Open its smart tag and click ”Convert to Template”. Customize the UI of the control to place a hyperlink control under the login button, which should link to the PassWordRecovery.aspx. Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email server to send the passwords to the users. Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView control in Welcome.aspx. Step (14) : Place a ChangePassword control on the change password page. This control also has two views. Now run the application and observe different security operations. To create roles, go back to the Web Application Administration Tools and click on the Security tab. Click on ”Create Roles” and create some roles for the application. Click on the ”Manage Users” link and assign roles to the users. IIS Authentication: SSL The Secure Socket Layer or SSL is the protocol used to ensure a secure connection. With SSL enabled, the browser encrypts all data sent to the server and decrypts all data coming from the server. At the same time, the server encrypts and decrypts all data to and from browser. The URL for a secure connection starts with HTTPS instead of HTTP. A small lock is displayed by a browser using a secure connection. When a browser makes an initial attempt to communicate with a server over a secure connection using SSL, the server authenticates itself by sending its digital certificate. To use the SSL, you need to buy a digital secure certificate
Category: asp.net
ASP.NET – Multi Views
ASP.NET – Multi Views ”; Previous Next MultiView and View controls allow you to divide the content of a page into different groups, displaying only one group at a time. Each View control manages one group of content and all the View controls are held together in a MultiView control. The MultiView control is responsible for displaying one View control at a time. The View displayed is called the active view. The syntax of MultiView control is: <asp:MultView ID= “MultiView1” runat= “server”> </asp:MultiView> The syntax of View control is: <asp:View ID= “View1” runat= “server”> </asp:View> However, the View control cannot exist on its own. It would render error if you try to use it stand-alone. It is always used with a Multiview control as: <asp:MultView ID= “MultiView1” runat= “server”> <asp:View ID= “View1” runat= “server”> </asp:View> </asp:MultiView> Properties of View and MultiView Controls Both View and MultiView controls are derived from Control class and inherit all its properties, methods, and events. The most important property of the View control is Visible property of type Boolean, which sets the visibility of a view. The MultiView control has the following important properties: Properties Description Views Collection of View controls within the MultiView. ActiveViewIndex A zero based index that denotes the active view. If no view is active, then the index is -1. The CommandName attribute of the button control associated with the navigation of the MultiView control are associated with some related field of the MultiView control. For example, if a button control with CommandName value as NextView is associated with the navigation of the multiview, it automatically navigates to the next view when the button is clicked. The following table shows the default command names of the above properties: Properties Description NextViewCommandName NextView PreviousViewCommandName PrevView SwitchViewByIDCommandName SwitchViewByID SwitchViewByIndexCommandName SwitchViewByIndex The important methods of the multiview control are: Methods Description SetActiveview Sets the active view GetActiveview Retrieves the active view Every time a view is changed, the page is posted back to the server and a number of events are raised. Some important events are: Events Description ActiveViewChanged Raised when a view is changed Activate Raised by the active view Deactivate Raised by the inactive view Apart from the above mentioned properties, methods and events, multiview control inherits the members of the control and object class. Example The example page has three views. Each view has two button for navigating through the views. The content file code is as follows: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”multiviewdemo._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> <h2>MultiView and View Controls</h2> <asp:DropDownList ID=”DropDownList1″ runat=”server” onselectedindexchanged=”DropDownList1_SelectedIndexChanged”> </asp:DropDownList> <hr /> <asp:MultiView ID=”MultiView1″ runat=”server” ActiveViewIndex=”2″ onactiveviewchanged=”MultiView1_ActiveViewChanged” > <asp:View ID=”View1″ runat=”server”> <h3>This is view 1</h3> <br /> <asp:Button CommandName=”NextView” ID=”btnnext1″ runat=”server” Text = “Go To Next” /> <asp:Button CommandArgument=”View3″ CommandName=”SwitchViewByID” ID=”btnlast” runat=”server” Text =”Go To Last” /> </asp:View> <asp:View ID=”View2″ runat=”server”> <h3>This is view 2</h3> <asp:Button CommandName=”NextView” ID=”btnnext2″ runat=”server” Text = “Go To Next” /> <asp:Button CommandName=”PrevView” ID=”btnprevious2″ runat=”server” Text = “Go To Previous View” /> </asp:View> <asp:View ID=”View3″ runat=”server”> <h3> This is view 3</h3> <br /> <asp:Calendar ID=”Calender1″ runat=”server”></asp:Calendar> <br /> <asp:Button CommandArgument=”0″ CommandName=”SwitchViewByIndex” ID=”btnfirst” runat=”server” Text = “Go To Next” /> <asp:Button CommandName=”PrevView” ID=”btnprevious” runat=”server” Text = “Go To Previous View” /> </asp:View> </asp:MultiView> </div> </form> </body> </html> Observe the following: The MultiView.ActiveViewIndex determines which view will be shown. This is the only view rendered on the page. The default value for the ActiveViewIndex is -1, when no view is shown. Since the ActiveViewIndex is defined as 2 in the example, it shows the third view, when executed. Print Page Previous Next Advertisements ”;
ASP.NET – AJAX Control
ASP.NET – Ajax Control ”; Previous Next 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” 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 contains 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: 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 executed, 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. A page can contain multiple update panels with each panel containing other controls like a grid and displaying different part of data. When a total post back occurs, the update panel content 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: Properties Description ChildrenAsTriggers This property indicates whether the post backs are coming from the child controls, which cause the update panel to refresh. ContentTemplate It is the content template and defines what appears in the update panel when it is rendered. ContentTemplateContainer Retrieves the dynamically created template container object and used for adding child controls programmatically. IsInPartialRendering Indicates whether the panel is being updated as part of the partial post back. RenderMode Shows the render modes. The available modes are Block and Inline. UpdateMode Gets or sets the rendering mode by determining some conditions. Triggers Defines 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: Methods Description CreateContentTemplateContainer Creates a Control object that acts as a container for child controls that define the UpdatePanel control”s content. CreateControlCollection Returns the collection of all controls that are contained in the UpdatePanel control. Initialize Initializes the UpdatePanel control trigger collection if partial-page rendering is enabled. Update Causes an update of the content of an UpdatePanel control. The behavior of the update panel depends upon the values of the UpdateMode property and ChildrenAsTriggers property. UpdateMode ChildrenAsTriggers Effect Always False Illegal parameters. Always True UpdatePanel refreshes if whole page refreshes or a child control on it posts back. Conditional False UpdatePanel refreshes if whole page refreshes or a triggering control outside it initiates a refresh. Conditional True UpdatePanel 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 displays 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: Properties Description AssociatedUpdatePanelID Gets and sets the ID of the update panel with which this control is associated. Attributes Gets or sets the cascading style sheet (CSS) attributes of the UpdateProgress control. DisplayAfter Gets and sets the time in milliseconds after which the progress template is displayed. The default is 500. DynamicLayout Indicates whether the progress template is dynamically rendered. ProgressTemplate Indicates the template displayed during an asynchronous post back which takes more time than the DisplayAfter time.
ASP.NET – Configuration
ASP.NET – Configuration ”; Previous Next The behavior of an ASP.NET application is affected by different settings in the configuration files: machine.config web.config The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file. If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict, or override any settings defined on the upper level. Visual Studio generates a default web.config file for each project. An application can execute without a web.config file, however, you cannot debug an application without a web.config file. The following figure shows the Solution Explorer for the sample example used in the web services tutorial: In this application, there are two web.config files for two projects i.e., the web service and the web site calling the web service. The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area. The following code snippet shows the basic syntax of a configuration file: <configuration> <!– Configuration section-handler declaration area. –> <configSections> <section name=”section1″ type=”section1Handler” /> <section name=”section2″ type=”section2Handler” /> </configSections> <!– Configuration section settings area. –> <section1> <s1Setting1 attribute1=”attr1″ /> </section1> <section2> <s2Setting1 attribute1=”attr1″ /> </section2> <system.web> <authentication mode=”Windows” /> </system.web> </configuration> Configuration Section Handler declarations The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides some configuration data. It has the following basic syntax: <configSections> <section /> <sectionGroup /> <remove /> <clear/> </configSections> It has the following elements: Clear – It removes all references to inherited sections and section groups. Remove – It removes a reference to an inherited section and section group. Section – It defines an association between a configuration section handler and a configuration element. Section group – It defines an association between a configuration section handler and a configuration section. Application Settings The application settings allow storing application-wide name-value pairs for read-only access. For example, you can define a custom application setting as: <configuration> <appSettings> <add key=”Application Name” value=”MyApplication” /> </appSettings> </configuration> For example, you can also store the name of a book and its ISBN number: <configuration> <appSettings> <add key=”appISBN” value=”0-273-68726-3″ /> <add key=”appBook” value=”Corporate Finance” /> </appSettings> </configuration> Connection Strings The connection strings show which database connection strings are available to the website. For example: <connectionStrings> <add name=”ASPDotNetStepByStepConnectionString” connectionString=”Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\projectsdatacaching / datacachingApp_DataASPDotNetStepByStep.mdb” providerName=”System.Data.OleDb” /> <add name=”booksConnectionString” connectionString=”Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C: databindingApp_Databooks.mdb” providerName=”System.Data.OleDb” /> </connectionStrings> System.Web Element The system.web element specifies the root element for the ASP.NET configuration section and contains configuration elements that configure ASP.NET Web applications and control how the applications behave. It holds most of the configuration elements needed to be adjusted in common applications. The basic syntax for the element is as given: <system.web> <anonymousIdentification> <authentication> <authorization> <browserCaps> <caching> <clientTarget> <compilation> <customErrors> <deployment> <deviceFilters> <globalization> <healthMonitoring> <hostingEnvironment> <httpCookies> <httpHandlers> <httpModules> <httpRuntime> <identity> <machineKey> <membership> <mobileControls> <pages> <processModel> <profile> <roleManager> <securityPolicy> <sessionPageState> <sessionState> <siteMap> <trace> <trust> <urlMappings> <webControls> <webParts> <webServices> <xhtmlConformance> </system.web> The following table provides brief description of some of common sub elements of the system.web element: AnonymousIdentification This is required to identify users who are not authenticated when authorization is required. Authentication It configures the authentication support. The basic syntax is as given: <authentication mode=”[Windows|Forms|Passport|None]”> <forms>…</forms> <passport/> </authentication> Authorization It configures the authorization support. The basic syntax is as given: <authorization> <allow …/> <deny …/> </authorization> Caching It Configures the cache settings. The basic syntax is as given: <caching> <cache>…</cache> <outputCache>…</outputCache> <outputCacheSettings>…</outputCacheSettings> <sqlCacheDependency>…</sqlCacheDependency> </caching> CustomErrors It defines custom error messages. The basic syntax is as given: <customErrors defaultRedirect=”url” mode=”On|Off|RemoteOnly”> <error. . ./> </customErrors> Deployment It defines configuration settings used for deployment. The basic syntax is as follows: <deployment retail=”true|false” /> HostingEnvironment It defines configuration settings for hosting environment. The basic syntax is as follows: <hostingEnvironment idleTimeout=”HH:MM:SS” shadowCopyBinAssemblies=”true|false” shutdownTimeout=”number” urlMetadataSlidingExpiration=”HH:MM:SS” /> Identity It configures the identity of the application. The basic syntax is as given: <identity impersonate=”true|false” userName=”domainusername” password=”<secure password>”/> MachineKey It configures keys to use for encryption and decryption of Forms authentication cookie data. It also allows configuring a validation key that performs message authentication checks on view-state data and forms authentication tickets. The basic syntax is: <machineKey validationKey=”AutoGenerate,IsolateApps” [String] decryptionKey=”AutoGenerate,IsolateApps” [String] validation=”HMACSHA256″ [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name] decryption=”Auto” [Auto | DES | 3DES | AES | alg:algorithm_name] /> Membership This configures parameters of managing and authenticating user accounts. The basic syntax is: <membership defaultProvider=”provider name” userIsOnlineTimeWindow=”number of minutes” hashAlgorithmType=”SHA1″> <providers>…</providers> </membership> Pages It provides page-specific configurations. The basic syntax is: <pages asyncTimeout=”number” autoEventWireup=”[True|False]” buffer=”[True|False]” clientIDMode=”[AutoID|Predictable|Static]” compilationMode=”[Always|Auto|Never]” controlRenderingCompatibilityVersion=”[3.5|4.0]” enableEventValidation=”[True|False]” enableSessionState=”[True|False|ReadOnly]” enableViewState=”[True|False]” enableViewStateMac=”[True|False]” maintainScrollPositionOnPostBack=”[True|False]” masterPageFile=”file path” maxPageStateFieldLength=”number” pageBaseType=”typename, assembly” pageParserFilterType=”string” smartNavigation=”[True|False]” styleSheetTheme=”string” theme=”string” userControlBaseType=”typename” validateRequest=”[True|False]” viewStateEncryptionMode=”[Always|Auto|Never]” > <controls>…</controls> <namespaces>…</namespaces> <tagMapping>…</tagMapping> <ignoreDeviceFilters>…</ignoreDeviceFilters> </pages> Profile It configures user profile parameters. The basic syntax is: <profile enabled=”true|false” inherits=”fully qualified type reference” automaticSaveEnabled=”true|false” defaultProvider=”provider name”> <properties>…</properties> <providers>…</providers> </profile> RoleManager It configures settings for user roles. The basic syntax is: <roleManager cacheRolesInCookie=”true|false” cookieName=”name” cookiePath=”/” cookieProtection=”All|Encryption|Validation|None” cookieRequireSSL=”true|false ” cookieSlidingExpiration=”true|false ” cookieTimeout=”number of minutes” createPersistentCookie=”true|false” defaultProvider=”provider name” domain=”cookie domain”> enabled=”true|false” maxCachedResults=”maximum number of role names cached” <providers>…</providers> </roleManager> SecurityPolicy It configures the security policy. The basic syntax is: <securityPolicy> <trustLevel /> </securityPolicy> UrlMappings It defines mappings to hide the original URL and provide a more user friendly URL. The basic syntax is: <urlMappings enabled=”true|false”> <add…/> <clear /> <remove…/> </urlMappings> WebControls It provides the name of shared location for client scripts. The basic syntax is: <webControls clientScriptsLocation=”String” /> WebServices This configures the web services. Print Page Previous
ASP.NET – Calendars
ASP.NET – Calendars ”; Previous Next The calendar control is a functionally rich web control, which provides the following capabilities: Displaying one month at a time Selecting a day, a week or a month Selecting a range of days Moving from month to month Controlling the display of the days programmatically The basic syntax of a calendar control is: <asp:Calender ID = “Calendar1” runat = “server”> </asp:Calender> Properties and Events of the Calendar Control The calendar control has many properties and events, using which you can customize the actions and display of the control. The following table provides some important properties of the Calendar control: Properties Description Caption Gets or sets the caption for the calendar control. CaptionAlign Gets or sets the alignment for the caption. CellPadding Gets or sets the number of spaces between the data and the cell border. CellSpacing Gets or sets the space between cells. DayHeaderStyle Gets the style properties for the section that displays the day of the week. DayNameFormat Gets or sets format of days of the week. DayStyle Gets the style properties for the days in the displayed month. FirstDayOfWeek Gets or sets the day of week to display in the first column. NextMonthText Gets or sets the text for next month navigation control. The default value is >. NextPrevFormat Gets or sets the format of the next and previous month navigation control. OtherMonthDayStyle Gets the style properties for the days on the Calendar control that are not in the displayed month. PrevMonthText Gets or sets the text for previous month navigation control. The default value is <. SelectedDate Gets or sets the selected date. SelectedDates Gets a collection of DateTime objects representing the selected dates. SelectedDayStyle Gets the style properties for the selected dates. SelectionMode Gets or sets the selection mode that specifies whether the user can select a single day, a week or an entire month. SelectMonthText Gets or sets the text for the month selection element in the selector column. SelectorStyle Gets the style properties for the week and month selector column. SelectWeekText Gets or sets the text displayed for the week selection element in the selector column. ShowDayHeader Gets or sets the value indicating whether the heading for the days of the week is displayed. ShowGridLines Gets or sets the value indicating whether the gridlines would be shown. ShowNextPrevMonth Gets or sets a value indicating whether next and previous month navigation elements are shown in the title section. ShowTitle Gets or sets a value indicating whether the title section is displayed. TitleFormat Gets or sets the format for the title section. Titlestyle Get the style properties of the title heading for the Calendar control. TodayDayStyle Gets the style properties for today”s date on the Calendar control. TodaysDate Gets or sets the value for today”s date. UseAccessibleHeader Gets or sets a value that indicates whether to render the table header <th> HTML element for the day headers instead of the table data <td> HTML element. VisibleDate Gets or sets the date that specifies the month to display. WeekendDayStyle Gets the style properties for the weekend dates on the Calendar control. The Calendar control has the following three most important events that allow the developers to program the calendar control. They are: Events Description SelectionChanged It is raised when a day, a week or an entire month is selected. DayRender It is raised when each data cell of the calendar control is rendered. VisibleMonthChanged It is raised when user changes a month. Working with the Calendar Control Putting a bare-bone calendar control without any code behind file provides a workable calendar to a site, which shows the months and days of the year. It also allows navigation to next and previous months. Calendar controls allow the users to select a single day, a week, or an entire month. This is done by using the SelectionMode property. This property has the following values: Properties Description Day To select a single day. DayWeek To select a single day or an entire week. DayWeekMonth To select a single day, a week, or an entire month. None Nothing can be selected. The syntax for selecting days: <asp:Calender ID = “Calendar1” runat = “server” SelectionMode=”DayWeekMonth”> </asp:Calender> When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears for selecting the week, and a >> symbol appears to the left of the days name for selecting the month. Example The following example demonstrates selecting a date and displays the date in a label: The content file code is as follows: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”calendardemo._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> Your Birthday:</h3> <asp:Calendar ID=”Calendar1″ runat=”server SelectionMode=”DayWeekMonth” onselectionchanged=”Calendar1_SelectionChanged”> </asp:Calendar> </div> <p>Todays date is: <asp:Label ID=”lblday” runat=”server”></asp:Label> </p> <p>Your Birday is: <asp:Label ID=”lblbday” runat=”server”></asp:Label> </p> </form> </body> </html> The event handler for the event SelectionChanged: protected void Calendar1_SelectionChanged(object sender, EventArgs e) { lblday.Text = Calendar1.TodaysDate.ToShortDateString(); lblbday.Text = Calendar1.SelectedDate.ToShortDateString(); } When the file is run, it should produce the following output: Print Page Previous Next Advertisements ”;
ASP.NET – Personalization
ASP.NET – Personalization ”; Previous Next Web sites are designed for repeated visits from the users. Personalization allows a site to remember the user identity and other information details, and it presents an individualistic environment to each user. ASP.NET provides services for personalizing a web site to suit a particular client”s taste and preference. Understanding Profiles ASP.NET personalization service is based on user profile. User profile defines the kind of information about the user that the site needs. For example, name, age, address, date of birth, and phone number. This information is defined in the web.config file of the application and ASP.NET runtime reads and uses it. This job is done by the personalization providers. The user profiles obtained from user data is stored in a default database created by ASP.NET. You can create your own database for storing profiles. The profile data definition is stored in the configuration file web.config. Example Let us create a sample site, where we want our application to remember user details like name, address, date of birth etc. Add the profile details in the web.config file within the <system.web> element. <configuration> <system.web> <profile> <properties> <add name=”Name” type =”String”/> <add name=”Birthday” type =”System.DateTime”/> <group name=”Address”> <add name=”Street”/> <add name=”City”/> <add name=”State”/> <add name=”Zipcode”/> </group> </properties> </profile> </system.web> </configuration> When the profile is defined in the web.config file, the profile could be used through the Profile property found in the current HttpContext and also available via page. Add the text boxes to take the user input as defined in the profile and add a button for submitting the data: Update Page_load to display profile information: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { ProfileCommon pc=this.Profile.GetProfile(Profile.UserName); if (pc != null) { this.txtname.Text = pc.Name; this.txtaddr.Text = pc.Address.Street; this.txtcity.Text = pc.Address.City; this.txtstate.Text = pc.Address.State; this.txtzip.Text = pc.Address.Zipcode; this.Calendar1.SelectedDate = pc.Birthday; } } } } Write the following handler for the Submit button, for saving the user data into the profile: protected void btnsubmit_Click(object sender, EventArgs e) { ProfileCommon pc=this.Profile.GetProfile(Profile.UserName); if (pc != null) { pc.Name = this.txtname.Text; pc.Address.Street = this.txtaddr.Text; pc.Address.City = this.txtcity.Text; pc.Address.State = this.txtstate.Text; pc.Address.Zipcode = this.txtzip.Text; pc.Birthday = this.Calendar1.SelectedDate; pc.Save(); } } When the page is executed for the first time, the user needs to enter the information. However, next time the user details would be automatically loaded. Attributes for the <add> Element Apart from the name and type attributes that we have used, there are other attributes to the <add> element. Following table illustrates some of these attributes: Attributes Description name The name of the property. type By default the type is string but it allows any fully qualified class name as data type. serializeAs The format to use when serializing this value. readOnly A read only profile value cannot be changed, by default this property is false. defaultValue A default value that is used if the profile does not exist or does not have information. allowAnonymous A Boolean value indicating whether this property can be used with the anonymous profiles. Provider The profiles provider that should be used to manage just this property. Anonymous Personalization Anonymous personalization allows the user to personalize the site before identifying themselves. For example, Amazon.com allows the user to add items in the shopping cart before they log in. To enable this feature, the web.config file could be configured as: <anonymousIdentification enabled =”true” cookieName=”.ASPXANONYMOUSUSER” cookieTimeout=”120000″ cookiePath=”/” cookieRequiresSSL=”false” cookieSlidingExpiration=”true” cookieprotection=”Encryption” coolieless=”UseDeviceProfile”/> Print Page Previous Next Advertisements ”;
ASP.NET – Data Binding
ASP.NET – Data Binding ”; Previous Next Every ASP.NET web form control inherits the DataBind method from its parent Control class, which gives it an inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline data binding. Simple data binding involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control. On the other hand, some controls can bind records, lists, or columns of data into their structure through a DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative data binding. The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and editing data collections. The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes: DataBoundControl HierarchicalDataBoundControl The abstract class DataBoundControl is again inherited by two more abstract classes: ListControl CompositeDataBoundControl The controls capable of simple data binding are derived from the ListControl abstract class and these controls are: BulletedList CheckBoxList DropDownList ListBox RadioButtonList The controls capable of declarative data binding (a more complex data binding) are derived from the abstract class CompositeDataBoundControl. These controls are: DetailsView FormView GridView RecordList Simple Data Binding Simple data binding involves the read-only selection lists. These controls can bind to an array list or fields from a database. Selection lists takes two values from the database or the data source; one value is displayed by the list and the other is considered as the value corresponding to the display. Let us take up a small example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data source control to retrieve two values from your database (we use the same DotNetReferences table as in the previous chapter). Choosing a data source for the bulleted list control involves: Selecting the data source control Selecting a field to display, which is called the data field Selecting a field for the value When the application is executed, check that the entire title column is bound to the bulleted list and displayed. Declarative Data Binding We have already used declarative data binding in the previous tutorial using GridView control. The other composite data bound controls capable of displaying and manipulating data in a tabular manner are the DetailsView, FormView, and RecordList control. In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET. However, the data binding involves the following objects: A dataset that stores the data retrieved from the database. The data provider, which retrieves data from the database by using a command over a connection. The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements. Relation between the data binding objects: Example Let us take the following steps: Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in the Solution Explorer and choosing the item ”Class” from the ”Add Item” dialog box. Name it as booklist.cs. using System; using System.Data; using System.Configuration; 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; namespace databinding { public class booklist { protected String bookname; protected String authorname; public booklist(String bname, String aname) { this.bookname = bname; this.authorname = aname; } public String Book { get { return this.bookname; } set { this.bookname = value; } } public String Author { get { return this.authorname; } set { this.authorname = value; } } } } Step (2) : Add four list controls on the page a list box control, a radio button list, a check box list, and a drop down list and four labels along with these list controls. The page should look like this in design view: The source file should look as the following: <form id=”form1″ runat=”server”> <div> <table style=”width: 559px”> <tr> <td style=”width: 228px; height: 157px;”> <asp:ListBox ID=”ListBox1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”ListBox1_SelectedIndexChanged”> </asp:ListBox> </td> <td style=”height: 157px”> <asp:DropDownList ID=”DropDownList1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”DropDownList1_SelectedIndexChanged”> </asp:DropDownList> </td> </tr> <tr> <td style=”width: 228px; height: 40px;”> <asp:Label ID=”lbllistbox” runat=”server”></asp:Label> </td> <td style=”height: 40px”> <asp:Label ID=”lbldrpdown” runat=”server”> </asp:Label> </td> </tr> <tr> <td style=”width: 228px; height: 21px”> </td> <td style=”height: 21px”> </td> </tr> <tr> <td style=”width: 228px; height: 21px”> <asp:RadioButtonList ID=”RadioButtonList1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”RadioButtonList1_SelectedIndexChanged”> </asp:RadioButtonList> </td> <td style=”height: 21px”> <asp:CheckBoxList ID=”CheckBoxList1″ runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”CheckBoxList1_SelectedIndexChanged”> </asp:CheckBoxList> </td> </tr> <tr> <td style=”width: 228px; height: 21px”> <asp:Label ID=”lblrdlist” runat=”server”> </asp:Label> </td> <td style=”height: 21px”> <asp:Label ID=”lblchklist” runat=”server”> </asp:Label> </td> </tr> </table> </div> </form> Step (3) : Finally, write the following code behind routines of the application: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { IList bklist = createbooklist(); if (!this.IsPostBack) { this.ListBox1.DataSource = bklist; this.ListBox1.DataTextField = “Book”; this.ListBox1.DataValueField = “Author”; this.DropDownList1.DataSource = bklist; this.DropDownList1.DataTextField = “Book”; this.DropDownList1.DataValueField = “Author”; this.RadioButtonList1.DataSource = bklist; this.RadioButtonList1.DataTextField = “Book”; this.RadioButtonList1.DataValueField = “Author”; this.CheckBoxList1.DataSource = bklist; this.CheckBoxList1.DataTextField = “Book”; this.CheckBoxList1.DataValueField = “Author”; this.DataBind(); } } protected IList createbooklist() { ArrayList allbooks = new ArrayList(); booklist bl; bl = new booklist(“UNIX CONCEPTS”, “SUMITABHA DAS”); allbooks.Add(bl); bl = new booklist(“PROGRAMMING IN C”, “RICHI KERNIGHAN”); allbooks.Add(bl); bl = new booklist(“DATA STRUCTURE”, “TANENBAUM”); allbooks.Add(bl); bl = new booklist(“NETWORKING CONCEPTS”, “FOROUZAN”); allbooks.Add(bl); bl = new booklist(“PROGRAMMING IN C++”, “B. STROUSTROUP”); allbooks.Add(bl); bl = new booklist(“ADVANCED JAVA”, “SUMITABHA DAS”); allbooks.Add(bl); return allbooks; } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { this.lbllistbox.Text = this.ListBox1.SelectedValue; } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { this.lbldrpdown.Text = this.DropDownList1.SelectedValue; } protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e) { this.lblrdlist.Text = this.RadioButtonList1.SelectedValue; } protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e) { this.lblchklist.Text = this.CheckBoxList1.SelectedValue; } } Observe the following: The booklist class has two properties: bookname and authorname. The createbooklist method is a user defined method that creates an array of booklist objects named allbooks. The Page_Load event handler ensures that a list of books is created. The
ASP.NET – Panel Controls
ASP.NET – Panel Controls ”; Previous Next The Panel control works as a container for other controls on the page. It controls the appearance and visibility of the controls it contains. It also allows generating controls programmatically. The basic syntax of panel control is as follows: <asp:Panel ID= “Panel1” runat = “server”> </asp:Panel> The Panel control is derived from the WebControl class. Hence it inherits all the properties, methods and events of the same. It does not have any method or event of its own. However it has the following properties of its own: Properties Description BackImageUrl URL of the background image of the panel. DefaultButton Gets or sets the identifier for the default button that is contained in the Panel control. Direction Text direction in the panel. GroupingText Allows grouping of text as a field. HorizontalAlign Horizontal alignment of the content in the panel. ScrollBars Specifies visibility and location of scrollbars within the panel. Wrap Allows text wrapping. Working with the Panel Control Let us start with a simple scrollable panel of specific height and width and a border style. The ScrollBars property is set to both the scrollbars, hence both the scrollbars are rendered. The source file has the following code for the panel tag: <asp:Panel ID=”Panel1″ runat=”server” BorderColor=”#990000″ BorderStyle=”Solid” Borderstyle=”width:1px” Height=”116px” ScrollBars=”Both” style=”width:278px”> This is a scrollable panel. <br /> <br /> <asp:Button ID=”btnpanel” runat=”server” Text=”Button” style=”width:82px” /> </asp:Panel> The panel is rendered as follows: Example The following example demonstrates dynamic content generation. The user provides the number of label controls and textboxes to be generated on the panel. The controls are generated programmatically. Change the properties of the panel using the properties window. When you select a control on the design view, the properties window displays the properties of that particular control and allows you to make changes without typing. The source file for the example is as follows: <form id=”form1″ runat=”server”> <div> <asp:Panel ID=”pnldynamic” runat=”server” BorderColor=”#990000″ BorderStyle=”Solid” Borderstyle=”width:1px” Height=”150px” ScrollBars=”Auto” style=”width:60%” BackColor=”#CCCCFF” Font-Names=”Courier” HorizontalAlign=”Center”> This panel shows dynamic control generation: <br /> <br /> </asp:Panel> </div> <table style=”width: 51%;”> <tr> <td class=”style2″>No of Labels:</td> <td class=”style1″> <asp:DropDownList ID=”ddllabels” runat=”server”> <asp:ListItem>0</asp:ListItem> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem>4</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td class=”style2″> </td> <td class=”style1″> </td> </tr> <tr> <td class=”style2″>No of Text Boxes :</td> <td class=”style1″> <asp:DropDownList ID=”ddltextbox” runat=”server”> <asp:ListItem>0</asp:ListItem> <asp:ListItem Value=”1″></asp:ListItem> <asp:ListItem>2</asp:ListItem> <asp:ListItem>3</asp:ListItem> <asp:ListItem Value=”4″></asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td class=”style2″> </td> <td class=”style1″> </td> </tr> <tr> <td class=”style2″> <asp:CheckBox ID=”chkvisible” runat=”server” Text=”Make the Panel Visible” /> </td> <td class=”style1″> <asp:Button ID=”btnrefresh” runat=”server” Text=”Refresh Panel” style=”width:129px” /> </td> </tr> </table> </form> The code behind the Page_Load event is responsible for generating the controls dynamically: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //make the panel visible pnldynamic.Visible = chkvisible.Checked; //generating the lable controls: int n = Int32.Parse(ddllabels.SelectedItem.Value); for (int i = 1; i <= n; i++) { Label lbl = new Label(); lbl.Text = “Label” + (i).ToString(); pnldynamic.Controls.Add(lbl); pnldynamic.Controls.Add(new LiteralControl(“<br />”)); } //generating the text box controls: int m = Int32.Parse(ddltextbox.SelectedItem.Value); for (int i = 1; i <= m; i++) { TextBox txt = new TextBox(); txt.Text = “Text Box” + (i).ToString(); pnldynamic.Controls.Add(txt); pnldynamic.Controls.Add(new LiteralControl(“<br />”)); } } } When executed, the panel is rendered as: Print Page Previous Next Advertisements ”;
ASP.NET – Data Sources
ASP.NET – Data Sources ”; Previous Next A data source control interacts with the data-bound controls and hides the complex data binding processes. These are the tools that provide data to the data bound controls and support execution of operations like insertions, deletions, sorting, and updates. Each data source control wraps a particular data provider-relational databases, XML documents, or custom classes and helps in: Managing connection Selecting data Managing presentation aspects like paging, caching, etc. Manipulating data There are many data source controls available in ASP.NET for accessing data from SQL Server, from ODBC or OLE DB servers, from XML files, and from business objects. Based on type of data, these controls could be divided into two categories: Hierarchical data source controls Table-based data source controls The data source controls used for hierarchical data are: XMLDataSource – It allows binding to XML files and strings with or without schema information. SiteMapDataSource – It allows binding to a provider that supplies site map information. The data source controls used for tabular data are: Data source controls Description SqlDataSource It represents a connection to an ADO.NET data provider that returns SQL data, including data sources accessible via OLEDB and ODBC. ObjectDataSource It allows binding to a custom .Net business object that returns data. LinqdataSource It allows binding to the results of a Linq-to-SQL query (supported by ASP.NET 3.5 only). AccessDataSource It represents connection to a Microsoft Access database. Data Source Views Data source views are objects of the DataSourceView class. Which represent a customized view of data for different data operations such as sorting, filtering, etc. The DataSourceView class serves as the base class for all data source view classes, which define the capabilities of data source controls. The following table provides the properties of the DataSourceView class: Properties Description CanDelete Indicates whether deletion is allowed on the underlying data source. CanInsert Indicates whether insertion is allowed on the underlying data source. CanPage Indicates whether paging is allowed on the underlying data source. CanRetrieveTotalRowCount Indicates whether total row count information is available. CanSort Indicates whether the data could be sorted. CanUpdate Indicates whether updates are allowed on the underlying data source. Events Gets a list of event-handler delegates for the data source view. Name Name of the view. The following table provides the methods of the DataSourceView class: Methods Description CanExecute Determines whether the specified command can be executed. ExecuteCommand Executes the specific command. ExecuteDelete Performs a delete operation on the list of data that the DataSourceView object represents. ExecuteInsert Performs an insert operation on the list of data that the DataSourceView object represents. ExecuteSelect Gets a list of data from the underlying data storage. ExecuteUpdate Performs an update operation on the list of data that the DataSourceView object represents. Delete Performs a delete operation on the data associated with the view. Insert Performs an insert operation on the data associated with the view. Select Returns the queried data. Update Performs an update operation on the data associated with the view. OnDataSourceViewChanged Raises the DataSourceViewChanged event. RaiseUnsupportedCapabilitiesError Called by the RaiseUnsupportedCapabilitiesError method to compare the capabilities requested for an ExecuteSelect operation against those that the view supports. The SqlDataSource Control The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two important properties ConnectionString and ProviderName. The following code snippet provides the basic syntax of the control: <asp:SqlDataSource runat=”server” ID=”MySqlSource” ProviderName=”<%$ ConnectionStrings:LocalNWind.ProviderName %>” ConnectionString=”<%$ ConnectionStrings:LocalNWind %>” SelectionCommand= “SELECT * FROM EMPLOYEES” /> <asp:GridView ID=”GridView1″ runat=”server” DataSourceID=”MySqlSource” /> Configuring various data operations on the underlying data depends upon the various properties (property groups) of the data source control. The following table provides the related sets of properties of the SqlDataSource control, which provides the programming interface of the control: Property Group Description DeleteCommand, DeleteParameters, DeleteCommandType Gets or sets the SQL statement, parameters, and type for deleting rows in the underlying data. FilterExpression, FilterParameters Gets or sets the data filtering string and parameters. InsertCommand, InsertParameters, InsertCommandType Gets or sets the SQL statement, parameters, and type for inserting rows in the underlying database. SelectCommand, SelectParameters, SelectCommandType Gets or sets the SQL statement, parameters, and type for retrieving rows from the underlying database. SortParameterName Gets or sets the name of an input parameter that the command”s stored procedure will use to sort data. UpdateCommand, UpdateParameters, UpdateCommandType Gets or sets the SQL statement, parameters, and type for updating rows in the underlying data store. The following code snippet shows a data source control enabled for data manipulation: <asp:SqlDataSource runat=”server” ID= “MySqlSource” ProviderName=”<%$ ConnectionStrings:LocalNWind.ProviderName %>” ConnectionString=” <%$ ConnectionStrings:LocalNWind %>” SelectCommand= “SELECT * FROM EMPLOYEES” UpdateCommand= “UPDATE EMPLOYEES SET LASTNAME=@lame” DeleteCommand= “DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid” FilterExpression= “EMPLOYEEID > 10”> ….. ….. </asp:SqlDataSource> The ObjectDataSource Control The ObjectDataSource Control enables user-defined classes to associate the output of their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource control. Following are two important aspects of binding business objects: The bindable class should have a default constructor, it should be stateless, and have methods that can be mapped to select, update, insert, and delete semantics. The object must update one item at a time, batch operations are not supported. Let us go directly to an example to work with this control. The student class is the class to be used with an object data source. This class has three properties: a student id, name, and city. It has a default constructor and a GetStudents method for retrieving data. The student class: public class Student { public int StudentID { get; set; } public string Name { get; set; } public string City { get; set; } public Student() { } public DataSet GetStudents() { DataSet ds = new DataSet(); DataTable dt = new DataTable(“Students”); dt.Columns.Add(“StudentID”, typeof(System.Int32)); dt.Columns.Add(“StudentName”, typeof(System.String)); dt.Columns.Add(“StudentCity”, typeof(System.String)); dt.Rows.Add(new object[] { 1, “M. H. Kabir”, “Calcutta” }); dt.Rows.Add(new object[] { 2, “Ayan J. Sarkar”,
ASP.NET – Environment
ASP.NET – Environment Setup ”; Previous Next ASP.NET provides an abstraction layer on top of HTTP on which the web applications are built. It provides high-level entities such as classes and components within an object-oriented paradigm. The key development tool for building ASP.NET applications and front ends is Visual Studio. In this tutorial, we work with Visual Studio 2008. Visual Studio is an integrated development environment for writing, compiling, and debugging the code. It provides a complete set of development tools for building ASP.NET web applications, web services, desktop applications, and mobile applications. Installation Microsoft provides a free version of visual studio which also contains SQL Server and it can be downloaded from www.visualstudio.com. Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed. Step 2 − Click on the Install button and it will start the installation process. Step 3 − Once the installation process is completed successfully, you will see the following dialog. Close this dialog and restart your computer if required. Step 4 − Open Visual Studio from start Menu which will open the following dialog. It will be a while for the first time for preparation. Step 5 − Once all is done you will see the main window of Visual studio. Let’s create a new project from File → New → Project The Visual Studio IDE The new project window allows choosing an application template from the available templates. When you start a new web site, ASP.NET provides the starting folders and files for the site, including two files for the first web form of the site. The file named Default.aspx contains the HTML and asp code that defines the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for VB coding) contains the code in the language you have chosen and this code is responsible for the actions performed on a form. The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use the designer to design a web form, to add code to the control on the form so that the form works according to your need, you use the code editor. Working with Views and Windows You can work with windows in the following ways: To change the Web Forms Designer from one view to another, click on the Design or source button. To close a window, click on the close button on the upper right corner and to redisplay, select it from the View menu. To hide a window, click on its Auto Hide button. The window then changes into a tab. To display again, click the Auto Hide button again. To change the size of a window, just drag it. Adding Folders and Files to your Website When a new web form is created, Visual Studio automatically generates the starting HTML for the form and displays it in Source view of the web forms designer. The Solution Explorer is used to add any other files, folders or any existing item on the web site. To add a standard folder, right-click on the project or folder under which you are going to add the folder in the Solution Explorer and choose New Folder. To add an ASP.NET folder, right-click on the project in the Solution Explorer and select the folder from the list. To add an existing item to the site, right-click on the project or folder under which you are going to add the item in the Solution Explorer and select from the dialog box. Projects and Solutions A typical ASP.NET application consists of many items: the web content files (.aspx), source files (.cs files), assemblies (.dll and .exe files), data source files (.mdb files), references, icons, user controls and miscellaneous other files and folders. All these files that make up the website are contained in a Solution. When a new website is created. VB2008 automatically creates the solution and displays it in the solution explorer. Solutions may contain one or more projects. A project contains content files, source files, and other files like data sources and image files. Generally, the contents of a project are compiled into an assembly as an executable file (.exe) or a dynamic link library (.dll) file. Typically a project contains the following content files: Page file (.aspx) User control (.ascx) Web service (.asmx) Master page (.master) Site map (.sitemap) Website configuration file (.config) Building and Running a Project You can execute an application by: Selecting Start Selecting Start Without Debugging from the Debug menu, pressing F5 Ctrl-F5 The program is built meaning, the .exe or the .dll files are generated by selecting a command from the Build menu. Print Page Previous Next Advertisements ”;