Thursday, June 23, 2011

SQL Server Views Tutorial - Create, Alter, Insert, Update, Delete etc..

SQL Server Views
Views allow you to create a virtual representation of table data defined by a SELECT statement.


Views can be used to simplify data access for query writers, obscuring the underlying complexity of the SELECT statement.


Views are also useful for managing security and protecting sensitive data. If you wish to restrict direct table access by the end user, you can grant permissions exclusively to views, rather than to the underlying tables. You can also use views to expose only those columns that you wish the end user to see, including just the necessary columns in the view definition.


Views work as an interface between database tables and user.


You cannot use certain SELECT elements in a view definition, including INTO, OPTION, COMPUTE, COMPUTE BY or ORDER BY. We cannot reference a temporary table.


Views can be used for different purposes:



  • To restrict the use of particular columns and/or rows of tables.

  • To hide the details of complicated queries. If database applications need queries that involve complicated join operations, the creation of corresponding views can simplify the use of such queries

CREATE VIEW Statement:
A view is created using the CREATE VIEW statement.

/*
create a view for viewing data within the table
Teachers for the user student
*/
CREATE VIEW Student.vu_SelectTeachers
AS
SELECT Name,JobTitle FROM Teacher.Teachers
GO

/*
select data by using the view
*/
SELECT * FROM Student.vu_SelectTeachers
Eg:
/*
create a view for the user teacher
*/
CREATE VIEW Teacher.vu_SelectTeachers
AS
SELECT Id, Name, JobTitle from Teacher.Teachers
GO

/*
select data
*/
SELECT * FROM Teacher.vu_SelectTeachers


Altering and Removing Views
ALTER VIEW statement is used to modify the definition of the view query. The DROP VIEW statement removes the definition of the specified view from the system tables.
Eg:


/*
Altering views
*/
ALTER VIEW Student.vu_SelectTeachers
AS
SELECT Name,JobTitle,Phone from Teacher.Teachers
GO
Eg:
/*
remove a view
*/
DROP VIEW Student.vu_SelectTeachers


INSERT, UPDATE and DELETE statement and VIEW
A view can be used with the INSERT, UPDATE and DELETE statements. When a view is used to insert, update or delete, the rows are actually insert, update or delete into the underlying base table.
The inserting, updating and deleting of rows into the underlying tables is not possible if the corresponding view contains any of the following features:



  • The FROM clause in the view definition involves two or more tables and the column list includes columns from more than one table

  • A column of the view is derived from an aggregate function

  • The SELECT statement in the view contains the GROUP BY clause or the DISTINCT option

  • A column of the view is derived from a constant or an expression (except in the case of deletion)


/*
INSERT, UPDATE and DELETE with Views
*/
INSERT INTO Teacher.vu_SelectTeachers(Id, Name,JobTitle) VALUES(4,'jobin','Faculty')

UPDATE Teacher.vu_SelectTeachers SET JobTitle='Trainer' WHERE Id=4

DELETE Teacher.vu_SelectTeachers WHERE Id=4



WITH Encryption:
The WITH ENCRYPTION option encrypts the SELECT statement, thus enhancing the security of the database system. Software vendors who use SQL Server in the back end often encrypt their views or stored procedures in order to prevent tampering or reverse-engineering from clients or competitors. If you use encryption, be sure to save the original, unencrypted definition.

Eg:
/*
creating a view with Encryption
*/
CREATE VIEW Teacher.vu_SelectTeachers
WITH ENCRYPTION
AS
SELECT Id, Name, JobTitle from Teacher.Teachers
GO


WITH SCHEMABINDING
The SCHEMABINDING clause binds the view to the schema of the underlying table. Creating a view with the SCHEMABINDING option locks the tables being referred by the view and prevents any changes that may change the table schema.

Notice two important points while creating a view with SCHEMABINDING OPTION:


  • The objects should be referred to by their owner names [two part name].

  • SELECT * is not permitted.

/*
create schema with SCHEMABINDING
*/
DROP VIEW Teacher.vu_SelectTeachers

CREATE VIEW Teacher.vu_SelectTeachers
WITH SCHEMABINDING
AS
SELECT Id, Name, JobTitle from Teacher.Teachers
GO

/*
try to change schema of tale Teacher
*/
alter schema student TRANSFER Teacher.Teachers
alter schema teacher TRANSFER student.Teachers


WITH CHECK OPTION
The option WITH CHECK OPTION is used to restrict the insertion of only such rows that satisfy the conditions of the query. If this option is used, Database Engine tests every inserted row to ensure that the conditions in the WHERE clause are evaluated to true.

/*
create schema with CHECK OPTION
*/
DROP VIEW Teacher.vu_SelectTeachers

CREATE VIEW Teacher.vu_SelectTeachers
AS
SELECT Id, Name, JobTitle FROM Teacher.Teachers WHERE JobTitle='faculty'
WITH CHECK OPTION
GO

