X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Thursday, June 26, 2014

Sql server context_info trigger

What is Trigger ?
A trigger is a database object that is attached to a table or we can define trigger as a stored procedure that automatically executes when an event occurs in the database server.
Triggers are classified into two types mainly-
  • Instead of Trigger
  • After Trigger
How can i access the tables in Triggers
When we update a record on the table where trigger is created, the magic tables “INSERTED” and “DELETED” both will be created, the Old data of the updating record will be available in “DELETED” table and, the new data will be available in “INSERTED” table, while accessing them inside the trigger. These tables are called magic tables of the SQL Server. We can not see these tables in the data base. But we can access these tables from the trigger.
How can i pass the value to Trigger ?
So now we are coming to the point where i need to send the data to trigger. So in case tables “INSERTED” and “DELETED” does not hold the data, and you still need to pass the data from either from parameters of stored procedure or from some variables which are evaluated in stored procedure then you are in right place :-)
Here i am creating the Test tables which are required for the demo. Below is the screenshot of the tables which are added newly in my “Testing” Database.
Sql server context_info trigger











Now the intension would be to insert a record in table “DataCheck” when some record is inserted in to table “Test“. So that means i am creating a trigger on table “Test” to insert the record in table “DataCheck“.
As you can see table “Test” has columns – ID, NAME
and table “DataCheck” has columns – UserID and Name.
So now lets create a trigger on table “Test“ -
CREATE TRIGGER USP_TR_Test ON dbo.Test
FOR INSERT
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE 
  @commaseparatedStr VARCHAR(200),
  @useridStr VARCHAR(200),
  @nameStr VARCHAR(200)


 SELECT @commaseparatedStr = CAST(CONTEXT_INFO() AS VARCHAR)
 FROM master.dbo.SYSPROCESSES
 WHERE SPID = @@SPID

 SELECT 
  @useridStr = substring(@commaseparatedStr,1,CHARINDEX(',',@commaseparatedStr)- 1),
  @nameStr = substring(@commaseparatedStr,CHARINDEX(',',@commaseparatedStr) + 1, len(@commaseparatedStr) - 1)


 INSERT INTO DataCheck (
  NAME
  ,UserID
 )
 SELECT 
  SUBSTRING(@namestr,CHARINDEX('=',@namestr) + 1, len(@namestr) - 1),
  CAST(SUBSTRING(@useridstr,CHARINDEX('=',@useridstr) + 1, len(@useridstr) - 1) AS INT)
END
GO

So basically it inserts data into table “DataCheck“.
Now lets create a stored procedure which inserts data into table “Test” and calls up trigger on the same table.
CREATE PROCEDURE USP_RP_InsertToTest 
(
 @intUserID INT, 
 @name VARCHAR(50)
)
AS
BEGIN
 SET NOCOUNT ON;

 DECLARE @CONTEXT_INFO VARBINARY(128)

 SET @CONTEXT_INFO = CAST('UserID=' + CONVERT(VARCHAR(10), @intUserID) + ',' + 'Name =' + @name AS VARBINARY(128))
 SET CONTEXT_INFO @CONTEXT_INFO

 INSERT INTO Test (NAME)
 VALUES (@name)
END
GO

Here we are using keyword called “CONTEXT_INFO” so this is used to retrieve the context information for the current session and session context information is also stored in the context_info columns.
So “SET CONTEXT_INFO variablename” is used to set the context info.
In the trigger if you observe i am using “CONTEXT_INFO()” to fetch the data from context info and insert into “DataCheck“.
Note that the data i am setting to context info is coming as parameters in stored procedures.
Now you just execute the stored procedure created above like this –
Sql server context_info trigger


and observe that in table “DataCheck” one record is inserted -
Sql server context_info trigger



Hope it helped.


Sunday, June 22, 2014

Who has Viewed my Facebook Profile !!

Everybody will be excited to check who viewed their “Facebook” profile. Now there are many third party softwares available for doing the same but here i am going to explain a simple trick.

Step - 1
Go to your Timeline and Right Click + Select View page source option as shown in the below image -
























Step - 2 Search for the keyword “InitialChatFriendsList” in the view source page as shown in the below image 












The numbers which immediately follow after keyword "List" are the identification numbers of the profiles of your friends. You will see a list of numbers, each set of numbers delimited by commas and you can observe that each number has either “-0″, “-2″, or “-3″ at the tail end. Copy only the string without "" and the "final number". Paste this after the “Facebook.com” when looking at the main Facebook page. This will bring up the profile so you know who it belongs to.  
So URL to find the friend will be like this - "Facebook.com/Number"

