Wednesday, 21 March 2018

Triggers -- SQL Server

A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server.

DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected.

DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations. 

Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE.

Basically, triggers are classified into two main types:
  1. After Triggers (For Triggers)
  2. Instead Of Triggers
(i) After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

AFTER INSERT Trigger
AFTER UPDATE Trigger
AFTER DELETE Trigger

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers.
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit trigger.

Now, create the audit table as:
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) After Insert Trigger
This trigger is fired after an INSERT on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 set @audit_action='Inserted Record -- After Insert Trigger.';

 insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER INSERT trigger fired.'
GO

The CREATE TRIGGER statement is used to create the trigger. The ON clause specifies the table name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the same.

In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values into the Audit table.
To see the newly created trigger in action, let's insert a row into the main table as:
insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:


Continue Reading →

Temporary Tables - SQL Server

SQL Server Temporary tables are a special type of tables that are written to the TempDB database and act like regular tables.

There are four main types for the temporary tables;
  • Local Temporary table, which is named starting with a # symbol (e.g. #TempShipments), that can be referenced only by the current database session and discarded by its disconnection,
  • a Global Temporary table, which is named starting with ## (e.g. ##TempShipments), that can be referenced by any process in the current database and discarded when the original database session that created that temp table disconnected or until the last statement that was referencing the temp table has stopped using it, as anyone who has access to the system TempDB database when that global temporary table is created will be able to use that table,
Both temporary tables and table variables are stored in the TempDB database, but there are many differences between them such as:
  • Temporary tables are created using CREATE TABLE T-SQL statement, but table variables are created using DECLARE @name Table T-SQL statement.
  • You can ALTER the temporary tables after creating it, but table variables don’t support any DDL statement like ALTER statement.
  • Temporary tables can’t be used in User Defined Functions, but table variables can be.
  • Temporary tables honor explicit transactions defined by the user, but table variables can’t participate in such transactions.
  • Temporary tables support adding clustered and non-clustered indexes after the temporary table creation and implicitly by defining Primary key constraint or Unique Key constraint during the tables creation, but table variables support only adding such indexes implicitly by defining Primary key constraint or Unique key constraint during tables creation.
  • Temporary tables can be dropped explicitly, but table variables can’t be dropped explicitly, taking into consideration that both types are dropped automatically when the session in which they are created is disconnected.
  • Temporary tables can be local temporal tables at the level of the batch or stored procedure in which the table declared or global temporal tables where it can be called outside the batch or stored procedure scope, but table variables can be called only within the batch or stored procedure in which it is declared.

Continue Reading →

Table-Valued Parameters - SQL Server

Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

Restrictions
Table-valued parameters have the following restrictions:
  1. SQL Server does not maintain statistics on columns of table-valued parameters.
  2. Table-valued parameters must be passed as input READONLY parameters to Transact-SQL routines. You cannot perform DML operations such as UPDATE, DELETE, or INSERT on a table-valued parameter in the body of a routine.
  3. You cannot use a table-valued parameter as target of a SELECT INTO or INSERT EXEC statement. A table-valued parameter can be in the FROM clause of SELECT INTO or in the INSERT EXEC string or stored procedure. Table-valued parameters perform well for inserting less than 1000 rows.
Example
The following example uses Transact-SQL and shows you how to create a table-valued parameter type, declare a variable to reference it, fill the parameter list, and then pass the values to a stored procedure.
USE AdventureWorks2012;  
GO  

/* Create a table type. */  
CREATE TYPE LocationTableType AS TABLE   
( LocationName VARCHAR(50)  
, CostRate INT );  
GO  

/* Create a procedure to receive data for the table-valued parameter. */  
CREATE PROCEDURE dbo. usp_InsertProductionLocation  
    @TVP LocationTableType READONLY  
    AS   
    SET NOCOUNT ON  
    INSERT INTO AdventureWorks2012.Production.Location  
           (Name  
           ,CostRate  
           ,Availability  
           ,ModifiedDate)  
        SELECT *, 0, GETDATE()  
        FROM  @TVP;  
        GO  

/* Declare a variable that references the type. */  
DECLARE @LocationTVP AS LocationTableType;  

/* Add data to the table variable. */  
INSERT INTO @LocationTVP (LocationName, CostRate)  
    SELECT Name, 0.00  
    FROM AdventureWorks2012.Person.StateProvince;  

/* Pass the table variable data to a stored procedure. */  
EXEC usp_InsertProductionLocation @LocationTVP;  
GO  


Continue Reading →

Exception Handling in SQL Server

Exception Handling in SQL Server
SQL Server provides TRY, CATCH blocks for exception handling. 

BEGIN TRY

/* T-SQL Statements */

END TRY
BEGIN CATCH


- Print Error OR
- Rollback Transaction

END CATCH 

Types of Exceptions

SQL Server contains the following two types of exceptions:
1- System Defined
2- User Defined