-- insertion fails on the following query because not faculty
INSERT INTO Teacher.vu_SelectTeachers(Id, Name, JobTitle) VALUES (5,'fff','Manager')
--insertion succeed on the following query because his JobTitle is faculty
INSERT INTO Teacher.vu_SelectTeachers(Id, Name, JobTitle) VALUES (5,'fff','faculty')

Monday, June 20, 2011

Styling Asp.Net Menu control with CSS - Example

Hello friends, here is an example to styling asp.net menu control by using a simple css and a background image. Hope it will help you

To create this stylish menu follow the following steps.

1. Create Menu.css file and type the following css code.

.Menu
{

}

.Menu ul
{
background:#7795BD;
}

.Menu ul li
{
background:#7795BD url(menu_bg.gif) repeat-x;
text-align:center;
/* set width if needed.*/
width:200px;
}

.Menu ul li a
{
color: black;
padding: 4px 2px 4px;
padding-left:8px !important;
border:1px solid #648ABD;
border-bottom: 0;
}

.Menu ul li a:hover
{
background-image: none;
}

.Menu ul li a:hover
{
color: White;
}

.Menu ul li a
{
color: Black;
}



2. add the following image into the web application.



3. place menu control and set the CssClass property as given below

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" CssClass="Menu">

<Items>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item">
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item New Item" Value="New Item"></asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item New Item" Value="New Item">
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item">
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
</asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item">
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item">
<asp:MenuItem NavigateUrl="#" Text="New Item" Value="New Item"></asp:MenuItem>
</asp:MenuItem>
</Items>

</asp:Menu>

Tuesday, June 14, 2011

Hosting a WCF Service in a Managed Application

WCF enables you to host your service through any managed application. This means you can use a Console application, a Windows service, a Windows Forms application, or even an application built with Windows Presentation Foundation.

Hosting a WCF Service by Using a Console Application

The Console application must specifically create and open an instance of the ServiceHost object. The ServiceHost then remains open and available until it is no longer needed.

Eg:
• Create a New Project from the File menu and select WcfServiceLibrary.
Create and Implement service.
Build the project.
• Create ConsoleApplication named ConsoleServiceHost. From the project menu select Add Reference option and select the WcfServiceLibrary1.dll. Click ok.
Write the following code in the Main function.


ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
host.Open();
Console.WriteLine("Service Started...");
Console.WriteLine("\nPress any key to stop...");
Console.ReadLine();
host.Close();

Add an Application Configuration file to the project. And write the following configuration settings in the app.config.
<configuration>
<system.serviceModel>
<services>
<service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServiceLibrary1.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

• Create a new console application. Copy the address from the app.config of ConsoleServiceHost application. Add service reference. Write the following code in the main function.
Console.WriteLine("Press ENTER when the service has started");
Console.Read();

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

Console.WriteLine(client.GetData(33));
client.Close();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
Console.ReadLine();

Monday, June 13, 2011

Hosting a WCF Service on a Web Server

Hosting a Service on an IIS Web Server
Hosting a service on an IIS Web server is very similar to hosting a traditional Web service. Services exposed this way will be highly available and scalable, but they will require the installation and configuration of an IIS Web server.

To register WCF in IIS Run the following command.

C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation>ServiceModelReg.exe -i.

You can host a WCF Service in two different ways.

1. Create WCF service in HTTP mode.
When creating a WCF Service in HTTP Mode it automatically hosted in IIS webserver. To create a service in HTTP Mode, your system must have IIS get installed.




2. Manually host the service in IIS like websites.
You can also do hosting a service by creating a virtual directory in IIS and paste you service files into your virtual directory.

Publishing Metadata Through Endpoints

WCF enables you to publish service metadata, using the HTTP-GET protocol. Clients can access the metadata using an HTTP-GET request with a ?wsdl query string appended. You do this by specifying a service behavior either programmatically or through a configuration file. The behavior is then referenced when specifying the service.

You also need to create a metadata exchange endpoint. This special endpoint can append mex to the HTTP address the service uses. The endpoint should use the IMetadataExchange interface as the contract and mexHttpBinding as the binding.

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="http://localhost:50187/WCFService1/" binding="wsHttpBinding" contract="IService"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Tuesday, June 7, 2011

Advanced TextBox for Asp.Net ( TextBox with built in Validation )

Advanced TextBox Control for Asp.Net (Asp.Net Custom Server Control)
Hello friends, we all have been using Asp.Net validation controls with TextBox controls. By default, we have to configure several properties to do a validation using any validation controls. Here I'm introducing a new Custom Server Control which is derived from TextBox control. This control have some additional properties under the Advanced tab on the properties window.
The given below example shows how to create (or setup) an AdvancedTextBox control with builtin logic for validations. AdvancedTextBox control uses the TextBox and validation controls built with Asp.Net .
To develop this control, create a Asp.Net Server Control Project and write the following code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvancedTextBox
{
public enum TextType
{
String,
Int,
Double,
Date,
Email,
Url
}

[DefaultProperty("Text")]
[ToolboxData("<{0}:AdvancedTextBox runat=server></{0}:AdvancedTextBox>")]
public class AdvancedTextBox : TextBox
{
private TextType _textType = TextType.String;
private bool _isRequired = false;
List<Control> _controls = new List<Control>();

[Category("Advanced")]
[Description("Text type for the TextBox")]
public TextType TextType
{
set
{
_textType = value;
}
get
{
return _textType;
}
}

[Category("Advanced")]
[Description("Mandatory field or not")]
public bool IsRequired
{
set { _isRequired = value; }
get { return _isRequired; }
}

[Category("Advanced")]
[Description("Minimum range value")]
public string MinimumValue
{
set;
get;
}

[Category("Advanced")]
[Description("Maximum range value")]
public string MaximumValue
{
set;
get;
}
[Category("Advanced")]
[Description("Error Message to be displayed when not entering value.")]
public string RequiredErrorMessage
{
set;
get;
}
[Category("Advanced")]
[Description("Error message to be displayed when type mismatch or range violation.")]
public string TypeOrRangeErrorMessage
{
set;
get;
}

[Category("Advanced")]
[Description("Sets the Text property of associated validation controls")]
public string ValidatorText
{
set;
get;
}

protected override void OnInit(EventArgs e)
{
GenerateControls();
base.OnInit(e);
}

protected void GenerateControls()
{
if (_isRequired)
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ForeColor = System.Drawing.Color.Red;
req.ValidationGroup = this.ValidationGroup;
req.ErrorMessage = this.RequiredErrorMessage;
req.Text = this.ValidatorText;
_controls.Add(req);
this.Controls.Add(req);
}
if (this.MinimumValue != null this.MaximumValue != null)
{
RangeValidator rag = new RangeValidator();
rag.ControlToValidate = this.ID;
rag.ForeColor = System.Drawing.Color.Red;
rag.ValidationGroup = this.ValidationGroup;
rag.ErrorMessage = this.TypeOrRangeErrorMessage;
rag.Text = this.ValidatorText;
switch (_textType)
{
case TextType.Int:
rag.Type = ValidationDataType.Integer;
break;
case TextType.Double:
rag.Type = ValidationDataType.Double;
break;
case TextType.Date:
rag.Type = ValidationDataType.Date;
break;
default: rag.Type = ValidationDataType.String;
break;
}

rag.MinimumValue = this.MinimumValue;
rag.MaximumValue = this.MaximumValue;
_controls.Add(rag);
this.Controls.Add(rag);
}
else
{
switch (_textType)
{
case TextType.String:

break;
case TextType.Int:
CompareValidator cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Integer;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Double:
cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Double;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Date:
cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Date;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Email:
RegularExpressionValidator reg = new RegularExpressionValidator();
reg.ControlToValidate = this.ID;
reg.ForeColor = System.Drawing.Color.Red;
reg.ValidationGroup = this.ValidationGroup;
reg.ErrorMessage = this.TypeOrRangeErrorMessage;
reg.Text = this.ValidatorText;
reg.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
_controls.Add(reg);
this.Controls.Add(reg);
break;
case TextType.Url:
reg = new RegularExpressionValidator();
reg.ControlToValidate = this.ID;
reg.ForeColor = System.Drawing.Color.Red;
reg.ValidationGroup = this.ValidationGroup;
reg.ErrorMessage = this.TypeOrRangeErrorMessage;
reg.Text = this.ValidatorText;
reg.ValidationExpression = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?";
_controls.Add(reg);
this.Controls.Add(reg);
break;
default:
break;
};
}

}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
for (int i = 0; i < _controls.Count; i++)
{
_controls[i].RenderControl(writer);
}
}
}
}



When using this AdvancedTextBox control you can see the "Advanced" tab on the properties window.







  • IsRequired : when you set this property to true, then AdvancedTextBox come up with RequiredFieldValidator control.

  • MaximumValue and MinimumValue: when you set this property AdvancedTextBox come up with a RangeValidatior Control.

  • RequiredErrorMessage: Error message to be set on the Required field validation control.

  • TextType: When you set this property, Advanced TextBox come up with a CompareValidator control to ensure the data type.

  • TypeOrRangeErrorMessage: Error message to be set on either compare validator control or range validator control.

  • ValidatorText: This will be for setting the Text property of the validation controls that are come up with AdvancedTextBox control.

This control will help developers to develop GUI fastly and efficiently without specifying or declaring any validation controls to validate a TextBox.
Hope all of you are doing great programming with AdvancedTextBox Control. Feel free to ask questions and doubts. :-)