Web App Notes 2
Web App Notes 2
Web App Notes 2
· First, open the Visual Studio then Go to File -> New ->
Project to create a new project and then select the language as Visual
C# from the left menu. Click on Windows Forms App(.NET
Framework) in the middle of current window. After that give the
project name and Click OK.
Here the solution is like a container which contains the projects and
files that may be required by the program.
· Now drag and drop the controls that you needed on created
Form. For example, if you can add TextBox, ListBox, Button etc. as
shown below. By clicking on the particular dropped control you can
see and change its properties present in the right most corner of
Visual Studio.
In the above image, you can see the TextBox is selected and its
properties like TextAlign, MaxLength etc. are opened in right most
corner. You can change its properties’ values as per the application
need. The code of controls will be automatically added in the
background. You can check the Form1.Designer.cs file present in the
Solution Explorer Window.
· To run the program you can use an F5 key or Play button present
in the toolbar of Visual Studio. To stop the program you can use
pause button present in the ToolBar. You can also run the program by
going to Debug->Start Debugging menu in the menubar.
Button in C#
A Button is an essential part of an application, or software, or
webpage. It allows the user to interact with the application or
software. For example, if a user wants to exit from the current
application so, he/she click the exit button which closes the
application. It can be used to perform many actions like to submit,
upload, download, etc. according to the requirement of your
program. It can be available with different shape, size, color, etc. and
you can reuse them in different applications. In .NET Framework,
Button class is used to represent windows button control and it is
inherited from ButtonBase class. It is defined
under System.Windows.Forms namespace.
C# | TextBox Controls
In Windows forms, TextBox plays an important role. With the help
of TextBox, the user can enter data in the application, it can be of a
single line or of multiple lines. The TextBox is a class and it is
defined under System.Windows.Forms namespace. In C#, you can
create a TextBox in two different ways:
1. Design-Time: It is the simplest way to create a TextBox as shown
in the following steps:
Step 1: Create a windows form. As shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and drop it on
the windows form. You can place TextBox anywhere on the
windows form according to your need.
Step 3: After drag and drop you will go to the properties of the
TextBox control to modify the TextBox design according to your
requirement.
Labels:-
Labels are one of the most frequently used C# control. We can use the
Label control to display text in a set location on the page. Label
controls can also be used to add descriptive text to a Form to provide
the user with helpful information. The Label class is defined in the
System.
Literals:-
Literals are constant values assigned to constant variables. Literals
represent fixed values that cannot be modified. Literals are a synthetic
representation of boolean, character, numeric, or string data, a
medium of expressing particular values in the program.
Image Controls:-
The PictureBox control is used for displaying images on the form.
The Image property of the control allows you to set an image both at
design time or at a runtime. Specifies whether the picture box accepts
data that a user drags on it. Gets or sets the path or the URL for the
image displayed in the control.
The following code snippet creates a PictureBox, sets its width and
height and adds control to the Form by calling Controls.Add()
method.
C# Code
1. PictureBox imageControl = newPictureBox();
2. imageControl.Width = 400;
3. imageControl.Height = 400;
4. Controls.Add(imageControl);
5. The output looks like Figure 1 where an image is displayed.
6.
Creating a Panel
We can create a Panel Control using the Forms designer at design-
time or using the Panel class in code at run-time.
Design-time
To create a Panel Control at design-time, you can drag and drop a
Panel Control from the Toolbox to a Form in Visual Studio. After you
dragging and dropping a Panel Control to the Form, the Panel looks
like Figure 1.
Once a Panel is on the form, you can move it around and resize it
using the mouse and set its properties and events.
Figure 1
The following code snippet creates a Panel Control object.
1. Panel dynamicPanel = newPanel( );
In the next step, you may set the properties of a Panel Control.
The following code snippet sets the location, size and Name
properties of a Panel.
1. dynamicPanel.Location = new System.Drawing.Point(26, 12);
2. dynamicPanel.Name = "Panel1";
3. dynamicPanel.Size = new System.Drawing.Size(228, 200);
4. dynamicPanel.TabIndex = 0;
ComboBox in C#:-
In Windows Forms, ComboBox provides two different features in a
single control, it means ComboBox works as both TextBox and
ListBox. In ComboBox, only one item is displayed at a time and the
rest of the items are present in the drop-down menu. The ComboBox
is a class in C# and defined
under System.Windows.Forms Namespace.
Property Description
Important Events
Event Description
DropDownList control:-
DateTimePicker:-
Step 2: Next, drag and drop the DateTimePicker control from the
toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the
DateTimePicker to modify DateTimePicker according to your
requirement.
1. // Set background and foreground
2. dynamicLinkLabel.BackColor = Color.Red;
3. dynamicLinkLabel.ForeColor = Color.Blue;
4. dynamicLinkLabel.Text = "I am a Dynamic LinkLabel";
5. dynamicLinkLabel.Name = "DynamicLinkLabel";
6. dynamicLinkLabel.Font = newFont("Georgia", 16);
CheckBox in C#:-
RadioButton in C#
In Windows Forms, RadioButton control is used to select a single
option among the group of the options. For example, select your
gender from the given list, so you will choose only one option among
three options like Male or Female or Transgender. In C#,
RadioButton is a class and it is defined under System.Windows.
Forms namespace. In RadioButton, you are allowed to display text,
image, or both and when you select one radio button in a group other
radio buttons automatically clear.
Step 1: Create a radio button using the RadioButton() constructor
is provided by the RadioButton class.
// Creating radio button
RadioButton r1 = new RadioButton();
Step 2: After creating RadioButton, set the properties of the
RadioButton provided by the RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;
1. TabPage newPage = new TabPage("New Page");
2. tabControl1.TabPages.Add(newPage);
After adding the page, the new TabControl would look like Figure 5.
Figure 5. Adding a Tab page programmatically.
The Remove method of TabPageCollection class (through
TabControl.TabPages) removes a page by name or index from the
page collection. The following code snippet removes "New Page"
from the collection:
1. TabPage newPage = new TabPage("New Page");
2. tabControl1.TabPages.Remove(newPage);
The RemoveAll method removes all the pages from the collection.
1. this.SettingsPage.Controls.Add(this.BrowseBtn);
2. this.SettingsPage.Controls.Add(this.textBox1);
3. this.SettingsPage.Controls.Add(this.label1);
ToolStrip Control In C#
ToolStrip control provides functionality of Windows toolbar controls
in Visual Studio 2010. ToolStrip class represents a ToolStrip control
in Windows Forms and serves as a base class of MenuStrip,
StatusStrip, and ContextMenuStrip classes.
We can create a ToolStrip control at design-time using Visual Studio
designer or using the ToolStrip class at run-time.
A ToolStrip control is nothing but a container without adding its child
controls. A ToolStrip control is capable of hosting Button, Label,
SplitButton, DropDownButton, Separator, ComboBox, TextBox and
ProgressBar controls.
MenuStrip In C#
We can create a MenuStrip control using a Forms designer at design-
time or using the MenuStrip class in code at run-time or dynamically.
To create a MenuStrip control at design-time, you simply drag and
drop a MenuStrip control from Toolbox to a Form in Visual Studio.
Creating a MenuStrip
We can create a MenuStrip control using a Forms designer at design-
time or using the MenuStrip class in code at run-time or dynamically.
To create a MenuStrip control at design-time, you simply drag and
drop a MenuStrip control from Toolbox to a Form in Visual Studio.
After you drag and drop a MenuStrip on a Form, the MenuStrip1 is
added to the Form and looks like Figure 1. Once a MenuStrip is on
the Form, you can add menu items and set its properties and events.
C# ProgressBar Control
Minimum : Sets the lower value for the range of valid values for
progress.
Maximum : Sets the upper value for the range of valid values for
progress.
By default, Minimum and Maximum are set to 0 and 100. As the task
proceeds, the ProgressBar fills in from the left to the right. To delay
the program briefly so that you can view changes in the progress bar
clearly.
The parent (MDI) form organizes and arranges all the child
forms or documents that are currently open. You might have
seen such options in many Windows applications under a
Windows menu, such as Cascade, Tile Vertical, and so on.
3. Drag a MenuStrip control to the ParentForm. In the top-left
corner, you should now see a drop-down showing the text
"Type Here". Enter the text "Open Forms" in the drop-down.
This will be your main, top-level menu.
4. Now under the Open Forms menu, add a submenu by
entering the text "Win App".
5. Under the Win App submenu, enter "User Info".
6. Now click the top menu, "Open Forms", and on the right
side of it, type "Help". Under the Help menu, enter "Exit".
7. Now, click the top menu, on the right side of Help, type
"Windows".
8. Under the Windows menu, add the following options as
separate submenus: Cascade, Tile Horizontal, Tile Vertical,
and Arrange Icons. These will help in arranging the child
forms.
9. Now it's time to attach code to the submenus you have
added under the main menu Open Forms. First, you'll add
code for the submenu Win App, that basically will open the
WinApp form. In the Design View, double-click the "Win
App" submenu, that will take you to the Code View. Under
the click event, add the following code:
WinApp objWA = new WinApp();
objWA.Show();
10. Now to associate functionality with the User Info submenu:
double-click this submenu, and under the click event add
the following code:
Application.Exit();
12. Now you have the form-opening code functionality in place,
and you are nearly set to run the application. But first, you
need to set the ParentForm as the start-up object. To do so,
open Program.cs, and modify the "Application.Run(new
UserInfo());" statement to the following:
Application.Run(new ParentForm());
13. Now build the solution, and run the application by pressing
F5; the MDI application will open and should look as in
Figure 1-1.
Figure 1-1. Running an MDI form application
14. Now if you click "Win App" and then "User Info" then both
the forms will open one by one. These forms can be opened
and dragged outside of the MDI form. This is not an
expected behavior from a MDI application, as shown in
Figure 1-2.
How It Works
Application.Exit();
objWA.MdiParent=this;
After adding this line, the code will appear as follows:
WinApp objWA = new WinApp();
objWA.MdiParent = this;
objWA.Show();
Now you will make the UserInfo form an MDI child form. To
do so, you need to set the MdiParent property to the name
of the MDI parent form but in the Code View. Add the
following code as you did in the previous step (this code
can be found under the User Info menu click event):
objUI.MdiParent=this;
Click "Open Form" -> "Win App"; the WinApp form should
open. Again, open the main menu and click "User Info".
Both the forms should now be open inside your main MDI
parent form application, and unlike before, you will not be
able to drag these out of your MDI parent form (as shown
in Figure 1-2). Figure 1-3 shows the expected behavior of an
MDI application with opened form(s).
Because both the forms are open inside one MDI parent, it
becomes easier to work with them, and they are not
draggable outside of the MDI parent. Switch among these
forms by clicking their title bars. Once you are done with
the forms, close the application by selecting "Help" ->
"Exit".
How It Works
As you noticed in an earlier exercise, the only issue discussed
was that child forms opened and were able to be dragged
outside. In other words, they didn't really belong to a parent
form. An MDI application is about claiming a form with a menu
bar as an MDI parent so all the child forms can open inside it.
objWA.MdiParent = this;
You have an object created and its context set to a MDI parent
form, so now it's a perfect time to call the Show() method, that
will launch the form so you can work with it.
objWA.Show();
Multiple forms will open within one MDI window, so once you
have a few open, your MDI application will be cluttered. It's
hard to move forms around to shift your focus from one to
another. Hence, it is a prime concern to have a mechanism that
allows you to arrange the forms in an organized manner.
LayoutMdi(MdiLayout.TileHorizontal);
4. Double-click the Tile Vertical, and in the Code View under
the click event, add the following code:
LayoutMdi(MdiLayout.TileVertical);
5. Double-click Tile Vertical, and in the Code View under the
click event, add the following code:
LayoutMdi(MdiLayout.ArrangeIcons);
6. Now build the solution, and run the application by pressing
F5; the MDI application will open. After it opens, go to the
Open Forms menu and click Win App and User Info one by
one. It is important to have at least two forms open in the
MDI parent form. Now go to the Windows menu and try the
available options by clicking Cascade, then Arrange Vertical,
then Arrange Horizontal, and finally Arrange Icons. When
you will try these options, Tile Vertical will show the child
forms arranged as in Figure 1-5.
Figure 1-5. Arranging (Tile Vertical) child forms in the MDI
form application
ADO.NET
ADO.NET(ActiveX Data Objects) is a module of .Net Framework
which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML.
ADO.NET consists of classes that can be used to connect,
retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and
integrated with XML classes located into System.Xml.dll.
ADO.NET has two main components that are used for accessing
and manipulating data are the .NET Framework data provider
and the DataSet.
XML stores data in plain text format. This provides a software- and hardware-
independent way of storing, transporting, and sharing data.
XML also makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.
With XML, data can be available to all kinds of "reading machines" like people,
computers, voice machines, news feeds, etc.
.NET Framework Data Providers
These are the components that are designed for data
manipulation and fast access to data. It provides various objects
such as Connection, Command, DataReader and
DataAdapter that are used to perform database operations.
ADO.NET DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter
provides the communication between the Dataset(A data set (or
dataset) is a collection of data. In the case of tabular data, a
data set corresponds to one or more database tables, where
every column of a table represents a particular variable, and
each row corresponds to a given record of the data set in
question.) and the Datasource.
We can use the DataAdapter in combination with the DataSet Object.
DataAdapter provides this combination by mapping Fill method, which
changes the data in the DataSet to match the data in the data source, and
Update, which changes the data in the data source to match the data in
the DataSet. That is, these two objects combine to enable both data
access and data manipulation capabilities.
Connect to a database
The steps in this article show how to connect to a data source
in the Visual Studio IDE. The data source can be a local
database, online data service, or a database opened from
an .mdf file. You can work directly with your data in Visual
Studio. You can execute queries, edit data, create and edit
tables and other schema properties, edit stored procedures and
functions, triggers, and so on. These functions are independent
of the programming language or .NET version you are using.
Server Explorer
MDF files
1.
2.
3.
Use the Browse button to find and select your master
database file (.mdf file), or enter the path in the Database
filename box.
4.
5.
6.
7.
8.
9.
Note
This means some of the data tools in Visual Studio will not be
able to connect to OLEDB or ODBC databases using 32-bit data
providers. This includes the Microsoft Access 32-bit OLEDB data
provider as well as other third-party 32-bit providers.
From there, you can browse the database, write and execute
queries, edit data, stored procedures and functions, and
perform other actions directly in Visual Studio.
Next steps
The first way to ensure this is use exception handlers. We open a connection in the
try block, use it inside the try block and close it in the finally block this will ensure
that even if an unhandled error occurs, the connection will be closed in the finally
block. If we don’t use this approach and simply close the connection inside try block
itself after performing the operation and an unhandled exception occurs, the
connection will remain open until the garbage collector disposes of
the SqlConnection object. And the connection being a precious and limited resource
we should never rely on the garbage collector to close it. It should always be closed
deterministically.
SqlConnection conn = new SqlConnection("CONNECTION_STRING_HERE");
try
conn.Open();
finally
conn.Close();
Command Object
The command object is one of the basic components of ADO .NET.
1. The Command Object uses the connection object to execute SQL queries.
2. The queries can be in the Form of Inline text, Stored Procedures or direct Table
access.
3. An important feature of Command object is that it can be used to execute
queries and Stored Procedures with Parameters.
4. If a select query is issued, the result set it returns is usually stored in either a
DataSet or a DataReader object.
Associated Properties of SqlCommand class
The properties associated with SqlCommand class are shown in the Table below.
Property Type of Description
Access
The SqlConnection object that is used by the
Connection Read/Write command object to execute SQL queries or
Stored Procedure.
Represents the T-SQL Statement or the name of
CommandText Read/Write the Stored Procedure.
This property indicates how the CommandText
property should be interpreted. The possible
values are:
CommandType Read/Write
1. Text (T-SQL Statement)
2. StoredProcedure (Stored Procedure Name)
3. TableDirect
This property indicates the time to wait when
executing a particular command.
Default Time for Execution of Command is 30
CommandTimeout Read/Write
Seconds.
The Command is aborted after it times out and
an exception is thrown.
Now, Let us have a look at various Execute Methods that can be called from a
Command Object.
Property Description
This method executes the command specifies and returns the
ExecuteNonQuery
number of rows affected.
The ExecuteReader method executes the command specified
ExecuteReader
and returns an instance of SqlDataReader class.
This method executes the command specified and returns the
ExecuteScalar first column of first row of the result set. The remaining rows
and column are ignored.
This method executes the command specified and returns an
ExecuteXMLReader instance of XmlReader class. This method can be used to
return the result set in the form of an XML document
These are quite often methods in the Command objects. Let us now see each of
these with an example
ExecuteNonQuery
1. The ExecuteNonQuery method is used to execute the command and return the
number of rows affected.
2. The ExecuteNonQuery method cannot be used to return the result set.
Snippets working with ExecuteNonQuery
1. public void CallExecuteNonQuery()
2. {
3. SqlConnection conn = new SqlConnection();
4. conn.ConnectionString = ConfigurationManager.ConnectionStrings["
connString"].ConnectionString;
5. try
6. {
7. SqlCommand cmd = new SqlCommand();
8. cmd.Connection = conn;
9. cmd.CommandText = "DELETE FROM EMP WHERE DEPTNO = 40";
10. cmd.CommandType = CommandType.Text;
11. conn.Open();
12. Int32 RowsAffected = cmd.ExecuteNonQuery();
13. MessageBox.Show(RowsAffected + " rows affected", "Message");
14. cmd.Dispose();
15. conn.Dispose();
16. }
17. catch (Exception ex)
18. {
19. MessageBox.Show(ex.Message);
20. }
21. }
Fill in the form and click the "Save" button. The record will be saved to the database
and a message box will be displayed with a confirmation message.
Now we retrieve records from the database. Take another button and set its text
property as "Show". Add the following code for the "Show" button.
1. private void btnshow_Click(object sender, EventArgs e) {
2. conn = new SqlConnection(connstring);
3. conn.Open();
4.
5. comm = new SqlCommand();
6. comm.Connection = conn;
7.
8. //Creating instance of SqlParameter
9. SqlParameter PmtrRollNo = new SqlParameter();
10. PmtrRollNo.ParameterName = "@rn"; // Defining Name
11. PmtrRollNo.SqlDbType = SqlDbType.Int; // Defining DataType
12. PmtrRollNo.Direction = ParameterDirection.Input; // Setting the
direction
13.
14. //Creating instance of SqlParameter
15. SqlParameter PmtrName = new SqlParameter();
16. PmtrName.ParameterName = "@nm"; // Defining Name
17. PmtrName.SqlDbType = SqlDbType.VarChar; // Defining DataType
18. PmtrName.Size = 30;
19. PmtrName.Direction = ParameterDirection.Output; // Setting the d
irection
20.
21. //Creating instance of SqlParameter
22. SqlParameter PmtrCity = new SqlParameter("@ct", SqlDbType.VarCha
r, 20);
23. PmtrCity.Direction = ParameterDirection.Output; // Setting the d
irection
24.
25. // Adding Parameter instances to sqlcommand
26.
27. comm.Parameters.Add(PmtrRollNo);
28. comm.Parameters.Add(PmtrName);
29. comm.Parameters.Add(PmtrCity);
30.
31. // Setting values of Parameter
32.
33. PmtrRollNo.Value = Convert.ToInt32(txtrollno.Text);
34. PmtrName.Value = txtname.Text;
35. PmtrCity.Value = txtcity.Text;
36.
37. comm.CommandText = "select @nm=name,@ct=city from student_detail
where rollno=@rn";
38.
39. try {
40. comm.ExecuteNonQuery();
41. txtname.Text = PmtrName.Value.ToString();
42. txtcity.Text = PmtrCity.Value.ToString();
43. } catch (Exception) {
44. MessageBox.Show("Not Found");
45. } finally {
46. conn.Close();
47. }
48. }
Run the application.
Output
Enter a roll number and click the "Show" button. It will show all the related
information of the student having the given roll number.
C# - Data Types
C# is a strongly-typed language. It means we must declare the type of a variable that
indicates the kind of values it is going to store, such as integer, float, decimal, text, etc.
C# mainly categorized data types in two types: Value types and Reference types. Value
types include simple types (such as int, float, bool, and char), enum types, struct types,
and Nullable value types. Reference types include class types, interface types, delegate
types, and array types. Learn about value types and reference types in detail in the next
chapter.
Validation Controls
Validation controls are an essential part of ASP.NET web development because they
help ensure the integrity of user input. When users enter information into web forms,
there is always the potential for intentional or unintentional errors. Validation controls
provide a way to check the accuracy and validity of user input before the web
application processes it.
Some of the reasons why validation controls are important in ASP.NET are:
Preventing invalid data from being submitted: Validation controls can check for
required fields, format and type of data, and other criteria that must be met
before the data can be submitted to the server. This helps ensure that the data
is accurate and complete and that the application can process it correctly.
Improving user experience: When users enter invalid data, they may receive
error messages or other feedback that helps them correct their mistakes. This
can help prevent frustration and improve the overall user experience.
Enhancing security: Validation controls can help prevent malicious code or
other attacks that could harm the web application or its users. For example,
validation controls can check for potentially dangerous input such as SQL
injection or cross-site scripting (XSS) attacks.
Meeting business requirements: Many businesses have specific rules and
requirements for data entry, such as a minimum or a maximum number of
characters or certain formatting conventions. Validation controls can help
ensure that these requirements are met.
1. Referred to using short names rather than a long string of text; therefore, less
network traffic is required to run the code within the sproc.
2. Pre-optimized and precompiled, so they save an incremental amount of time
with each sproc call/execution.
3. Encapsulate a process for added security or to simply hide the complexity of the
database.
4. Can be called from other sprocs, making them reusable and reducing code size.
5. Stored procedures are executed on the database server and can be better for
performance.
6. Stored procedures are also secure and do not expose database details in
application.
Parameterization
Input parameters
Output parameters
From outside the sproc, parameters can be passed in either by position or reference.
The name
The datatype
The default value
The direction
SQL
Copy
First open Microsoft SQL Server -> Enterprise Manager, then navigate to the
database in which you want to create the stored procedure and select New Stored
Procedure.
See the below Stored Procedure Properties for what to enter, then click OK.
Now create an application named Store Procedure in .net to use the above sprocs.
Web User Controls in ASP.Net
Web user controls are derived from System.Web.UI.UserControl namespace. These
controls once created, can be added to the aspx page either at design time or
programmatically during run time. But they lack the design time support of setting the
properties created along with the control. They cannot run on their own and they
need to stand on another platform like an aspx page. Even if we try to load it on a
web browser, IIS will not serve the files of the type .ascx.
1. Create a new ASP .Net web application using Visual Studio.Net.
1. Add a Web User Control to the project. Name it as WebUserControl1.ascx.
2.
Add a Panel Control on the user control form
3.
1. Add a hyperlink,a TextBox and a button Add a property to the User Control as
follows.
ASP.NET - Custom Controls
ASP.NET allows the users to create controls. These user defined controls are
categorized into:
User controls
Custom controls
User Controls
User controls behaves like miniature ASP.NET pages or web forms, which could be
used by many other pages. These are derived from the System.Web.UI.UserControl
class. These controls have the following characteristics:
Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a
Dynamic Link Library (DLL) and used as any other ASP.NET server control. They
could be created in either of the following way:
Tracing - tracing the program execution at page level or application level.
Error handling - handling standard errors or custom errors at page level or
application level.
Debugging - stepping through the program, setting break points to analyze
the code
Where there are codes, the chances for exceptions / error always exist so it is very
important for developers when developing web applications to understand the errors
and implement the error handling techniques to avoid breaking pages or providinig
unhandled errors to end uses.
Exceptions are nothing but unseen error occurs when executing code logic.
Demo Web Application
Sample Code
1. namespace ErrorHandlingDemo
2. {
3. public partial class _Default : Page
4. {
5. protected void Page_Load(object sender, EventArgs e)
6. {
7. if (!IsPostBack)
8. {
9. string connectionString = ConfigurationManager.Conne
ctionStrings["MyConn"].ConnectionString;
10. string selectSQL = "SELECT * FROM tblEmployees";
11. SqlConnection con = new SqlConnection(connectionStri
ng);
12. SqlCommand cmd = new SqlCommand(selectSQL, con);
13. SqlDataAdapter adapter = new SqlDataAdapter(cmd);
14. DataSet ds = new DataSet();
15. adapter.Fill(ds, "Employees");
16. GridView1.DataSource = ds;
17. GridView1.DataBind();
18. }
19. }
20. }
21. }
Using this web page I am trying to display employee's details in a grid view control
on page load. The following is the output page with employee details.
Example to show data on the webpage from the database using some ADO.NET
code:
Now from this basic what if the table containing employees is deleted or renamed or
the developer has used the wrong table name in the code behind.
I have now changed the table name in the code and complied and run the page.
1. string selectSQL = "SELECT * FROM tblEmployees1";
After running the application a broken Yellow screen is shown with the message
Invalid Object name.
But exposing this error message in Yellow page format is a bad practice because:
It does not make any sense to the end user although it can be helpful for
developers for debugging and investigating the issue.
This exposure can help hackers to get information about your application that is
not good according to security.
Handling Exceptions
Whenever an exception happens when executing the logic in a try block, the control
is immediately moved to the catch block that reads the exception message and after
catching the exception in the catch block a user-friendly error can be shown to the
end users.
Sample Code
1. namespace ErrorHandlingDemo
2. {
3. public partial class _Default : Page
4. {
5. protected void Page_Load(object sender, EventArgs e)
6. {
7. if (!IsPostBack)
8. {
9. try
10. {
11. string connectionString = ConfigurationManager.C
onnectionStrings["MyConn"].ConnectionString;
12. string selectSQL = "SELECT * FROM tblEmployees1"
;
13. SqlConnection con = new SqlConnection(connection
String);
14. SqlCommand cmd = new SqlCommand(selectSQL, con);
15. SqlDataAdapter adapter = new SqlDataAdapter(cmd)
;
16. DataSet ds = new DataSet();
17. adapter.Fill(ds, "Employees");
18. GridView1.DataSource = ds;
19. GridView1.DataBind();
20. }
21. catch (Exception ex)
22. {
23. // Log the exception
24. Label1.Text = "Something Bad happened, Please co
ntact Administrator!!!!";
25. }
26. finally
27. {
28. }
29. }
30. }
31. }
32. }
Cookies and Their Types
What is a Cookie?
Cookies are nothing but a small file containing text which is being made when you
enter a website. According to the law, if a website plans on collecting cookies, it
must get consent before doing so. When a new web page is opened, they're
typically written.
Cookies are tiny text files with a name, value, and attribute that are often encrypted.
A web server's name is used to identify cookies. Value is a random alphanumeric
character that holds information such as a unique identifier for the user and other
data. The data can be obtained and utilized to customize the web page once the
code has read the cookie on the server or client computer.
Types of Cookies
Cookies are divided based on their attributes, such as source, duration, and
purpose.
Cookies Based on Source
First-party cookies − The user's browser sets first-party cookies when they visit a
website. The information gathered by first-party cookies is used to calculate page
views, sessions, and the number of users. Ad agencies and advertisers primarily
utilize it to locate potential ad targets.
Third-party cookies − These are set by domains that the user does not visit directly.
This occurs when publishers include third-party elements on their website (such as a
chatbot, social plugins, or advertisements).
Cookies Based on Duration
Session cookie − A session cookie is a file that a website server delivers to a
browser with an identification (a string of letters and numbers) for temporary use
during a set period. By default, session cookies are enabled. Their goal is to make
individual webpages load faster and improve website navigation.
Persistent cookies − Persistent cookies are those that remain in the browser for an
extended length of time. They will only be erased when the cookies expire or the
users clear them from the browser after being installed.