System Defined Exception
In a System Defined Exception the exceptions (errors) are generated by the system.

  1. Declare @val1 int;  
  2. Declare @val2 int;  
  3. BEGIN TRY  
  4. Set @val1=8;  
  5. Set @val2=@val1/0; /* Error Occur Here */  
  6. END TRY  
  7. BEGIN CATCH  
  8. Print 'Error Occur that is:'  
  9. Print Error_Message()  
  10. END CATCH  

Output
Error Occur that is:
Divide by zero error encountered

User Defined Exception
This type of exception is user generated, not system generated.

  1. Declare @val1 int;  
  2. Declare @val2 int;  
  3. BEGIN TRY  
  4. Set @val1=8;  
  5. Set @val2=@val1%2;   
  6. if @val1=1  
  7. Print ' Error Not Occur'  
  8. else  
  9. Begin  
  10. Print 'Error Occur';  
  11. Throw 60000,'Number Is Even',5  
  12. End  
  13.   
  14. END TRY  
  15. BEGIN CATCH  
  16. Print 'Error Occur that is:'  
  17. Print Error_Message()  
  18. END CATCH  

Output
Error Occur
Error Occur that is:
Number Is Even

Here 60000 denotes the error number and 5 denotes the state to associate with the message.

The following are system functions and the keyword used within a catch block:

@@ERROR
ERROR_NUMBER()
ERROR_STATE()
ERROR_LINE()
ERROR_MESSAGE()
ERROR_PROCEDURE()
ERROR_SEVERITY()
RAISERROR()
GOTO()
Continue Reading →

Sunday, 18 March 2018

Properties - C#

Properties are special kind of class member, In Properties we use predefined Set or Get method.They use accessors through which we can read, written or change the values of the private fields.

For example, let us Take a class named Employee, with private fields for name,age and Employee Id. We cannot access these fields from outside the class , but we can accessing these private fields Through properties.

Why We use properties
Marking the class field public & exposing is a risky, as you will not have control what gets assigned & returned.

To understand this clearly with an example lets take a student class who have ID, pass mark , name.Now in this example some problem with public field
  1. ID should not be -ve.
  2. Name can not be set to null
  3. Pass mark should be read only.
  4. If student name is missing No Name should be return.
