Thursday 21 November 2013

Delegates And Events - C#



        In this article we are going to see the delegates and events in c#, A delegate is a class that holds the reference of method with the same signature.we can add many methods as a reference to the delegate. we can add or remove the signature reference.Finally we can execute all methods in sequence by reference.

A Event is a trigger raise by user interaction or action.The object that raises the event is a known as event sender.the object that captures the event and response back is known as event receiver.

In this following example we are going to execute a two method with same signature which accepts the int as input parameter. we are going to add four times Add method and remove one time. so add method is called two times.

once a time we uses the delegate and another time event to execute the methods.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatesSample
{
    class Program
    {
        public delegate void PrintOperation(int number);

        private event PrintOperation _printevent;
        public event PrintOperation PrintEvent
        {
            add
            {
                lock (this)
                {
                    _printevent += value;
                }
            }
            remove
            {
                lock (this)
                {
                    _printevent -= value;
                }
            }
        }

        static void Main(string[] args)
        {
            Program ka = new Program();
            Console.WriteLine("/* Delegate */");

            /* Using delegate to handle the methods */
            PrintOperation operation = new PrintOperation(ka.Square);
            operation += Add;
            operation += Add;
            operation += Add;
            operation -= Add;           
            operation(5);

            Console.WriteLine();
            Console.WriteLine("/* Event */");
            /* Using Event to handle the methods */           
            ka._printevent += ka.Square;
            ka._printevent += Add;
            ka._printevent += Add;
            ka._printevent += Add;
            ka._printevent -= Add;
            ka._printevent(5);

            Console.Read();
        }

        static void ka__printevent(int number)
        {
            throw new NotImplementedException();
        }

        void Square(int a)
        {
            a *= a;
            Console.WriteLine(" Time {1} : {0}", a, DateTime.Now.ToString());
        }

        static void Add(int a)
        {
            a += 2;
            Console.WriteLine(" Time {1} : {0}", a, DateTime.Now.ToString());
        }
    }
}


Output:
/* Delegate */
 Time 21-11-2013 23:28:33 : 25
 Time 21-11-2013 23:28:33 : 7
 Time 21-11-2013 23:28:33 : 7

/* Event */
 Time 21-11-2013 23:28:33 : 25
 Time 21-11-2013 23:28:33 : 7

 Time 21-11-2013 23:28:33 : 7


From this article you can find various ways of execute a multiple methods of same signature using delegate and events.

SQL SERVER - Notes 10


68. What is Change Tracking ?
       Change Tracking is used to track the changes takes place in the tables with in the database. to read about Change Tracking Click Here to read about Change Tracking

69. Create a User in SQL SERVER?
          Users can be created in Server level as well as database level. Now we see Steps to create the new user in server level.

1.     Right click the Security and click New and Select Login.
2.     Now a screen launches and select in General tab.
3.     Give the name for the Login Name
4.     Select Sql Server authentication and give password and new password.
5.     Uncheck the “user must change password at next login.”
6.     Select the Default Database from the database list.
7.     Now select the Server Roles from the left pane.

Server roles are the roles assign to the user to allow the user to do the actions in the server level based on the privileges,

Bulkadmin : allow user to execute the bulk insert statement in DB.
dbcreator : allow user to create the DB
diskadmin: allow user to do the manage disk files.
process admin: allow user to kill the process
public : every user is mapped to public user.
securityadmin : allow user to do the action of grant and deny permission
serveradmin: allow user to do the server wide configuration
setupadmin: allow user to do the setup like linked server
sysadmin: allow user to do all actions in server

8.     Now select the all list from the server roles
9.     Select the “User Mapping” from the left pane. In that we can map a user access to the database and schema.
10. Map the Database and see now and list of database role will seen under the map database panel.
11. Database Role Membership Which gives or specifies the roles to the user for that particular database

Public: this is the default role mapped to the user in db.
db_accessadmin: can able to add or remove access for windows login users.
db_backupoperator: can able to backup the db
db_datareader: can able to do read the data
db_datawriter: can able to do all add, delete and modify the data
db_ddladmin: can able to do all data definition language
db_owner: can able to do configuration and maintenance
db_denydatareader: can’t able to read data.
db_denydatawriter: can’t able to add,delete and modify data.
db_securityadmin: able to add role and manage permissions.


12. Now select the db_owner,db_datareader,db_datawriter,db_ddladmin, public
13. Now select the Securables  in the left pane and click search and add the object and give the give the permission on the list.
14. Now select the status in the left pane and select the Grant in the permission to connect to database engine and select enabled in login.

70. what are the various options of recovery model  ?
          Full, Bulk-logged, Simple
         
          Full : No work is lost, due to failure. It is default recovery model.
          Bulk-logged : Allows high-performance bulk copy operations. Minimum space    
                               is required , we can perform recovery when have taken the     
                                  backup of the database.
          Simple: Allows high-performance bulk copy operations,  we can perform  
                        recovery when we have taken the backup,advantage of using this is  
                        minimumspace requirement.


71. How to back-up database?

1.     Right click the database,Select Tasks in that select Back up database.
2.     Select the General in the left pane.
3.     Select the database to back up.
4.     Select a Back up type.
Full: Used for database , files, and filegroups.
Differential : Used for capture all data’s that has changed since the last full database backup.
Transaction log: Capture the modifications to the database, provide the history of the transaction takes place in the database.
Select the Full option.
5.     Select “Database” in back up component group.
6.     Give the name of the backup database.
7.     Select the Disk in the destination back up type and click ok.




I hope from this series of questions and explanation will give a basics and intermediate things in SQL SERVER. This articles make you to understand the about SQLSERVER.

Wednesday 20 November 2013

SQL SERVER - Notes 9

65. What is E-R Diagram ?
       An E-R Diagram is a graphical representation of  the inter relationship between the Entities in a database. Table is an Entity  ex: Employee table is an Entity

      An E-R Diagram Consists of an Following Elements.
      1. Entities      [Table   i.e Employee]  
      2. Attributes  [Columns i.e Employeeid,Name,Salary]
      3. Relationships [relationship between two tables]  , i.e three types One-One,One-Many,Many-Many

       One-One :  Person table - Passport table
       One - Many : Student - Subjects
       Many - Many : Customer - Order

66. What is Policy Based Management [PBM] ?
      Policy Based Management is a new feature in SQL Server 2008 that enables database administrators to  create and enforce policies to configure and manage SQL SERVER. A policy is a Rule that specifies a certain conditions to be evaluated against a managed Target.

       Following are the basic terms in PBM
      1. Managed Target
      2. Facet
      3. Condition
      4. Policy
      5. Policy Category
      6. Effective Policy

     Managed Target : A Managed Target is an Entity on which you want to apply policy. Ex Sql Server instance, Schema, Database etc.
     
     Facet :  Facet is set of properties that model the behavior and characteristics of a managed target.

    Condition : A condition is a one or more clauses that specify properties of a facet.
  
    Policy : A Policy contains the condition that specifies how to set the properties of the facet of a managed target.

    Policy Category : we can group the policy into different policy types known as policy categories.A policy can be belong to only one category. we can create policy categories at server level or database level.
   
    Effective Policy :  A Policy is considered to be effective policy if:
     1. Policy is Enabled
     2. The managed target belongs to the set of managed targets targeted by the policy.
     3. The managed target or one of its ancestors subscribes to the policy category that contains the policy.

67. How To CREATE Policy Based Management ?
      In Our example we are going to create a policy that function that create in db must be starts with name udf_.

       step 1. expand the Policy Based Management      
       step 2. Right click Condition and create a new condition
       step 3. specify the condition name and select facet as UserDefiendFunction as our sample 
       step 4: In the grid sepcify the Attribute 
                   Field : @Name
                   Operator: Like
                    Value : 'UDF_%'
      Step 5: click Ok.
      Step 6. Right Click the Policy and create a new Policy
      Step 7: Give a name for the policy and select the condition present in combo and select Evaluation                             Mode: Change:Prevent
      Step 8: Enable the Policy and Click Ok.



Sunday 17 November 2013

SQL SERVER - Notes 8


57.  What is valid xml and well formed xml?
  
            Well Formed XML: XML which adheres to the syntax rules.
            Valid XML: It is a well formed xml and which is validated against rules present in DTD

58.  Usage of Explicit XML?
            The output of the explicit mode contains all the information of the resulting XML tree. The FOR XML clause in EXPLICIT mode associates with every element, a tag number of the current element and tag number for parent element. This tag numbers are stored in separate columns, named Tag and Parent Respectively.

SELECT      1           AS Tag,
            NULL        AS Parent,
            id          AS [Employees!1!id],
            department AS [Employees!1!dept],
            name        AS[Employees!1]
FROM  employee
FOR XML EXPLICIT

Output:
            <Employees id="2" dept="Tech">DF</Employees>
<Employees id="3" dept="HR">Siv</Employees>
<Employees id="4" dept="BA">SS</Employees>
           
59.  What are the operators present in SQL Server?
o   Arithmetic Operators [+,-,*,/,%]
o   Logical Operators [ALL,AND,OR,ANY,BETWEEN,IN,EXISTS,LIKE]
o   Comparison Operators [=, <,>,>=, <=, <>,! =]
o   Assignment Operators [=]
o   Bitwise Operators [&, |,^]
o   Unary Operator [+,-,~]
o   Compound Operator [+=,*=,-=,/=,&=,^=,|=]

60.  What is the Data Integrity?
            Data Integrity means maintaining accurate, reliable and consistent data during any operation.
·         Entity Integrity
It ensures that each row in a table must be unique identified by an attribute, called primary key
·         Domain Integrity
It ensures that only a valid range of values is allowed to be stored in a column. It restricts the type of data, range of values and format of data.
·         Referential Integrity
It ensures that all the values in the foreign key match the values in primary key.
·         User-Defined Integrity
It enforces the data integrity on tables in two ways by defining constraints or by defining rules.

61.  Usage of GoTo statement?
            Goto statement causes the program control to unconditionally jump to the label specified in the GOTO statement.
           
DECLARE @i INT =1
WHILE(@i < 8)
BEGIN

      IF @i%4=0
      GOTO outofloop;
      ELSE
      GOTO Incr;

      Outofloop:
      BREAK;

      Incr:
      PRINT @i
      SELECT @i+=1

END

Output:
1
2
3

62.  What is ACID?
            ACID is an acronym of four important properties i.e Atomicity, Consistency, Isolation and Durability.
o   Atomicity
It ensures that any update occurs in the database, then either all or none of the transactions executed successfully.

o   Consistency
It ensures that any changes update in the database is consistent and logical after and before of the update committed successfully.

o   Isolation
It ensures that multiple transactions are executed simultaneously, Then each Transaction is isolated from each other till the transaction executed completely.

o   Durability
It ensures that the data will be restored when system crashes or power failure up to last committed successful transaction. Durability ensures that the data is permanent after updating.

63.  What is partition? How it is helpful in improving the performance?
            After index a table we can further optimize the performance of a table by partitioning the tables and indexes. Partitioning allows you to modify the data without affecting the integrity of the entire collection. Partition is the process of distributing the data of tables and indexes on separate filegroups.

       Need to perform the following task to create the partition
o   Create a Partition Function
o   Create File groups
o   Create a Partition Scheme
o   Create a Partition Table

-- Create a Partition Function [function takes one parameter as input]
CREATE PARTITION FUNCTION emp_partfunc(INT)
AS RANGE LEFT        --Left keyword specifies that vlaues one less than the specified
FOR VALUES(1980,1990,2000,2010)

-- Create a File group
RIGHT Click ON DATABASE
CLICK Properties AND SELECT FileGroups AND ADD four GROUP f1,f2,f3,f4

-- Create a Partition Scheme
CREATE PARTITION SCHEME emp_part_sch
AS PARTITION emp_partfunc
TO (f1,f2,f3,f4)

-- Create a partition table
CREATE TABLE employ(id INT IDENTITY(1,1), NAME VARCHAR(40),yearofjoin INT)
ON emp_part_sch(yearofjoin)

64.  Resource Governance
            SQL Server provides a new feature known as Resource Governor, which allows the database administrators to put a check on the server resources consumed by various connections or applications. It can control the CPU time and memory used by specific applications. It allows you to allocate the server resources to different types of connections. It category the incoming connections to different workloads groups, Each of which can be monitored individually. WorkLoad group are contained inside the resource pool which contains the portion of CPU and memory resources available to the current instance. It allows you to set importance for different workload groups.

o   Creating a Resource Pool
o   Creating a workload group
o   Creating a classifier function
o   Configure the Resource governor.

-- Create a Resource Pool
CREATE RESOURCE POOL reportpool
WITH (MAX_CPU_PERCENT = 50, MAX_MEMORY_PERCENT = 50)

-- Create a WorkLoad Group
CREATE WORKLOAD GROUP reportworkload
WITH (IMPORTANCE = HIGH)
USING samplepool

-- Create a Classifier Function
CREATE FUNCTION reportfunc()
RETURNS sysname
WITH schemabinding
AS
BEGIN

   DECLARE @wklgrp sysname
   IF(APP_NAME()= 'Report application')
   SET @wklgrp = 'reportworkload'
   ELSE
   RETURN default
  
   RETURN @wklgrp
END

-- Classifier the Resource Governer
ALTER RESOURCE GOVERNOR
WITH ( CLASSIFIER_FUNCTION = dbo.reportfunc)
GO

ALTER RESOURCE GOVERNOR RECONFIGURE

GO