CODES : Beginners delight

[E] : Some more codes

Imports System.Data
Imports System.Data.SqlClient

Partial Class Adminfinance_Loaninterest
Inherits System.Web.UI.Page

Protected Sub calinterest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calinterest.Click
Dim rdr As SqlDataReader
Dim param As SqlParameter
Dim sb As New StringBuilder
sb = sb.Append("SELECT rate_of_interest,amount_received ")
sb = sb.Append("FROM new_loans_db ")
sb = sb.Append("WHERE loan_id=@loan_id")

Dim objconn As New SqlConnection
objconn.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString
Dim objcmd As New SqlCommand
objcmd.Connection = objconn
objcmd.CommandText = sb.ToString()
param = objcmd.Parameters.Add("@loan_id", SqlDbType.VarChar)
param.Value = Me.ddnloanid.SelectedItem.Text
rdr = objcmd.ExecuteReader()
If rdr.Read Then
Me.txtroi.Text = rdr(0).ToString
Me.amountreceived.Text = rdr(1).ToString

End If
Catch ex As SqlException
message.Text = "xception " + ex.Message.ToString()


End Try

'filling up amount of loan left

Dim rdr1 As Object
Dim param1 As SqlParameter
Dim sb1 As New StringBuilder
sb1 = sb1.Append("SELECT SUM(amount) as rdr1 ")
sb1 = sb1.Append("FROM loan_repayment_db ")
sb1 = sb1.Append("WHERE loan_id=@loan_id")
Dim objconn1 As New SqlConnection
objconn1.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString
Dim objcmd1 As New SqlCommand
objcmd1.Connection = objconn1
objcmd1.CommandText = sb1.ToString()
param1 = objcmd1.Parameters.Add("@loan_id", SqlDbType.VarChar)
param1.Value = Me.ddnloanid.SelectedItem.Text
rdr1 = objcmd1.ExecuteScalar()
Me.txtamountpaid.Text = rdr1.ToString()

Catch ex1 As SqlException
message.Text = "xception " + ex1.Message.ToString()


End Try

CODES : DB entry codes

[D] : Some other codes

Admin section codes :
'vacancies db
Partial Class Adminrse_Setvacancies
Inherits System.Web.UI.Page
Protected Sub calldoa_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calldoa.SelectionChanged
Me.txtldoa.Text = Me.calldoa.SelectedDate

End Sub

Protected Sub caled_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caledrd.SelectionChanged
Me.txted.Text = Me.caledrd.SelectedDate
End Sub

Protected Sub calid_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caliddoj.SelectionChanged
Me.txtid.Text = Me.caliddoj.SelectedDate
End Sub

Protected Sub calrd_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caledrd.SelectionChanged
Me.txtrd.Text = Me.caledrd.SelectedDate
End Sub

Protected Sub caldoj_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caliddoj.SelectionChanged
Me.txtdoj.Text = Me.caliddoj.SelectedDate
End Sub

Protected Sub setvacancies_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles setvacancies.Click
Dim sb As New StringBuilder()
sb = sb.Append("insert into vacancies_db")
sb = sb.Append("(job_code,job_specification,no_of_vacancies,")
sb = sb.Append("eligibility,salary_perks,ldoa,")
sb = sb.Append("ed,id,rd,doj)")
sb = sb.Append("values")
sb = sb.Append("('" + Me.jobcode.Text.ToString + "','" + Me.txtjobs.Text.ToString + "','" + Me.txtnoofv.Text.ToString + "',")
sb = sb.Append("'" + Me.txtelig.Text.ToString + "','" + Me.txtsp.Text.ToString + "','" + Me.txtldoa.Text.ToString + "' ,")
sb = sb.Append("'" + Me.txted.Text.ToString + "','" + Me.txtid.Text + "','" + Me.txtrd.Text + "','" + Me.txtdoj.Text.ToString + "')")
Dim setvacancies As New hcms
If (setvacancies.makeentry(sb.ToString)) Then
Me.message.Text = "Vacancies Set Succesfully"
Me.message.Text = "Vacancies Set Failed"
End If

End Sub
End Class

'salary db
Partial Class Adminrse_Setsalary
Inherits System.Web.UI.Page
Protected Sub setsalary_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles setsalary.Click
Dim sb As New StringBuilder()
sb = sb.Append("insert into salary_db")
sb = sb.Append("(designation,salary)")
sb = sb.Append("values")
sb = sb.Append("('" + Me.txtdesig.Text.ToString + " ','" + Me.txtsal.Text.ToString + "')")
Dim setsalary As New hcms
If (setsalary.makeentry(sb.ToString)) Then
Me.message.Text = "Salary Set Succesfully"
Me.message.Text = "Salary Set Failed"
End If
End Sub
End Class

Partial Class Adminrse_Setovertimes
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub caldatalltd_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caldatalltd.SelectionChanged
Me.txtdatalltd.Text = Me.caldatalltd.SelectedDate
End Sub
End Class

' bonusdb
Partial Class Adminrse_Setbonus
Inherits System.Web.UI.Page
Protected Sub setbonus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles setbonus.Click
Dim sb As New StringBuilder()
sb = sb.Append("insert into bonus_db")
sb = sb.Append("(month_year,designation,bonus_amount,")
sb = sb.Append("overtime_per_hour)")
sb = sb.Append("values")
sb = sb.Append("('" + Me.ddnmon.SelectedItem.Text.ToString + " " + Me.txtyear.Text.ToString + "',")
sb = sb.Append("'" + Me.txtdesig.Text.ToString + "','" + Me.txtbon.Text.ToString + "','" + Me.txtoph.Text.ToString + "')")
Dim setbonus As New hcms
If (setbonus.makeentry(sb.ToString)) Then
Me.message.Text = "Bonus Set Succesfully"
Me.message.Text = "Bonus Set Failed"
End If

End Sub
End Class

Here the authorised accesibility has been granted to some user so that specific data can be set up...

CODES : hcms class file

[C] : Very Simple , I hope there won't be any u can relate the other class files with this class.

Imports System.Data
Imports System.Data.SqlClient

Public Class hcms
' try to incorporate the concept of session here as well
Public Function authenticateuser(ByVal login As String, ByVal pwd As String) _
As Boolean
Dim objconn As New SqlConnection
objconn.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString
Dim cmd As New SqlCommand("select * from member_professional where loginid=" + login, objconn)
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.Read AndAlso dr("password") = pwd Then
authenticateuser = True
authenticateuser = False
End If
Catch ex As SqlException
authenticateuser = False

End Try

End Function

Public Function authenticateadmin(ByVal login As String, ByVal pwd As String) _
As Boolean

Dim objconn As New SqlConnection
objconn.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString

Dim cmd As New SqlCommand("select * from admin_db where loginid=" + login, objconn)
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.Read AndAlso dr("password") = pwd Then
authenticateadmin = True
authenticateadmin = False
End If
Catch ex As Exception
authenticateadmin = False
End Try

End Function

Public Function makeentry(ByVal insertelement As String) As Boolean
Dim objconn As New SqlConnection
objconn.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString
Dim strsql As String = insertelement
Dim objcmd As New SqlCommand
objcmd.Connection = objconn
objcmd.CommandText = strsql
makeentry = True
Catch ex As Exception
makeentry = False
End Try

End Function

End Class

CODES : Application form

[A] : Apply for a job by filling up the recruitment form .
Partial Class recruitment_form
Inherits System.Web.UI.Page
Protected Sub caldob_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caldob.SelectionChanged
Me.txtdob.Text = Me.caldob.SelectedDate
End Sub

Protected Sub btnsub_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsub.Click

Me.txtmarks10.Text = Format(CType(Me.txtmarks10.Text, Decimal), "##0.00")
Catch ex As Exception
Me.txtmarks10.Text = "0"
Me.txtmarks10.Text = Format(CType(Me.txtmarks10.Text, Decimal), "##0.00")
End Try
Me.txtmarks12.Text = Format(CType(Me.txtmarks12.Text, Decimal), "##0.00")
Catch ex As Exception
Me.txtmarks12.Text = "0"
Me.txtmarks12.Text = Format(CType(Me.txtmarks12.Text, Decimal), "##0.00")
End Try
Me.txtmarksg.Text = Format(CType(Me.txtmarksg.Text, Decimal), "##0.00")
Catch ex As Exception
Me.txtmarksg.Text = "0"
Me.txtmarksg.Text = Format(CType(Me.txtmarksg.Text, Decimal), "##0.00")
End Try
Me.txtmarkspg.Text = Format(CType(Me.txtmarkspg.Text, Decimal), "##0.00")
Catch ex As Exception
Me.txtmarkspg.Text = "0"
Me.txtmarkspg.Text = Format(CType(Me.txtmarkspg.Text, Decimal), "##0.00")
End Try
Dim sb As New StringBuilder()
sb = sb.Append("insert into recruitment_db")
sb = sb.Append("(name,address,date_of_apply,dob,sex,")
sb = sb.Append("designation,specialization,")
sb = sb.Append("marks_10,marks_12,marks_g,marks_pg,subject_g,subject_pg,")
sb = sb.Append("extra_qualification,login_id,password,pwdrq,pwdra,")
sb = sb.Append("quarter_desired,experience,code,interview_marks,exam_marks)")
sb = sb.Append("values")
sb = sb.Append("('" + Me.txtfname.Text.ToString + Me.txtmname.Text.ToString + Me.txtlname.Text.ToString + "',")
sb = sb.Append("'" + Me.txtaddress1.Text.ToString + Me.txtaddress2.Text.ToString + Me.txtpin.Text.ToString + Me.txtcountry.Text.ToString + "',")
sb = sb.Append("'" + Me.txtdoa.Text.ToString + "','" + Me.txtdob.Text.ToString + "','" + Me.radiosex.SelectedItem.Text.ToString + "',")
sb = sb.Append("'" + Me.ddndesig.SelectedItem.Text.ToString + "',")
sb = sb.Append("'" + Me.ddnspecialize.SelectedItem.Text.ToString + "',")
sb = sb.Append("'" + Me.txtmarks10.Text + "','" + Me.txtmarks12.Text + "','" + Me.txtmarksg.Text + "','" + Me.txtmarkspg.Text + "',")
sb = sb.Append("'" + Me.txtsubg.Text.ToString + "','" + Me.txtsubpg.Text.ToString + "','" + Me.txtextrq.Text.ToString + "',")
sb = sb.Append("'" + Me.txtloginid.Text.ToString + "','" + Me.txtpwd.Text.ToString + "',")
sb = sb.Append("'" + Me.ddnprq.SelectedItem.Text.ToString + "','" + Me.txtpra.Text.ToString + "',")
sb = sb.Append("'" + Me.radioquarter.SelectedValue.ToString + "',")
sb = sb.Append("'" + Me.ddnexpe.SelectedItem.Text.ToString + "','" + Me.ddncode.SelectedItem.Text.ToString + "',")
sb = sb.Append("'" + Format(CType("0", Decimal), "##0.00") + "','" + Format(CType("0", Decimal), "##0.00") + "')")
Dim recruit As New hcms
If (recruit.makeentry(sb.ToString)) Then
Me.message.Text = "member registration succesfull"
Me.message.Text = "member registration unsuccesfull"
End If

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.txtdoa.Text = Date.UtcNow
End Sub
End Class

//hcms is a class file which has some reusable codes in it.
// i shall put it now

CODES : Forgot pwd

[A] : Here we can retrieve the loginid,password of any user via its three parameters . if u get doubt put comments in here :
Imports System.Data
Imports System.Data.SqlClient
Partial Class forgot_password
Inherits System.Web.UI.Page

Protected Sub btnpwd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnpwd.Click
Dim rdr As SqlDataReader
Dim param1, param2, param3 As SqlParameter
Dim sb As New StringBuilder
sb = sb.Append("SELECT login_id,password ")
sb = sb.Append("FROM recruitment_db ")
sb = sb.Append("WHERE pwdrq=@pwdrq and pwdra=@pwdra and dob=@dob")
Dim objconn As New SqlConnection
objconn.ConnectionString = ConfigurationManager.ConnectionStrings("hcms").ConnectionString
Dim objcmd As New SqlCommand
objcmd.Connection = objconn
objcmd.CommandText = sb.ToString()
param1 = objcmd.Parameters.Add("@pwdrq", SqlDbType.VarChar)
param1.Value = Me.ddnprq.SelectedItem.Text
param2 = objcmd.Parameters.Add("@pwdra", SqlDbType.VarChar)
param2.Value = Me.txtpra.Text.ToString
param3 = objcmd.Parameters.Add("@dob", SqlDbType.DateTime)
param3.Value = Me.txtdob.Text
rdr = objcmd.ExecuteReader()
If rdr.Read Then
Me.message.Text = "Login Id : " + rdr(0).ToString + " " + "Password :" + rdr(1).ToString
End If
Catch ex As SqlException
message.Text = "xception " + ex.Message.ToString()
End Try
End Sub

Protected Sub caldob_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles caldob.SelectionChanged
Me.txtdob.Text = Me.caldob.SelectedDate

End Sub
End Class

SQL Server Endpoints :

A]Overview of Endpoint :

Endpoints control the capability to connect to an instance of SQL Server as well as dictating the communications methods that are acceptable.

1. Endpoint types of payloads
An endpoint has two basic parts: a transport and payload.
Transport Payload
By combing an endpoint transport and payload, SQL Server can filter acceptable traffic before a command event reached the SQL Server instance. (First the validate the transport and payload, then authenticate)

2. Endpoint access
(1) Even if traffic going to the endpoint matches the correct transport and payload, a connection is still not allowed unless access has been granted on the endpoint.
(2) The first layer of access security is determined by the endpoint state. An endpoint can have one of three states: STARTED, STOPPED, and DISABLED.
* STARTED: The endpoint is actively listening for connections and will replay to an application
* STOPPED: The endpoint is actively listening, but returns a connection error to an application
* DISABLED: The endpoint does not listen and does not respond to any connection attempted
(3) The second layer of security is permission to connect to the endpoint. An application muse have a login created in SQL Server hat has the CONNECT permission granted on the endpoint before the connection is allowed through the endpoint.
(4) SQL Server 2005 ensures that only valid requests can be submitted by a valid user before a request is scheduled within the engine. Administrators also have a master switch to immediately shut off access if they feel someone is attempting to compromise their SQL Server, by setting the state of the endpoint being used to DISABLED.

3. Practice: Inspecting existing endpoints
select * from sys.endpoints
select * from sys.tcp_endpoints
select * from sys.http_endpoints
select * from sys.database_mirroring_endpoints
select * from sys.service_broker_endpoints

B] TCP Endpoints

1. TCP protocol arguments
(1) TCP endpoints are configured to listen on specific IP addresses and port numbers. The two arguments that can be specified that are universal for all TCP endpoints are the following. LISENER_PORT and LISENER_IP.
(2) LISENER_PORT argument is required. The TCP or TSQL endpoint that is created for each instance during installation is already configured for port 1433 o the alternative port number for the instance.
(3) LISENER_IP argument is an optional argument that can provide a powerful security layer for some types of applications. You can specify a specific IP address for the endpoint to listen on. The default setting is ALL.

2. Database mirroring and service broker common arguments
(1) Database mirroring and service broker endpoints provide options to specify the authentication method and the encryption setting. You can use either Microsoft Windows-based authentication or certificates.
(2) Windows-based authentication: NTLM, KERBEROS, NEGOTIATE (Negotiate means that dynamical select the authentication method.)
(3) Best practices
* If the same domain or across trusted domain, use the Windows-based authentication
* If different non-trusted domain, use the certification
(4) All communication between endpoints can be encrypted, and you can specify which algorithm to use for the communications. The default algorithm is RC4, but you can specify the much stronger advanced encryption standard (AES) algorithm.

3. Database mirroring specific arguments
(1) Database mirroring endpoints include a third argument related to the role within the database mirroring session.
(2) Database mirroring endpoints role
Role Description
PARTNER The endpoint can be only as the principal or the mirror
WITNESS The endpoint can be only as the witness
ALL The endpoints can be either partner or witness
(3) Other
4. Database mirroring Practice
(1) structure
(2) preparing works
* Set the recovery mode of the principal to FULL.
* Backup the database on principal
* Restore the database on mirror with NORECOVERY
* Backup the transaction log on principal, restore the transaction log on the mirror
* Transfer to the instance hosting the mirror all logins, jobs, linked server, and other objects external to the database.
--on the principal server
use master
backup database DB_Mirror_Sample
to disk = 'c:\test\DB_Mirror_Sample.bak'
with format

backup log DB_Mirror_Sample
to disk = 'c:\test\DB_Mirror_Sample_Log.bak'
with norecovery

--on the mirroring server
use master

restore database DB_Mirror_Sample
from disk='c:\test\DB_Mirror_Sample.bak'
with file=1, norecovery

restore log DB_Mirror_Sample
from disk='c:\test\DB_Mirror_Sample_Log.bak'
with file=1, norecovery
(3) Establishing endpoints.
Enable the database mirror

Configure security
Change the SQL Server Service Account for Principal, Mirror, and Witness.

(4) You can change operation mode if possible
Mode Witness Explanation
High performance (asynchronous) N/A To maximize performance, the mirror database always lags somewhat behind the principal database, never quite catching up. However, the gap between the databases is typically small. The loss of a partner has the following effect:
* If the mirror server instance becomes unavailable, the principal continues.
* If the principal server instance becomes unavailable, the mirror stops; but if the session has no witness (as recommended) or the witness is connected to the mirror server, the mirror server is accessible as a warm standby; the database owner can force service to the mirror server instance (with possible data loss).
High safety without automatic failover (synchronous) No All committed transactions are guaranteed to be written to disk on the mirror server.
Manual failover is possible when the partners are connected to each other and the database is synchronized.
The loss of a partner has the following effect:
* If the mirror server instance becomes unavailable, the principal continues.
* If the principal server instance becomes unavailable, the mirror stops but is accessible as a warm standby; the database owner can force service to the mirror server instance (with possible data loss).
High safety with automatic failover (synchronous) Yes All committed transactions are guaranteed to be written to disk on the mirror server.
Availability is maximized by including a witness server instance to support automatic failover. Note that you can select the High safety with automatic failover (synchronous) option only if you have first specified a witness server address.
Manual failover is possible when the partners are connected to each other and the database is synchronized.
Important: If the witness becomes disconnected, the partners must be connected to each other for the database to be available.
In the presence of a witness, the loss of a partner has the following effect:
* If the principal server instance becomes unavailable, automatic failover occurs. The mirror server instance switches to the role of principal, and it offers its database as the principal database.
* If the mirror server instance becomes unavailable, the principal continues.

(5) Failover

(6) Removing the mirror
alter database DB_Mirror_Sample set partner OFF

5. Service broker-specific arguments
(1) In addition to authentication modes and encryption, the service broker endpoints implement arguments related to message forwarding.
(2) The MESSAGE_FORWAREDING (DISABLED | ENABLED) option enables messages destined for a different broker instance to be forwarded to a specified forwarding address.
6. Service broker practice

use master
alter database DB_SB
set enable_broker

use DB_SB

create master key
encryption by password = 'Pa$$w0rd'

--message type
create message type SubmitBOMProduct
validation = well_formed_xml
create message type ReceiveBOM
validation = well_formed_xml
-- create contract
create contract BOMContract
(SubmitBOMProduct sent by initiator,
ReceiveBOM sent by target)

[ create queue ]
1. create queue
create queue BOMProductQueue
create queue BOMResultQueue

2 create a service

create service BOMRequestService
on queue BOMProductQueue(BOMContract)
create service BOMResultService
on queue BOMResultQueue(BOMContract)

[ create a conversation ]
declare @dialoghandle uniqueidentifier

begin dialog conversation @dialoghandle
from service BOMRequestService
to service 'BOMResultService'
on contract BOMContract

select @dialoghandle

[ send and receive message ]
select * from BOMProductQueue
select * from BOMResultQueue

1. send msg
send on conversation 'AC0996FF-1C16-DE11-AA62-0003FF1D2E78'
message type SubmitBOMProduct

select * from BOMProductQueue
select * from BOMResultQueue

2. receive msg
receive top(1) *
from BOMResultQueue

select * from BOMProductQueue
select * from BOMResultQueue

C] HTTP Endpoints :
1. HTTP endpoint security
(1) In addition to specifying the HTTP protocol with a SOAP payload that restricts the endpoints to accepting only a well-formed SOAP Request, HTTP endpoints provide additional layers of security.
(2) Authentication method
Type details
Windows NTLM, KERBEROS, or NEGOTIATE (dynamic select)
Certificate Use a certificate from a trusted authority or generate your own Windows certificate
(3) Encryption
Clear text or SSL
(4) Login type
Windows or Mixed
(5) Specifying web methods

2. Creating an endpoint
CREATE ENDPOINT sample_endpoint
SSL_PORT = 1233,

DATABASE = 'DB_Mirror_Sample',

Database Server Security Policies

A] Enforcing SQL Server Security through Group Policy :

1. What is Group Policy
(1) Group policy is a framework that administrators use to control the configuration of users and computers in an Active Directory domain.
* Security options affecting passwords policies
* Software settings affecting application availability
* Desktop configuration settings affecting the start menu appearance
(2) Group policy settings are contained in Group Policy Objects (GPOs), which in turn are associated with selected Active Directory objects: sites, domains, or organizational units.
(3) Local computer policy
Every computer running Windows 2000 or later includes a Local Computer policy, sometimes call a local GPO.
Command name: gpedit.msc; if the GPO, MMC—group policy editor—scope: Default domain policy
get the local GPO
(4) Order of policy processing
No Order Description
1 Local GPO, Each computer has exactly one GOP that is stored locally.
2 Site, Any GPOs that have been linked to the site are processed next. Processing of multiple site-linked GPOs is applied sequentially and in the order specified by the administrator
3 Domain, Processing of multiple domain-linked GPOs is applied sequentially and in the order specified by the administrator
4 OUs, GPOs that are linked to the OU that is highest in the Active Directory hierarchy are processed first, then GPOs that are linked to its child OU, and so on. Finally, the GPOs that are linked to the OU that contains the user or computer are processed.
(5) Administrative templates, enables user to control the registry settings for users and computers through Group Policy.
(6) Configuring Windows Server Update Services (WSUS)
2. Password Policy
(1) In Windows, we can configure password policies either in a local GPO or in a GPO in Active Directory
(2) Enforcing password policy
(3) Enforcing password expiration
(4) Password Complexity, password complexity requirements are designed to deter brute force attacks by eliminating common passwords and by increasing the number of possible passwords
* The password cannot contain all or part of the user’s account name
* The password is at least eight characters long
* The password contains characters from three of the following four categories
Latin uppercase letters (A-Z)
Latin lowercase letters (a-z)
Base 10 digits (0-9)
Non-alphanumeric characters (!, @, #, $, %)
(5) Password policies and Domain-level GPOs, policies take effect only when they are applied to domain-level GPOs.
3. Practice: Enforcing password policy
4. Practice: add the logon script in the Active Directory
(1) Create logon script file
set oNet = CreateObject("wscript.Network")
userid = oNet.UserName
domian = oNet.UserDomain
msgbox "hello: " & domian & "/" & userid

(2) Call the logon script when user logon

B]Encrypting SQL Server Traffic :
1. Server-Level encryption
2. IPSec policies
(1) You can use IPSec policies encrypt traffic to and from Windows-based computers. IPSec requires no configuration within SQL server itself, but both endpoints of the encrypted channel must be authenticated by a common authentication system: a trusted CA or an Active Directory domain.
(2) Windows 2003 include the following three default IPSec policies, all of which you can deploy through local security policy or group policy
* Client (Response Only)
* Server (Request Security)
* Secure Server (Require Security)
3. Compare the Force Encryption Option and IPSec
(1) Deploy environment: Encryption – Outer of the company; IPSec – Active Directory

4. Practice: IIS SSL & Encrypting traffic to and from SQL Server


get a cert.txt file, and the request a cert from a cert publisher.
Issue the certification
Download the issued certification
Install the cert to IIS
After installation, you should set the request need the SSL
Then, you can visit the web site through https

(2) SQL Server SSL
on one SQL Server, you request a and install one certificate from the publisher

The last page presents you with a certificate to install hyperlink, click to install this certificate
Check whether the certificate is stalled or not?

Set the SSL for SQL server

To make SSL active, you please restart the SQL Server service

If you want to disable SSL: first, change the Force Encryption to false; then clear the value for the register key

C] Reducing the Attack Surface of SQL Server 2005 :
1. Disabling unneeded services
You can use the SQL Server Surface Configuration tool to enable, disable, or stop features, services, and remote connectivity of you SQL Server 2005 installations
Component Description
SQL Server Database Engine Database engine, the core service for sorting, processing, and securing data; replication; full-text search; and tools for managing relational and xml data
Analysis Services Includes the tools for creating and managing OLAP and data mining application
Reporting Services Includes server and client components for creating, managing, and deploying tabular, matrix, graphical, and free-form reports. Reporting services is also an extensible platform that you can use to develop report applications
Notification Services Notification services is a platform for developing and deploying application that send personalized, timely info to subscribers on a variety of devices
Integration Services A set of tools and programmable objects for moving, copying, and transforming data

Services Description
SQL Server SQL Server Database Engine
SQL Server Agent Executes jobs, monitors SQL Server, fires alerts, and enables automation of some administrative tasks
Analysis Services Provides OLAP and data mining functionality for BI application
Report Services Manages, executes, renders, schedules, and delivers reports
Integration Services Provide management support for integration services package storage and execution.
SQL Server Browser Provide SQL server connection info for client computers. If you have named instances, you must turn on this to resolve them. Otherwise, you can turn it off.
Full-Text Engine for SQL Create full-text indexes on content and properties of structured and semi-structured data to allow fast linguistic searches on this data
SQL Server Active Directory Helper Publisher and manages SQL Server services in AD
SQL Writer Enables backup and restore app to operate in the Volume Shadow Copy Service (VSS) framework.

2. Service Accounts
According to the principle of lease privilege, user should be granted the minimum rights and permissions necessary to do their jobs.
(1) Using a domain user account. Using a domain user account as service account is preferable when the service in question needs to interact with other services on the network. The following services all require server-to-server connections and are handled by domain user accounts
* Remote procedure calls
* Replication
* Backing up to network drives
* Heterogeneous join that involve remote data access
(2) Using the local service account. The local service account is a special built-in account whose default rights and access permissions are equivalent to those of a member of the users group.
* The minimal privileges
* Can access network resources only as a null session with no credentials
(3) Using the network service account. The network service account is a special built-in account whose default rights and access permissions to local objects are equivalent to those of a member of the users group.
* Can access network resources by using the credentials of the local computers’ computer account
(4) Using the local system account. The local system account is a built-in user account with the most powerful set of rights and permissions on the system and is a common target for exploitation by attackers. For increased security, run SQL Server services under a Windows account with the lowest required privileges.
(5) Groups for SQL Service Accounts. After you specify an account for each SQL Server service, SQL Server Setup creates Windows group accounts for the different SQL Server services and adds the service accounts to these group accounts.
Services Group Account Privilege
SQL Server SQLServer2005MSSQLUser$WIN0301 Log on as a service.
Log on as a batch job
Replace a process-level token
Bypass traverse checking
Adjust memory quotas for a process
Permission to start SQL Server AD Helper
Permission to start SQL Writer
SQL Server Agent SQLServer2005SQLAgentUser$WIN0301$MSSQLSERVER Log on as a service
Log on as a batch job
Replace a process-level token
Bypass traverse checking
Adjust memory quotas for a process
Analysis Server SQLServer2005SQLAgentUser$WIN0301$MSSQLSERVER Log on as a service

Report Server SQLServer2005ReportServerUser$WIN0301$MSSQLSERVER Log on as a service

Notification Services SQLServer2005NotificationServicesUser$WIN0301 N/A
Integration Services SQLServer2005DTSUser$WIN0301 Log on as a service
Permission to write to application event log
Bypass traverse checking
Create global objects
Impersonate a client after authentication
Full-Text Search SQLServer2005MSFTEUser$WIN0301$MSSQLSERVER Log on as a service

SQL Server Browser SQLServer2005SQLBrowserUser$WIN0301 Log on as a service

SQL Server AD Helper SQLServer2005MSSQLServerADHelperUser$WIN0301 None
SQL Writer N/A none

3. Security beast practices
(1) Enhance physical security. You should consider the following recommendations:
* Place the server in a room that is inaccessible to unauthorized persons
* Place computers that host a database in a physically protected location – ideally a locked computer room with monitored flood detection and fire detection or suppression systems.
* Install database in the secure zone of the corporate internet and never directly connected to the internet.
* Back up all data regularly and store copies in a secure offsite location
(2) Use firewalls
* Put a firewall between the server and the internet
* Divide the network into security zones separated by firewalls. Block all traffic and then selectively admit only what is required
* Always block packets addressed to TCP 1433 and UDP port 1434 on your perimeter firewall. If named instances are listening on additional ports, block them, too.
* In a multitier environment, use multiple firewalls to create screened subnets.
* When you are installing the server inside a Windows domain, configure interior firewalls to permit Windows Authentication.
* Open ports used by Kerberos or NTLM authentication.
* If your application uses distributed transactions, you might have to configure the firewall to allow MS DTC traffic to flow between separate MS DTC instances, and between the MS DTC and resource managers such as SQL Server.
(3) Use antivirus software
(4) Isolate services
* Avoid installing SQL Server on a domain controller
* Run separate SQL Server services under separate Windows accounts
* In a multitier environment, run web logic and business logic on separate computers.
(5) Configure a secure file system
* Use NTFS
* Use a redundant array of inexpensive disks (RAID) for critical data files
(6) Disable NetBIOS and server message block

(7) Authentication settings
 Authentication mode: Require Windows authentication for connections to SQL Server.
 String password: Increase security by following these practices.
Enforce password policies and require passwords to meet complexity requirements.
Always assign a strong password to the SA account, even when using Windows authentication.
Always use strong passwords for all SQL Server accounts.
4. Practice: Reducing the attack surface of a Server
(1) Using the surface area configuration tool

(2) Configuring a service account for SQL Server

Database Security :

Designing Instance-level Security

A]. Configuring Service Account :
(1) In SQL Server 2005, when selecting the service account for SQL server instance, you should use an account with minimal permissions to restrict the access to system on your network. Because service accounts are low-privileged accounts, additional configuration is required to ensure that the SQL Server instance can function. To run a SQL Server instance, the account need permissions to several resources, such as the following
* Read/Write permissions to the SQL Server registry keys
* Run as Service tights
* Read/Write permissions to the directories containing database files
(2) Group membership
(3) Service Account Permissions
DBA do not need to change the default permissions assigned to default SQL service group DBA should understand the security context of each command you will execute. (For example, backup)
DBA should grant any additional permission needed for processes to execute to the Windows group that contains the service account.
4. Instance-level principal :
(1) Principal are entities that are granted permissions to a securable. At an instance level, principals are implemented as logins, which can be of five types:
* Standard SQL Server login
* Windows login
* Windows group
* Certificate
* Asymmetric key

You can map a SQL Server login to a Windows user account or Windows group.
Create a Windows user account, specify the user to run IIS, and then you can use this account to connect to SQL Server.

3. Authentication mode :
(1) Windows authentication
(2) SQL Server and Windows authentication (Mixed Mode)
D] Configuring the attack surface :
(1) SQL Server installs and configures under three principles:
* Secure by design
* Secure by default
* Secure by deployment
(2) SQL Server Configuration Manager. It enables you to stop, pause, and start SQL Server services. The most function of the SSCM is to change service accounts and service account passwords.
(3) SQL Server Surface Area Configuration. It enables you to turn features and behaviors on or off.

MSDE, new called SQL Server Express Edition, is installed by many applications to e used as a local data store. Each of these installations is another instance of SQL Server.

The default connection for different SQL Server Edition
Edition Default setting
Express, Evaluation, Developer Local connection
Workgroup, Standard, Enterprise Both local and remote connection

Some description for surface configuration features Feature Description Ad Hoc Remote Queries. If you have any queries that use OPENROWSET or OPENDATASOURCE command
CLR If you intend to use triggers, functions, stored procedures, custom aggregates, or CLR Data types written in .NET language, you must enable the CLR capability.
Database Mail Xp_cmdshell You commonly use xp_cmdshell in administrative procedures to execute ad hoc SQL commands as well as operating system commands.

5. Server role :
name principal_id sid type type_desc
bulkadmin 10 0x0A R SERVER_ROLE
dbcreator 9 0x09 R SERVER_ROLE
diskadmin 8 0x08 R SERVER_ROLE
processadmin 7 0x07 R SERVER_ROLE
public 2 0x02 R SERVER_ROLE
securityadmin 4 0x04 R SERVER_ROLE
serveradmin 5 0x05 R SERVER_ROLE
setupadmin 6 0x06 R SERVER_ROLE
sysadmin 3 0x03 R SERVER_ROLE

6. SQL Server Agent proxy accounts :
Job steps created within SQL Server Agent can access external subsystems such as SSIS or operating system commands. You can create proxy accounts for these jobs to provide the appropriate permissions. This provides more granular control than granting permissions to the SQL Server Agent service account because every job step would then have elevated permissions
7. Designing Security for .NET Assemblies
(1) .NET assemblies use Code Access Security (CAS) to restrict the allowable set of operations that can be performed. SQL Server also uses CAS to lock down the managed code and ensure the integrity of the database server and operating system.
(2) When creating the assembly, the sysadmin specifies the level of CAS that is applied to the assembly. The access permissions available for assemblies are SAFE, EXTERNAL_ACCESS, and UNSAFE.
type Description
SAFE It is the default permission set and does not allow access to resources external to the SQL Server instance or any machine resources.
EXTERNAL_ACCESS It enables an assembly to access resource external to the SQL Server instance such as files, shares, and network resources.
UNSAFE It enables to perform any operation and access any resource.
8. Practice: Managing Accounts

B] Designing Database Security :
1. Database Users and Roles
To grant access to the database, you add the login as a user in the database by executing CREATE USER command. When adding a user to a database, the user is normally mapped to a login, certificate, or asymmetric key. You can add each user in a database to one or more database roles.
Role Description
db_accessadmin Adds or removes user in the database
db_backupoperator Backs up the database
db_datareader Issues select operations against all tables within the database.
db_datawriter Issues insert, update, and delete operations against all tables within the database
db_ddladmin Execute DDK commands
db_denydatareader Denies select operations against all tables within the database
db_denydatawriter Denies insert, update, and delete operations against all tables
db_owner Owner of the database with full control over all objects
db_securityadmin Manages role membership and permissions
public Default group that every user belongs to
2. Designing Schemas
(1) Schemas are new features in SQL Server 2005 that provide a means to group objects within a database together.

(2) A schema is a securable object that enables you to group multiple objects into a schema and then grant permissions to a principal to the scheme.
(3) The most powerful capability of schemas is to manage permissions. Users with the authority to read related to employees can be granted permissions in two ways.
* You can grant select permission to each object within the HumanResources schema
* Or you can issue a single grant statement on the HumanResource schema.
(4) Schema provides more powerful security assignments.

3. Walkthrough Encryption :
(1) Encryption is accomplished by using a flexible, multi-layered series that start at the instance level and goes through data within the database.
(2) Service Master Key. The root of the encryption hierarchy is the service master key, which is automatically generated the first time a credential needs to be encrypted. Service master keys are derived from the Windows credentials of the SQL Server service account and encrypted using either the local machine key or the Windows Data Protection API.
(3) Database Maser key.
* The next layer in the encryption hierarchy is the database master key, which must be explicitly generated using the following command. CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'password'
* Each database has a different master key.
* The database master key is used to protect any certificates, symmetric keys, or asymmetric keys that are stored within the database.
* The database master key is encrypted by using Triple Data Encryption Standards (DES) and the user-supplied password.
* When you make a request to decrypt data, the service master key is used to decrypt the database master key; decrypt a certificate, symmetric key, or asymmetric key; decrypt the data.
(4) Asymmetric Keys. Asymmetric keys use a public and private key system.
(5) Certificates. A public key certificate is digital signed instrument that binds the public key to an identity. It can be a person, organization, or machine that controls the corresponding private key. A certificate is normally issued by a certificate authority that certifies the identity holding the certificate.
(6) Symmetric keys. Symmetric keys use a single key for both encryption and decryption.

4. Designing DDL Triggers :
(1) The main purpose of DDL triggers is to audit as well as regulate actions performed on a database. This enables DDL operation to be restricted even if a user might normally have the permission to execute the DDL command.
5. Practice: Encryption
6. Practice
(1) Creating a database master key

SELECT * FROM sys.symmetric_keys

(2) Encrypting Data with a Passphrase
DECLARE @plaintext NVARCHAR(50)
DECLARE @decrypted nvarchar(50)
DECLARE @encrypted varbinary(52)

SET @plaintext = 'SQL Server 2005'
SET @key = 'MyKey'
SET @encrypted = EncryptByPassPhrase(@key, @plaintext)
SET @decrypted = DecryptByPassPhrase(@key, @encrypted)

SELECT @encrypted Encrypted, @decrypted Decrypted

(3) Creating s self-signed Certificate
DECLARE @encrypted varbinary(500)
DECLARE @decrypted varchar(50)
SET @encrypted = EncryptByCert(Cert_id('MyCert'), 'SQL Server 2005')
SET @decrypted = DecryptByCert(Cert_id('MyCert'), @encrypted)

SELECT @encrypted Encrypted, @decrypted Decrypted

(4) Creating an Asymmetric key

SELECT * FROM sys.asymmetric_keys

DECLARE @encrypted varbinary(500)
DECLARE @decrypted varchar(50)

SET @encrypted = EncryptByAsymKey(AsymKey_id('MyAsymmetricKey'), 'SQL Server 2005')
SET @decrypted = DecryptByAsymKey(AsymKey_id('MyAsymmetricKey'), @encrypted)

SELECT @encrypted Encrypted, @decrypted Decrypted

(5) Create a DDL Trigger
CREATE TRIGGER tddl_table_preventdropalter
PRINT 'You are attempting to drop or alter tables in production!'

DROP TABLE XmlTransfer

C] Securing Database Object :
1. Permission Scope
(1) Permissions are granted on a securable that can be a database, a schema, or an object. This creates a hierarchical structure of permissions within a database.
(2) The first layer of security that you will want to plan within a database is a schema. Objects are then created within each schema. After objects are created in schemas, permission are granted on the schemas to provide security access to an application.
2. Execution Context
(1) An execution can be specified for code. Specifying an execution context enables code to be run under a specific security context.
(2) Module execution context
Context Description
CALLER Default behavior. The permissions of the user are evaluated based on the permissions granted by the schema owner.
Execute the code under another user’s credentials
SELF Executes under the security credentials of the user specifying the execution context
OWNER Executes under the security credentials of the owner of the schema that the object belongs to.
3. Encrypting Columns
4. Practice: Granting Permission
(1) Grant permission to a database.
(2) Grant permission to a schema.
(3) Encrypt and decrypt column
create table staff
staff_no nvarchar(5) not null,
first_name nvarchar(30) not null,
last_name nvarchar(10) not null,
salary varbinary(256)

insert into staff
(staff_no, first_name, last_name, salary)
('10000','Bill', 'Zhang',
ENCRYPTBYPASSPHRASE('Password', convert(nvarchar(20),'8000.00'),
1, convert(varbinary, '10000')))


staff_no, first_name, last_name,
CONVERT(nvarchar(20), DecryptByPassphrase('Password', salary, 1, CONVERT(varbinary, '10000')))
AS salary
from staff

I Hope Dat Was Commentable !!!

Cache object in ASP.NET designs

An effective caching strategy is a key element of any application design. It increases performance by returning data more quickly to a larger number of users. It also increases scalability by limiting the number of calls required to back-end systems by providing data from a local source instead of requiring a call to the back end. Beyond the Application and Session objects, classic ASP provided little support for caching mechanisms. ASP.NET, however, provides advanced caching capabilities in the form of a programmable Cache object.

Implementing the Cache object :
Program can access the Cache object using the System.Web.Caching namespace. You can set a reference to the Cache object using either the Cache property of the HttpContext class in the System.Web namespace or the Cache property of the Page object. The Cache object allows you to store key-value pairs that become accessible by any user or page in the application domain. For example, you can store a list of state abbreviation and state names in a Dataset called ShortState and then store that Dataset object in the Cache for use by any page that needs to allow state selection or display by abbreviation. Loading the page from the cache eliminates the need to regenerate the database programmatically or to load it from a back-end database.

Cache object memory management :
The inability to automatically manage cached objects is one of the most significant limitations of the classic ASP-caching mechanisms. Developers using the Application or Session objects had to write code to manage the creation and destruction of the data they managed. But the ASP.NET Cache object adds dependency and expiration policies to make cache management automatic. Whenever you add an item to the ASP.NET cache, you have the option of telling the common language runtime (CLR) when to remove the item automatically. This automatic removal depends on certain conditions and is therefore called a cache dependency. When an item is to be removed from the cache, it’s said to be invalidated. Invalidating a cached item tells the CLR that it should remove the item from the cache. Built in ASP.NET cache dependencies include file, key, and time-based features. Let’s look at each of these in more detail.

File dependency :
In many cases, you may want a cached item to be invalidated when a disk-based file changes. For example, if you use data generated or uploaded by an external system, you need to refresh the cached data whenever that external system sends new data. Suppose that your ASP.NET application relies on a customer list supplied by a mainframe and that the mainframe sends new data in a file named Customers.xml to an FTP site whenever the customer list changes. The code fragment shown BELOW

CacheDependency cDepend = new CacheDependency(“C:\InetPub\FTP\customers.xml”);
//Custom method to build dataset from xml file in FTP directory

DataSet ds = new BuildDSFromXml(“customers.xml”);

Cache.Insert(“Customers”, ds, cDepend);

uses a custom method called BuildDSFromXml to load the file from the FTP site and the CacheDependency object to introduce a file dependency into the cache

Key dependency :
In many cases, you may want cached items to depend on or relate to one another. If your application caches calculated values based on the values in other cached keys, you would want the calculated values to be invalidated whenever the values upon which they were based have been changed. The code fragment shown BELOW

Cache[“Fname”] = “VIP”;

String[] dependencyKey = newString[1];

dependencyKey[0] = “Fname”;

CacheDependency cDepend = new CacheDependency(null, dependencyKey);

Cache.Insert(“LName”, “Landgrave”, cDepend);

demonstrates how to introduce a key dependency between cached objects.

Time expiration :
In many cases, the values in the cache don’t depend on other circumstances but instead depend on the amount of time that has passed since they were placed in the cache. When determining the amount of time that an item should remain in the cache before it’s invalidated, you can either specify an exact time at which it should be invalidated or the amount of time that it can stay in the cache without being accessed.

You can use the first method to ensure that cached items are refreshed on a regular schedule. For example, if you want data to be cached each morning that reflects activity from the prior day, you can programmatically set the cache to invalidate at 8 A.M. on the following morning, thus forcing your system to use and cache new data after that time. Using the second method—commonly called the sliding window—you can ensure that items are kept in the cache only when being used regularly. For example, using the command shown in Listing C, you can cache a list of hot selling items in a commerce site and specify that the list of items be regenerated if the list hasn’t been accessed from the cache in the last 30 seconds.

Effective caching helps manage resources :
Effective use of the caching capabilities in ASP.NET will allow you to balance the use of precious resources like machine memory and database connections with the need to generate client pages quickly. The ASP.NET Cache object adds another tool to the architect’s arsenal that you can use when designing caching strategies for Web-based systems.

AppDomains - ASP.NET applications Stability

What is it?
The Application Domain, known as AppDomain, provides a sandbox for .NET applications. An AppDomain is a container, or secure boundary, for code and data used by the .NET runtime. It is analogous to an operating system process used for an application and its data. The code and data is securely isolated within the boundaries of an AppDomain.
The goal of an AppDomain is to isolate the applications within it from all other application domains. That is, applications are protected from being affected by other applications running in different application domains. It provides stability.
This isolation of AppDomains is achieved by making sure exactly one application occupies unique parts of memory and scopes the resources for the process or application domain using that address space. The .NET runtime enforces AppDomain isolation by controlling memory usage. Application domains run on a single Win32 process. All AppDomain memory is managed by the runtime to ensure no overlap in memory usage.
It may seem like there is one AppDomain for every application, but the .NET Common Language Runtime (CLR) allows multiple applications to run within a single AppDomain. The CLR also verifies that the user code in an AppDomain is type safe. An assembly must be loaded into an AppDomain before it can execute. By default, the CLR loads an assembly into the AppDomain containing the code that references it.
The CLR automatically creates a default AppDomain when a process that hosts the CLR is created. This default AppDomain exists as long as the host process is alive. A good example of hosting the CLR is IIS.

When a request first enters an ASP.NET application, the IIS-managed engine module creates an application domain; then the application domain performs the necessary processing tasks for the application, such as authentication.
When dealing with multiple ASP.NET applications on a server, the ASP.NET worker process will host all of them, but each one will have its own. This ensures that each application is protected from problems in another application. In addition, each application has its own set of global variables. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain.
An interesting caveat with ASP.NET and application domains is the fact that ASP.NET applications run with full trust rights by default. Applications running with full trust can execute native code and circumvent all security checks by the .NET runtime, so the security boundary provided by the application domain is moot. You can override the default behavior and run applications with partial trust to overcome this issue.

It is easy to see the benefits of the AppDomain concept, as applications are protected from harming others. It is great for ASP.NET hosting providers to protect customer applications from each other. In addition, the .NET Framework provides programmatic access to the application domain concept.

Programmatic access
AppDomain class is in the base System namespace. The Microsoft documentation offers the following guidelines for using the AppDomain class:
* Use application domains to isolate tasks that might bring down a process. If the state of the AppDomain that’s executing a task becomes unstable, the AppDomain can be unloaded without affecting the process. This is important when a process must run for long periods without restarting. You can also use application domains to isolate tasks that should not share data.
* If an assembly is loaded into the default application domain, it cannot be unloaded from memory while the process is running. However, if you open a second application domain to load and execute the assembly, the assembly is unloaded when that application domain is unloaded. Use this technique to minimize the working set of long-running processes that occasionally use large DLLs.

The AppDomain class allows you to create and manipulate your own application domains based upon your needs. The CreateDomain method is available to create a new application domain. The following C# snippet creates a new application domain and executes an assembly within the new application domain.

AppDomain domain = AppDomain.CreateDomain("TestAppDomain");
domain.ExecuteAssembly("AssemblyName.exe", null, args);

In addition to creating a new application domain, the AppDomain class provides methods and properties for working with new and existing application domains.

This comprehensive list of online samples show you how to work with the current application domain and interact with other application domains.

Application domains are an essential feature of the .NET platform because they isolate applications from each other; this prevents problems in one application from affecting others running on the same platform. In addition, the AppDomain class allows you to create your own application domains to isolate tasks for various reasons.

Windows Server 2008

Security :
From a security perspective Windows Server 2008 includes Network Access Protection (NAP). The NAP engine ensures that workstation computers that connect to your network meet minimum computer defined requirements set forth in the security policy your administrator creates.

For example, a virtual employee visits corporate HQ for the first time in four weeks with his laptop. When he hooks up to the network, he is required to update security and critical windows patches before connecting to the network. Until all this work is done, the laptop via NAP can be quarantined or denied access completely until the computer meets the minimum health requirements. ha ha ha!!!

In a perfect world, all domain controllers would be in a single server room with unlimited bandwidth and power with constant surveillance. We do not live in this world and in many corporations there are quite a few satellite or branch offices throughout the country or world. In Window Server 2008, you can configure Read-Only Domain Controllers (RODC).

An RODC is a domain controller that you could install at a remote location and its sole purpose is to host a read-only copy of your Active Directory (AD) database. This method gives you peace of mind in not having to worry about the physical security of a domain controller hundreds or thousands of miles away. The RODC holds a minimal set of information and all changes made must come from a domain controller with full control that replicates to the RODC.

For example, a major car dealership could have all of their domain controllers in corporate headquarters and put an RODC in every dealership location throughout the country instead of the current common practice of a full-control domain controller. I am really excited about this feature in Windows Server 2008.

Terminal Services :
Microsoft is moving in on Citrix territory even more as they now introduce the following components: Terminal Server Gateway, RemoteApp, and Terminal Services Web Access. Terminal Server Gateway allows remote user’s access to Terminal Servers through your perimeter firewall. RemoteApp allows you to publish applications on a Terminal Server as opposed to an entire desktop. Finally, Terminal Server Web access provides you with a portal to access application and/or desktops.

IIS 7.0 :
Over the years, Internet Information Services (IIS), Microsoft’s flagship web server product, has taken a lot of flack for being hacked and compromised.Microsoft and the IIS team did something above and beyond what was expected by completely redesigning and overhauling IIS’s core functionality and design.

What’s New
The IIS team has taken the core functionality of IIS and broken it down into modules. You can take any one of these modules and break them down further by plugging or unplugging them as well as extending them or simply ripping the code out and not using them at all.
In other words, you can turn on or turn off any module in IIS whenever you want. For example, if you do not use basic authentication in your web sites, you can simply remove the code quickly and simply. Furthermore, if your application does not take advantage of common gateway interfaces (CGI), simply remove that specific component.
Now when you deploy a brand new web server, you can choose what components you want and only run those components. This allows you to secure IIS further and gives you a huge performance boost enabling IIS to run much faster than it ever has before.
Another area is ASP.NET integration. Currently, ASP.NET sits on top of IIS and compliments it very well. In IIS 7, IIS and ASP.NET are completely integrated with one another. Included in this integration is the entire .NET framework, ADO.NET and the next version of the web services platform called Indigo.

Ease of Use
We now have one configuration point for all of our components as opposed to managing two or more. This greatly eases the IT administrator’s life.

Windows Management Instrumentation (WMI) is also being widely used in IIS 7, making it easy to manage IIS 7 via WMI. Simply put, it allows you to manage IIS from a set of scripts that you create. There is a lot of automation that can be done with IIS 7.0 via WMI. Your IT administrators will welcome the enhancements.

Prior to IIS 7.0, there was no way to delegate rights to developers. You had to be an administrator on the machine or you had to make the developer a local administrator to perform routine IIS tasks.This is not the best way to maximize security. Ideally, you want to be able to have developers do their job without having to elevate their privileges.This is taken care of in IIS 7. You do not need to be a machine administrator to perform basics tasks. You have the ability to make specific people website operators on a machine and give them the appropriate tasks to do their job without elevating their privileges.
All of these tasks are now handled by the new IIS 7 web admin tool that replaces the existing MMC snap-in. This tool takes care of all of your administrators needs and is where they will manage their IIS 7 web servers.

The last feature I am going to talk about is the web.config file. This is where all information that is input in the web admin tool is stored. You could edit this file manually, if your IT administrator did not want to use the web admin tool. They could put this web.config file on a file server to be accessed by multiple servers in a cluster.One change to the web.config file will change every web server in your infrastructure that is pointed to it. This is very powerful.
IIS 7 meets a lot of needs: modular components, easy administration, security, delegation, and speed.

LINQ in Visual Studio 2008

LINQ was first introduced in C# 3.0 and added to Visual Basic 9.0 with .NET 3.5.

LINQ and the Visual Studio 2008 IDE make it easy to pull data from a SQL Server database via a template item called LINQ to SQL Classes that you may add to a project. A dbml resource is created when you add this item type with a default name (that you may change) of DataClasses1.dbml.
Once the item is added, the O/R Designer pane opens within Visual Studio. This allows you to drag and drop database items (tables, views, stored procedures) to the O/R Designer which generates the dbml file, which provides the mapping between the LINQ to SQL classes and database objects. The O/R Designer also generates the typed DataContext and the entity classes.
There are two main areas within the O/R Designer pane: Entities and Methods. The main area of the design area is for entities like Tables and Views, along with their hierarchies and relationships. The Methods pane includes stored procedures and functions that are mapped to methods of the DataContext class. The O/R Designer currently supports SQL Server 2000, SQL Server 2005, and SQL Server Express Edition.

Suppose a Web Form contains an instance of the GridView controlwhich displays data via LINQ. Code is placed in the form’s Page_Load event, so the data is loaded when the page is opened.

The first step is to create an instance of the DataContext class. This provides database access, so I can access its included table as a property of the DataContext class. Once the DataContext class is created, I can pull data from it via a query.
The code includes a query that pulls all data records and columns from the Customers table. The data is sorted by the second column, and the query is executed when it is bound to the GridView control on the page.
protected void Page_Load(object sender, EventArgs e) {
DataClasses1DataContext db = new DataClasses1DataContext();
var customers = from p in db.Customers
orderby 1 "1 means the second column"
select p;
gvCustomers.DataSource = customers;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As DataClasses1DataContext = New DataClasses1DataContext()
Dim customers As Object
customers = From p In db.Customers Order By 1 Select p
gvCustomers.DataSource = customers
End Sub

When the page loads, all data from the Customers table is displayed in the GridView control.
As a further example, I can easily call the SQL Server stored procedure as a method of my DataContext object. The results of the method – stored procedure — can be used to populate a data control like the previously used GridView, as the next code snippet demonstrates:
protected void Page_Load(object sender, EventArgs e) {
DataClasses1DataContext db = new DataClasses1DataContext();
var top_customers = db.Ten_Most_Expensive_Products();
gvCustomers.DataSource = top_customers;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As DataClasses1DataContext = New DataClasses1DataContext()
Dim customers As Object
customers = db.Ten_Most_Expensive_Products()
gvCustomers.DataSource = customers
End Sub

These simple examples demonstrate query syntax and how to use the O/R Designer within Visual Studio 2008. LINQ allows you to manipulate (update, delete, add) and read data.
Details at Microsoft MSDN...

Service Basics

A service is a contract between two VSPackages. One VSPackage provides a specific set of interfaces for another VSPackage to consume. Visual Studio is itself a collection of VSPackages that provides services to other VSPackages.
For example, you can use the SVsActivityLog service to obtain an IVsActivityLog interface, which you can use to write to the activity log.
Services have no discoverability. Therefore, you must know the service identifier (SID) of a service that you want to consume, and you must know which interfaces it provides. The reference documentation for the service provides this information.

* VSPackages that provide services are called service providers.
* Services that are provided to other VSPackages are called global services.
* Services that are available only to the VSPackage that implements them, or to any object it creates, are called local services.
* Services are loaded on demand, that is, the service provider is loaded when the service it provides is requested by another VSPackage.
* To support on-demand loading, a service provider registers its global services with Visual Studio. For more information, see Registering Services.
* After you obtain a service, use QueryInterface (unmanaged code) or casting (managed code) to get the desired interface, for example:
Visual Basic
TryCast(GetService(GetType(SVsActivityLog)), IVsActivityLog)
GetService(typeof(SVsActivityLog)) as IVsActivityLog;

* Managed code refers to a service by its type, whereas unmanaged code refers to a service by its GUID.
* When Visual Studio loads a VSPackage, it passes a service provider to the VSPackage to give the VSPackage access to global services. This is referred to as "siting" the VSPackage.
* VSPackages can be service providers for the objects they create. For example, a form might send a request for a color service to its frame, which might pass the request to Visual Studio.
* Managed objects that are deeply nested, or not sited at all, may call GetGlobalService for direct access to global services.

How to: Provide a Service (C#) :

A VSPackage can provide services that other VSPackages can consume. To provide a service, a VSPackage must perform the following tasks:
* Register the service with Visual Studio.
Implement IServiceProvider.
The Package class implements both IServiceProvider and IServiceContainer. IServiceContainer holds callback methods to provide local and global services on demand.
When a VSPackage is about to be unloaded, Visual Studio waits until all requests for services that a VSPackage provides have been delivered. It does not allow new requests for these services. Therefore, VSPackages should not explicitly call the RevokeService method to revoke a service when unloading.

The following code is taken from the Reference.Services Sample (C#). It provides the local service, SMyLocalService, and the global service, SMyGlobalService.
To provide a service
Add the ProvideServiceAttribute to the VSPackage providing the global service.
public sealed class ServicesPackage : Package
The ProvideServiceAttribute registers SMyGlobalService with Visual Studio. Only the global service must be registered.
Add callback methods to the service container to create the services.
public ServicesPackage()
IServiceContainer serviceContainer = this as IServiceContainer;
ServiceCreatorCallback callback =
new ServiceCreatorCallback(CreateService);
serviceContainer.AddService(typeof(SMyGlobalService), callback, true);
serviceContainer.AddService(typeof(SMyLocalService), callback);

The true flag instructs the service container to make SMyGlobalService a global service.
Visual Studio can reject a request to provide a service. It does so if another VSPackage already provides the service.
Implement the callback method.
private object CreateService(IServiceContainer container, Type serviceType)
if (typeof(SMyGlobalService) == serviceType)
return new MyGlobalService(this);

if (typeof(SMyLocalService) == serviceType)
return new MyLocalService(this);

CreateService creates either SMyGlobalService or SMyLocalService on demand.

Implement the global service class.
public class MyGlobalService : IMyGlobalService, SMyGlobalService
private IServiceProvider serviceProvider;
public MyGlobalService(IServiceProvider sp)
"Constructing a new instance of MyGlobalService");
serviceProvider = sp;
// Implement the methods of IMyGlobalService here.

The MyGlobalService class implements both SMyGlobalService and the IMyGlobalInterface interface provided by this service. The service provider passed to the constructor is cached so that the interface methods have access to other services.
Implement the local service class.
public class MyLocalService : IMyLocalService, SMyLocalService
private IServiceProvider serviceProvider;
public MyLocalService(IServiceProvider sp)
"Constructing a new instance of MyLocalService");
serviceProvider = sp;
// Implement the methods of IMyLocalService here.

Consume a Service & Activity Logs Writing

How to: Consume a Service (C#)
Any managed VSPackage that derives from Package and that has been correctly sited can ask itself for any global service. Because the Package class implements IServiceProvider, any VSPackage that derives from Package is also a service provider.
When Visual Studio loads a managed VSPackage, it passes an IServiceProvider service provider to the Package SetSite method during initialization, siting the VSPackage. The Package class wraps this service provider and provides the GetService method for obtaining services.
Because the VSPackage constructor is called before the VSPackage is sited, global services are typically unavailable from within the VSPackage constructor.
How to: Troubleshoot Services for a workaround.
To consume a service
Insert this code in any method except the VSPackage constructor:
IVsActivityLog log =
GetService(typeof(SVsActivityLog)) as IVsActivityLog;
if (log == null) return;

This code obtains an SVsActivityLog service and casts it to an IVsActivityLog interface, which can be used to write to the activity log.

How to: Write to the Activity Log (C#) :
To write an entry to the activity log
Insert this code in the Initialize method or in any other method except the VSPackage constructor:
IVsActivityLog log =
GetService(typeof(SVsActivityLog)) as IVsActivityLog;
if (log == null) return;
int hr = log.LogEntry(
"Entering initializer for: {0}", this.ToString())

This code gets the SVsActivityLog service and casts it to an IVsActivityLog interface. LogEntry writes an informational entry into the activity log using the current cultural context.
In the Visual Studio Command Window, start devenv.exe with the /log switch. Make sure that you add the appropriate /rootsuffix argument to run in the registry root where the VSPackage is registered, for example: devenv /rootsuffix Exp /log.
Load the VSPackage.
To examine the activity log
Find the activity log.
By default, the location is \Application Data\Microsoft\VisualStudio\8.0Exp\ActivityLog.XML.
Open the activity log with any text editor.

Visual Studio 2010

Visual Studio 2010, codenamed "Hawaii", is under development. A CTP version of Visual Studio 2010 is publicly available as a pre-installed Virtual Hard Disk containing Windows Server 2008 as the OS.

The Visual Studio 2010 IDE has been redesigned which, according to Microsoft, clears the UI organization and "reduces clutter and complexity". The new IDE better supports multiple document windows and floating tool windows, while offering better multi-monitor support. The IDE shell has been rewritten in Windows Presentation Foundation (WPF); where as the internals have been redesigned using Managed Extensibility Framework (MEF) that offers more extensibility points than previous versions of the IDE that enabled add-ins to modify the behavior of the IDE. The new multi-paradigm programming language ML-variant F# programming language will be a part of Visual Studio 2010; as will be the M, the textual modelling language, and Quadrant, the visual model designer, which are a part of the Oslo initiative.

Visual Studio 2010 will come with .NET Framework 4.0 and will support developing applications targeting Windows 7. It will support IBM DB2 and Oracle databases out of the box, in addition to Microsoft SQL Server. It will have integrated support for developing Microsoft Silverlight applications, including an interactive designer.Visual Studio 2010 will offer several tools to make parallel programming simpler. In addition to the Parallel Extensions for .NET Framework and the Parallel Patterns Library for native code, Visual Studio 2010 includes tools for debugging parallel applications. The new tools lets parallel Tasks and their runtime stacks to be visualized. Tools for profiling parallel applications can be used for visualization of thread wait times and thread migrations across processor cores.

The Visual Studio 2010 code editor now highlights references; whenever a symbol is selected, all other usages of the symbol are highlighted. It also offers a Quick Search feature to incrementally search across all symbols in C++, C# and VB.NET projects. Quick Search supports substring matches and camelCase searches. The Call Hierarchy feature allows the developer to see all the methods that are called from a current method as well as the methods that call the current one. IntelliSense in Visual Studio supports a consume-first mode, which can be opted-into by the developer. In this mode, IntelliSense will not auto-complete identifiers; this allows the developer to use undefined identifiers (like variable or method names) and define those later. Visual Studio 2010 can help in this also by automatically defining them, if it can infer their types from usage.

Visual Studio Team System 2010, codenamed Rosario is being positioned for Application lifecycle management. It will include new modelling tools, including the Architecture Explorer that graphically displays the projects and classes and the relationships between them. It supports UML activity diagram, component diagram, (logical) class diagram, sequence diagram, and use case diagram. Visual Studio Team System 2010 also includes Test Impact Analysis which provides hints on which test cases are impacted by modifications to the source code, without actually running the test cases. This speeds up testing by avoiding running unneeded test cases.

Visual Studio Team System 2010 also includes a Historical Debugger. Unlike the current debugger, that records only the currently-active stack, the historical debugger records all events like prior function calls, method parameters, events, exceptions etc. This allows the code execution to be rewound in case a breakpoint wasn't set where the error occurred. The historical debugger will cause the application to run even slower than the current debugger, and will use more memory as a lot of data needs to be recorded. Microsoft allows configuration of how much data should be recorded, in effect allowing developers to balance speed of execution and resource usage. The Lab Management component of Visual Studio Team System 2010 uses virtualization to create a similar execution environment for testers and developers. The virtual machines are tagged with checkpoints which can later be investigated for issues, as well as to reproduce the issue. Visual Studio Team System 2010 also includes the capability to record test runs, that capture the specific state of the operating environment as well as the precise steps used to run the test. These steps can then be played back to reproduce issues.
Pre-Installed Virtual Machines :

Microsoft is offering virtual machines with Visual Studio Team System 2008 and 2005 pre-installed in the documented Virtual Hard Disk format for trial use.

Visual Studio 2008

Visual Studio 2008, codenamed  Orcas , was released to MSDN subscribers on 19 November 2007 alongside .NET Framework 3.5. The codename Orcas is, like Whidbey, a reference to an island in Puget Sound, Orcas Island. The source code for the Visual Studio 2008 IDE will be available under a shared source license to some of Microsoft's partners and ISVs.Microsoft released Service Pack 1 for Visual Studio 2008 on 11 August 2008.

Visual Studio 2008 is focused on
development of Windows Vista, 2007 Office system, and Web applications. For visual design, a new Windows Presentation Foundation visual designer and a new HTML/CSS editor influenced by Microsoft Expression Web are included. J# is not included. Visual Studio 2008 requires .NET Framework 3.5 and by default configures compiled assemblies to run on .NET Framework 3.5, but it also supports multi-targeting which lets the developers choose which version of the .NET Framework (out of 2.0, 3.0, 3.5, Silverlight CoreCLR or .NET Compact Framework) the assembly runs on. Visual Studio 2008 also includes new code analysis tools, including the new Code Metrics tool. For Visual C++, Visual Studio adds a new version of Microsoft Foundation Classes (MFC 9.0) that adds support for the visual styles and UI controls introduced with Windows Vista. For native and managed code interoperability, Visual C++ introduces the STL/CLR, which is a port of the C++ Standard Template Library (STL) containers and algorithms to managed code. STL/CLR defines STL-like containers, iterators and algorithms that work on C++/CLI managed objects.

Visual Studio 2008 features a XAML based designer (codenamed Cider), workflow designer, LINQ to SQL designer (for defining the type mappings and object encapsulation for SQL Server data), XSLT debugger, JavaScript Intellisense support, JavaScript Debugging support, support for UAC manifests, a concurrent build system, among others. It ships with an enhanced set of UI widgets, both for WinForms and WPF. It also includes a multithreaded build engine (MSBuild) to compile multiple source files (and build the executable file) in a project across multiple threads simultaneously. It also includes support for compiling PNG compressed icon resources introduced in Windows Vista. An updated XML Schema designer will ship separately some time after the release of Visual Studio 2008.

The Visual Studio debugger includes features targeting easier debugging of multi-threaded applications. In debugging mode, in the Threads window, which lists all the threads, hovering over a thread will display the stack trace of that thread in tooltips. The threads can directly be named and flagged for easier identification from that window itself. In addition, in the code window, along with indicating the location of the currently executing instruction in the current thread, the currently executing instructions in other threads are also pointed out. The Visual Studio debugger supports integrated debugging of the .NET Framework 3.5 BCL. It can dynamically download the BCL source code and debug symbols and allow stepping into the BCL source during debugging. Currently a limited subset of the BCL source is available, with more library support planned for later in the year.