To remove this problem We use Get and set method.
// A simple example
public class student
{
public int ID;
public int passmark;
public string name;
public class programme
{
    public static void main()
    {
       student s1 = new student();
       s1.ID = -101; // here ID can't be -ve
       s1.Name = null ; // here Name can't be null
    }
}

Now we take an example of get and set method

public class student
{
    private int _ID;
    private int _passmark;
    private string_name ;
    // for id property
   public void SetID(int ID)
   {
       if(ID<=0)
       {
         throw new exception("student ID should be greater then 0");
       }
       this._ID = ID;
    }
    public int getID()
    {
       return_ID;
     }
   }
   public class programme
   {
       public static void main()
       {
         student s1 = new student ();
         s1.SetID(101);
      }
      // Like this we also can use for Name property
      public void SetName(string Name)
      {
        if(string.IsNullOrEmpty(Name))
        {
          throw new exeception("name can not be null");
        }
        this._Name = Name;
     }
     public string GetName()
     {
        ifstring.IsNullOrEmpty(This.Name))
        {
          return "No Name";
       }
       else
      {
        return this._name;
      }
      // Like this we also can use for Passmark property
      public int Getpassmark()
      {
        return this._passmark;
      }
}
Continue Reading →

What is NodeJS

Node.js is a server-side environment that allows Node developers to build servers and network applications with JavaScript for the first time. This means entire sites can be run on a unified JavaScript stack—both the client-side software, and the server-side software.
Technically, it’s a development platform, not a framework—with numerous frameworks that run on top of it. It’s also a runtime environment, a component of a development platform that allows developers to test a software program while it’s running—simulating how the program will behave once it’s been executed, so any bugs or errors can be tracked and fixed. Node.js runs a programming construct called an “event loop,” which waits for client requests then sends them to the server or database. It’s best to think of Node.js as less of a full-fledged server, and more of a foundation upon which you can easily add libraries and workhorse connectors like HTTP, SSL, and TCP to quickly set up a working dynamic web server—all with only a few lines of JavaScript.
  • It’s the N in the MEAN software stack. Software stacks are bundles of all the necessary components needed to build sites that are proven to work well together, so they’re dubbed “a stack.” They include: an OS, a database, a server, and a programming language. The MEAN software stack is a JavaScript-powered stack: MongoDBExpress.js, AngularJS, and Node.js.
  • It’s open source and cross-platform.
  • It’s an asynchronous, non-blocking, event-driven I/O system. In other words, your application doesn’t have to wait around for an initial operation to complete before it can respond to another event. It can instead queue callbacks in the event loop in the order it receives them, and perform other processes before the initial transmission has finished. Because it brings JavaScript’s asynchronous method to back-end programming, it takes calls separately from one another, on an individual basis, which makes it excellent with handling cascading calls made through multiple APIs—things that could slow down traditional back-end programming with languages like PHP.
  • It’s built on Chrome’s JavaScript virtual machine, V8. V8 is Google’s JavaScript engine and is responsible for executing Node’s code.
WHAT IS NODE.JS USED TO BUILD?
JavaScript programmers can use Node.js to build real-time web APIs, network programs (like servers), and real-time, moderately data-intensive applications. It builds fast server applications in an event-driven model that achieves concurrency without the hassle of managing application state across multiple threads (i.e., avoid deadlocking processes).
On the other hand, it’s important to remember that the single-thread, multi-process approach can run into a different bottleneck at higher per request latencies (greater than 2,000 simultaneous requests a second)—the speed difference between IPC (interprocess communication) used by Node.js and communication between multiple threads becomes more noticeable. For truly data-intensive, real-time applications, you may want to choose a database system based on a language that better optimizes threading, like Java.
The popularity, ease-of-use, and speed of Node.js is perfect for most general web server applications, especially in situations where the speed with which you can add a new feature trumps the need to squeeze out additional performance from an application that is already fast enough to meet your needs. This leads to fast, efficient server programs that aren’t slowed down by traditional bottlenecks.
Added bonus: Web servers or network servers built by Node.js are written in JavaScript, making them naturally compatible with browser-based JavaScript. As a result, everything works in harmony.
THE EXPRESS.JS FRAMEWORK & THE KOA.JS FRAMEWORK
Node.js builds server apps with a lightweight, efficient JavaScript framework called Express.js. There are other frameworks it’s compatible with, but Express.js is best known as another quarter of the MEAN software stack. Newer to the scene and following in Express’ footsteps is the Koa.js framework, a callback-less lightweight framework written by the same author as Express. Get a rundown of more Node frameworks in this 15 Frameworks to Know for Next-Level Node Development article.
SO, WHAT MAKES NODE.JS SO EXCELLENT (AND EFFICIENT) FOR BACK-END PROGRAMMING?
Two words—programmer productivity. While other server-side technologies have their own means of creating dynamic, asynchronous web servers, Node.js is simply easier to use. At a glance, it’s similar to back-end platforms powered by PHP, Java, and Python, but Node.js solves for speed issues in a few key ways that result in less programming overhead for the developer. A few sites that use Node.js include: PayPal, LinkedIn, Groupon, Walmart, Yahoo!, Intuit, and Voxer. Here’s a quick look at six of its advantages:
  1. What makes JavaScript fast makes Node.js fast. That’s a broad way of looking at things, but essentially, Node.js is harnessing the speed and power of JavaScript. And because JavaScript is everywhere on the front end, migrating it over to the back end means a more fluid stack right off the bat. Node.js servers work in lockstep with JavaScript, have excellent JavaScript libraries built in, and make life easy for developers who can now work on both front- and back-end programming without having to shift gears. Everything that makes JavaScript fast is driving Node.js—and it all comes down to browser compatibility, the use of JSON, and the event-loop model of handling requests.
  2. It’s cross-platform. JavaScript works on nearly every OS, because it was born in the browser and had to be compatible. It’s lent this flexibility to Node.js. It runs on OS X, Windows, Linux, FreeBSD, and more.
  3. Event-driven programming. Node.js has made event-driven programming possible on the server-side—bringing vast improvements to server speed. The event loop paradigm synergizes perfectly with the way web browsers work. In the same way that JavaScript is designed to internally handle an event loop, Node.js can snap requests onto the event loop and process them, effectively achieving concurrency without having to assign additional threads. It’s similar to (but more straightforward than) Ruby’s EventMachine or Python’s Twisted event-processing engines—eliminating concurrency issues that sometimes slow down server-side applications.And, because Node.js works asynchronously, similar to AJAX, it handles server connections on an event-driven basis only. Calls are addressed individually, at the same time, but separate from one another—and Node.js will go to sleep in the absence of events. That means less waiting, bottlenecks, and no overloads.
  4. The V8 virtual machine. The engine powering Node.js is Google’s Chrome JavaScript runtime, the V8 virtual machine. It’s incredibly fast and compiles JavaScript code into “machine code”—a language readable by whatever hardware or operating system it’s being run on. Used by companies like Walmart to build APIs, and written in C++, the V8 virtual machine is the main reason it can boast so much speed.
  5. JSON has done for Node.js what it did for JavaScript. JSON is an incredibly simple, fast text format used to describe and transfer data. JSON and JavaScript go hand in hand, and have contributed to the strength of one another—and Node.js capitalizes on that. JSON also led to the rise of document-oriented NoSQL databases like MongoDB—one fourth of the Node.js-powered MEAN software stack.
  6. Like AJAX, Node.js only wakes up for a “callback.” This is a whole different approach, now applied to server-side applications. The parallel connections mentioned above trigger what’s known as a “callback”—between callbacks, Node.js goes into hibernation. This event model is borrowing from JavaScript’s browser behavior in this way—there’s no threading, and no waiting for a loop to close to initiate a new connection.
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives