Thursday, March 28, 2013

Disable UAC (User Account Control) Setting in Windows 8

Disable UAC (User Account Control) Setting in Windows 8

Hi,
This post i want to tell that in Window's 8 OS, although we Enable / Disable the UAC setting. It didn't affect in Registry (REGEDIT).

First we will see what is UAC
UAC (User Access Control):

It notifies us before changes are made to our PC that require administrative permissions. Mean once we change the UAC Setting from "Always Notify" to "Never Notify" we can Install Programs / Software which Window's OS thinks as harmful to system.

How to launch UAC Setting Screen: 

Open windows Run
Type "MSCONFIG" and press enter
Select Tools tab
Select "Change UAC Setting" tool and
Click on "Lauch" button

or

UAC Application Location:
C:\Windows\System32\UserAccountControlSettings.exe

Issue with Windows 8:

Althoug you change the UAC Setting with appliction. It didn't get changed in the Windows Registry, so in that case we have to change the value against concern Key in Registry as follows

Open the registry with REGEDIT command from Windows RUN and locate the following key in registry

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

here in right pane change the value for EnableLUA from 1 to 0 and restart you machine and enjoy...



Bye.


Monday, March 25, 2013

Computed Column in SQL Table


Computed Column:

We can add computed column in SQL Database tables where the value of one column is calculated from one or more columns of the same table. While creating table we have to use the column name for calculation of computed column.

Example:

I want to calculate the Square, Cube etc of the Number and store in database. For this i have the following create table statement

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Num * Num * Num)
)

Here first column of the table definition is number for which I want to calculate the Square and Cube, so while adding second column as Sq (Square) I have used first column name Num * Num, and same way for cube.

Insert values in table.

Insert one value at a time into table.
INSERT INTO ROOTS VALUES (-1)

Insert more than one value into table.
INSERT INTO ROOTS VALUES (1) , (2) , (3) , (4) , (5) , (6) , (7) , (8)


One computed column we can not use for the calculation of another Computed column. If we try to create table definition as shown below

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Sq * Num)
)

SQL Query Analyser will throw the following error

"Msg 1759
Computed column 'Sq' in table 'Roots' is not allowed to be used in another computed-column definition."

Friday, March 22, 2013

Take SQL Database Backup using C#


Take SQL Database Backup using C#

Hi Dear,

I have studied it from one of the Blog. Where using SQL Server SMO (Server Management Object) in C# how to take a SQL Server Database Backup. There are other ways also to take database backup like through wizard in SQL Management Studio.

1.  Add following references to your project

a.  Microsoft.SqlServer.ConnectionInfo
b.  Microsoft.SqlServer.Management.Sdk.Sfc
c.  Microsoft.SqlServer.Smo
d.  Microsoft.SqlServer.SmoExtended
e.  Microsoft.SqlServer.SqlEnum

2.  In your CS file add folliwing 2 Usings statements

a.  Microsoft.SqlServer.Management.Smo;
b.  using Microsoft.SqlServer.Management.Common;


following classes objects used to take Backup

a.  Backup
b.  BackupDeviceItem
c.  ServerConnection
d.  Server
e.  Database

and following enums are used for assgning values

a.  BackupTruncateLogType ( it contains NoTruncate, Truncate and TruncateOnly)
b.  BackupActionType (it contains Database, Files and Log)


Steps to take Backup:
1.  Create object of Backup Class
2.  Assign Action, Database, BackupSetDescrption, Checksum, Intialize, ContinueAfterError, ExpirationDate etc properties.
3.  Create object of BackupDeviceItem class
4.  Create object of ServerConnection class
5.  Create object of Server class with ServerConnection object
6.  Add object of BackupDeviceItem class as Device to object of Backup Class
7.  Call SqlBackup method of object of Backup Class
8.  Remove Device from object of Backup Class

Code:

public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
            {

                try
                {                  
                    Backup BKP = new Backup();

                    BKP.Action = BackupActionType.Database;
                    BKP.BackupSetDescription = "BackUp of: " + databaseName.ToUpper() + "on" + DateTime.Now.ToString();
                    BKP.BackupSetName = databaseName.ToUpper();
                    BKP.Database = databaseName.ToUpper();

                    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + databaseName.ToUpper() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".bak", DeviceType.File);

                    ServerConnection connection = new ServerConnection(serverName, userName, password);

                    Server sqlServer = new Server(connection);
                    sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
                    Database db = sqlServer.Databases[databaseName];

                    BKP.Initialize = true;
                    BKP.Checksum = true;
                    BKP.ContinueAfterError = true;
                    BKP.Devices.Add(deviceItem);
                    BKP.Incremental = false;
                    BKP.ExpirationDate = DateTime.Now.AddDays(3);
                    BKP.LogTruncation = BackupTruncateLogType.Truncate;
                    BKP.FormatMedia = false;
                    BKP.SqlBackup(sqlServer);
                    BKP.Devices.Remove(deviceItem);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.Read();
                }
            }
        }

Wednesday, March 20, 2013

SQL Server User Defined Functions

SQL Server User Defined Functions:

Functions accepts some parameters process and then returns some data. A function can have maximum 1024 input parameters. A parameter of the function can have a default value, the keyword DEFAULT must be specified when calling the function to get the default value. UDF are used to reduce the code blocks and it makes easy to maintain the function in case it needs to change.

UDF Types:

1.  Scalar value returning UDF
2.  Table value returning UDF
     a.  Inline Table
     b.  Multistatement Table

Scalar UDFs:

These UDFs returns a single value of a scalar datatypes such as integer, varchar(n), char(n), money, datetime, bit etc. Even UDF returns User Defined Data Types (UDDTs). All the datatypes can not be returned from the UDFs like text, ntext, image, timestamp etc.

How to Create Scalar UDF:

CREATE FUNCTION fnNeedToReorder
     (
         @ReorderLevel INT,
         @UnitsInStock INT,
         @UnitsOnOrder INT
     )
    RETURNS VARCHAR(3)
AS
BEGIN
    DECLARE @ReturnValue VARCHAR(3)
    IF ((@UnitsInStock + @UnitsOnOrder) - @ReorderLevel) < 0
        SET @ReturnValue = 'Yes'
    ELSE
        SET @ReturnValue = 'No'
    RETURN @ReturnValue
END


Use Scalar UDF:

SELECT    ProductID,
      ReorderLevel,
      UnitsInStock,
      UnitsOnOrder,
      fnNeedToReorder(ReorderLevel, UnitsInStock, UnitsOnOrder) AS NeedToReorder
FROM    Products

another alternative to use of above function can be computed column in table. In products table we can create one computed column called as NeedToReorder as shown below

ALTER TABLE Products
ADD  NeedToReorder AS fnNeedToReorder(ReorderLevel,UnitsInStock, UnitsOnOrder)

Few practical use of functions:

1.  Format the phone number in desired format
2.  Format a date in standard format MM/DD/YYYY
3.  Number in particular format ex. you need 1 to 100 number like 001,002,003 .. 100 format.


Table Valued UDFs:

With these UDFs we can return either inline or multistatement tables, a rowset can be returned via the table Data Type. As I told earlier with table valued UDF two types are inline and multistatement table value returing UDFs. Inline Table returning UDF returns rowset via SLQ server table datatype. Inline table returning UDF are defined with a single SELECT statement making up the body of the function. Such UDFs cannot contain additional T-SQL logic outside of the SQL SELECT statement that defines the table it will return. It is easier to create inline table compared to multistatement table returning UDFs.

Create Inline Table Valued UDF:

CREATE FUNCTION Fn_GetEmpByCity (@City VARCHAR(30))
       RETURNS TABLE
AS
RETURN
    (
        SELECT    FirstName, LastName, Address
        FROM    Employees
        WHERE    City = @City
    )

Use of Inline UDF:

Select * from Fn_GetEmpByCity('Ganesh')

Thursday, March 14, 2013

Second Largest salary

Find Second Largest salary of the employee..



SELECT *FROM Employee E1WHERE (N-1) = (SELECT COUNT(DISTINCT(E2.Salary))FROM Employee E2WHERE E2.Salary > E1.Salary)

Friday, March 08, 2013

Team Foundation Server Control 2010 commands

Hi Dear all,
Here I am giving some TFS commands to performs few basic activities like add files / folders to Team Foundation Version Control, checkin etc.

Command:     TF help
Description:   For command line description.

Command:     TF msdn
Description:   For full documentation in Microsoft Document Explorer.


TFS Commands:

TF ADD        
Adds new files and folders from a local file system location to Team Foundation version control.

TF BRANCH     
Copies an item or set of items, including metadata and version control history, from one location to another on the Team Foundation version control server and in the local workspace.

TF BRANCHES  
Displays the history of a branch for a specified file or folder.

TF CHANGESET
Displays information about a changeset and lets you change the associated attributes, such as comments and check-in notes.

TF CHECKIN
Commits pending changes in the current workspace to Team Foundation version control.

TF CHECKOUT
Makes the local file writable and changes its pending Change status to "edit" in the workspace. Edit is an alias for the Checkout command.

TF CERTIFICATES 
Configures how client authentication certificates are used when connecting to TFS through a secure connection.

TF CONFIGURE  
Enables an administrator to view and change the following configuration settings for a team project in the Source Control Settings dialog box:
               - Check-out settings
               - Check-in policies
               - Check-in notes

TF DELETE
Removes files and folders from Team Foundation version control and deletes them from the disk.

TF DESTROY
Destroys, or permanently deletes, version-controlled files from Team Foundation version control.

TF DIFF       
Compares, and if it is possible, displays differences between two files, files in two folders, or a shelveset and a local or server file.

TF DIR        
Displays all or part of the contents of Team Foundation version control.

TF FOLDERDIFF 
Display a visual representation of the differences between files in two server folders, in a server folder and a local folder, or in two local folders.

TF GET
Retrieves a read-only copy of a file from Team Foundation Server to the workspace and creates folders on disk to contain it.

TF HELP       
Displays a help topic to the command-line that contains detailed information about a Team Foundation command.

TF HISTORY 
Displays the revision history for one or more files and folders.

TF LEBEL      
Attaches a label to or removes a label from a version of a file or folder in Team Foundation version control.

TF LABLES     
Displays the list of labels in Team Foundation version control.

TF LOCALVERSIONS 
Displays the version of one or more items in a workspace.

TF LOCK       
Locks or unlocks a file or folder to deny or restore the permissions of users to check out an item for edit into a different workspace or to check in pending changes to an item from a different workspace.

TF MERGE      
Applies changes from one branch into another.

TF MERGES     
Displays detailed information about past merges between the specified source and destination branches.

TF MSDN      
Launches the Microsoft Document Explorer to the documentation page for the command.

TF PERMISSION 
Modifies the user access control list (ACL) and displays authorization settings for an item under version control.

TF PROPERTIES 
Displays information about items under version control.

TF PROXY      
Configures the proxy setting automatically or manually. You can also use the proxy command to add, delete, and list proxy server records.

TF RENAME     
Changes the name or the path of a file or folder. You can use the rename command or the alias move, to move a file or folder to a new location.

TF RESOLVE    
Resolves conflicts between changed items in your workspace and the latest or destination versions of items on the server.

TF ROLLBACK   
Rolls back the changes in a single or a range of changesets.

TF SHELVE     
Stores a set of pending changes, together with pending check-in notes, a comment, and a list of associated work items in Team Foundation Server without actually checking them into the version control server.

TF SHELVESETS 
Displays information about a set of shelved changes.

TF STATUS 
Displays information about pending changes to items in one or more workspaces.

TF UNDELETE   
Restores items that were previously deleted.

TF UNDO
Removes pending changes from a workspace.

TF UNLABEL    
Removes an item from an existing label in Team Foundation version control.

TF UNSHELVE   
Restores shelved file revisions, check-in notes, comments, and work item associations to the current workspace or removes  an existing shelveset from the server.

TF VIEW       
Retrieves a specific version of a file to a temporary folder on your computer and displays it.

TF WORKFOLD   
Creates, modifies, or displays information about the mappings between your workspace folders and the Team Foundation version control folders.

TF WORKSPACE  
Creates, deletes, displays, or modifies properties and mappings associated with a workspace.

TF WORKSPACES 
Displays information about workspaces in the system and updates cached information about a user name or computer name change on Team Foundation Server.


Enjoy.....