Hope it helps.


Thursday, June 19, 2014

Linq and lambda expressions in c#

Introduction

LINQ or Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
LINQ simplifes and reduces the code with neat and effective way. It provides an easy way to write queries that can run with the in-memory objects.
Linq is always associated with Lambda Expressions. in .NET 2.0 we had the concept of Annonymous Methods that allows you to write function body inline without the need of writing a delegate function. So In .Net 3.5 Lambda Expressions are used for the same purpose.
Linq and lambda expressions in c#
Types of LINQ
There are basically 3 types they are -
1. LINQ (Linq to Objects)
2. DLINQ (Linq to SQL)
3. XLINQ (Linq to XML)
How to use
So you will be thinking now in which scenarios i can use it. Here i am going to explain few scenarios where LINQ simplifies the process.
Following are some of the scenarios where we can use LINQ or Lambda expressions -
1) DataTable to List of Objects
Add one method to get the data table for our testing purpose. Since i love to use MVC i will create an MVC application but you can create webform as well.
 private DataTable GetDataTable()
  {
      DataTable dt = new DataTable();
      dt.Columns.Add("ID", typeof(int));
      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Gender", typeof(string));

      DataRow dr1 = dt.NewRow();
      dr1["ID"] = 1;
      dr1["Name"] = "aa";
      dr1["Gender"] = "M";

      DataRow dr2 = dt.NewRow();
      dr2["ID"] = 2;
      dr2["Name"] = "bb";
      dr2["Gender"] = "M";

      DataRow dr3 = dt.NewRow();
      dr3["ID"] = 3;
      dr3["Name"] = "cc";
      dr3["Gender"] = "F";

      dt.Rows.Add(dr1);
      dt.Rows.Add(dr2);
      dt.Rows.Add(dr3);
      
      return dt;
  }



Now i will create one class which same properties as Datatable columns. I will call it as “Employee”.
public int ID { get; set; }

public string Name { get; set; }
        
public string Gender { get; set; }

I will add one more method which uses the DataTable and converts into List of Employees using Reflection -
private IList ConvertToList(DataTable dt)
 {

   var columns = dt.Columns.Cast()
                .Select(c => c.ColumnName)
                .ToList();
    
    var props = typeof(T).GetProperties();
       return dt.AsEnumerable().Select(row =>
       {
          var objT = Activator.CreateInstance();
          foreach (var pro in props)
          {
               if (columns.Contains(pro.Name))
               {
                    if (row[pro.Name] != DBNull.Value)
                    {
                        pro.SetValue(objT, row[pro.Name], null);
                    }
                    else
                    {
                        pro.SetValue(objT, null, null);
                    }
                }
           }
    
        return objT;
    }).ToList();
            
 }

So Call the method like this -
DataTable dt = GetDataTable();
List employees = ConvertToList(dt).ToList();

2) Get DISTINCT List of Objects
Now lets see how we can get distinct records of employees based on employee name using LINQ.

//Get Distinct Employees
List distinctItems = employees.GroupBy(a => a.Name).Select(b => b.First()).ToList();

3) Check value exists in List of Objects
Below is the query to check the value exists in List of Objects or not. If it exists then it will return "true" else "false".

//Check for Employee Name in List of Employees
bool isRes = employees.Any(w => w.Name.Contains("er"));

Hope this helps.

Thank You.


Sunday, June 15, 2014

MVC Route Debugger – GLIMPSE

As we all know MVC pattern purely relies on Routing. In ASP.NET MVC routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string. So here i am not elaborating much on MVC pattern and Routing mechanism. So this post is written mainly concentrating on the mvc routing debugger.
I know there are lot of people loving to code in MVC. But there are lot of people like me who struggled a lot in the MVC Routing, who are not able to find which method is being called on client request.
To overcome this there are lots of tools came in the market to ease the debugging the routing part. So here i am going to explain the debugger called “Glimpse”, which is used by majority of the people to debug their routing needs.
So what is Glimpse ?
Glimpse is like the FireBug client side debugger, except it’s implemented in JavaScript on the client side with hooks in to ASP.NET on the Server Side.
How i can use it in my Visual Studio Project ?
So here i am going to explain you the steps to use “Glimpse” in your project -
Open your Visual Studio -> Click on New Project -> Click on Web -> Select ASP.NET MVC4 Web Application

MVC Route Debugger – GLIMPSE















Click on Tools -> Nuget Package Manager -> Package Manager Console -> Install-Package Glimpse


MVC Route Debugger – GLIMPSE



and Install Glimpse for MVC4 using command -> Install-Package Glimpse.MVC4
You can observe the change in your web.config, it adds the few lines which are relevant to glimpse.

Now, I will run my app. I can turn Glimpse on like visiting http://localhost:portname//glimpse.axd and click on button “Turn Glimpse On”

You can see the below toolbar at the bottom of the screen -
MVC Route Debugger – GLIMPSE





In the above screenshot you can check the request details, method called in server, time taken to get the response etc. which i feel is boon to all developers to track the code and debug. 
This article is just for overview of it you can check more on - http://www.getglimpse.com


Monday, June 9, 2014

Identity_insert is set to off in sql

How many times you might came across this issue -
“An explicit value for the identity column in table ‘***’ can only be specified when a column list is used and IDENTITY_INSERT is ON.”
I would say its common issue which occurs when we are trying to insert the value to “IDENTITY” column in a table.
Lets look at why this issue comes up and what it means -
First what you mean by IDENTITY column -> These are commonly used as primary keys in our database tables.
How this issue comes up ?
Ok to answer this question lets create a sample table in our SQL Server -
Identity_insert is set to off in sql







Error thrown – "An explicit value for the identity column in table ‘Test’ can only be specified when a column list is used and IDENTITY_INSERT is ON."
Lets solve it now -
Identity_insert is set to off in sql






Execute this now. Worked !!!!
Simple isn’t it.
Hope its helpful too.

Sunday, June 8, 2014

DataContracts are not generated in Client side after adding Service Reference !!

Hi All,
Back to boring WCF but this time with a different issue :-):-)
This time my client wanted to have an smart client application using .NET technology. So here is my list of layers created for this project -
1) DataAccess Layer – Contains my Classes with DataContracts and library references which are used to connect to my SQL database.
2) Service Layer – which is used for calling the methods which are in DataAccess Layer. We have used WCF service with SOAP in this case.
3) Client Library – which takes the reference of the service and calls up the methods in service layer.
After giving an reference of the WCF service to my client library i was not getting the classes generated in the client side.
I made sure that i have added “DataContract” and “DataMember” attributes are added on my Class and Property level respectively.
1 full day i was scratching my head but of no use :-):-)
Next day some forum answers provoked me to find the root cause of it. I got following answers in forums -
1. Try remove the entire service reference and add again, instead of update.
2. Please check if project settings are same – like – platform, framework and other settings are same – any assembly keys you are using?
3. Also check if there are any predefined assembly references are missing on your destination project.
So finally i found the solution – That was because My Service Library was in Framework 4.5 and my Client Library was in Framework 3.5.
So after changing my Service Library to Framework 3.5 it solved the issue.
Note : In my case client wanted the client library to be in Framework 3.5 so i changed my Service Library to Framework 3.5. You can do it vice versa too. (Client and Service libraries to be in framework 4.5)
Other reason also i found by googling is “If DataContracts are not been used in any of your Service Methods
(Operation Contracts) then also you would not get that in Client side”.
In my case DataContract was of type class. Same thing is true for other types like structures, or enumerations too.
Hope this is helpful to others.

Change base address wcf

Wow !!! today i had first vision towards WCF technology its seems to be very interesting. I was scratching my head from last 2 hours and got the solution and by seeing the solution i myself got ashamed…..

The funny thing started from here -


Change base address wcf
















Here I am trying to create a new WCF project and here I have the options
1)      WcfServiceLibrary
2)      WcfService Application
3)      Wcf Workflow Service Application
4)      Syndication Service Library
I am choosing “WcfServiceLibrary” because I wanted a dll to be created and I am hosting WCF in self-hosting method.
Now look at the app.config which is been created by default,
Change base address wcf














This is the config file generated and the default base address generated is
 Which is using Http binding, Now suppose I want to change the base address to
I tried this but I was getting this error
“Please try changing the HTTP port to 8732 or running as Administrator.”
Then after googling this I got some links which could help me to resolve this issue and finally it got solved by running visual studio in Administrator mode.
Change base address wcf

Running as administrator will allow you to run the service on any port.
After doing this automatically everything  worked !!!!
Isn’t  that funny.. yes it is….


Hope it helps…..