Friday 14 December 2012

Performance of CTE(Common table expression) Vs Hash(#)Tables.


Let say we have one report and in which we want data from around 20 tables.

so i just created some 4 to 5 cte(Common table expression) for every 4 to 5 tables.

and then join cte's and get the data.but when i execute that stored procedure it will take around 10 Minutes.

i am really strange about this.

Now what i do just replace all cte(Common table expression) with Hash(#)table.

and it's executed with only around 15 seconds.

So i suggest when cte 1 or 2 then ok but 4 to 5 then you can use #tables.

This is work for me.Let's you guys try it.if you use cte and it will take too much time to execute.

Friday 7 December 2012

Bind WebGrid in Asp.net MVC


I just learn how to bind grid in MVC. I hope you guys just know basic about MVC.
First of all You guys just have to install one package.for that got to Tools->Library Package Manager
and run command in output window
Command:- Install-Package RazorGenerator.Templating

1.) Below is controller code.
in above code i just create simple List of my model.you can also get that list from database also.

2.) Below is model code.


in above code simple properties are created.

3.) Below is view code.







Here is your view code. here one thing is that you have to take care is that is first line.i tried with @model MvcApplication1.Models.NiksModel but it means it accept model from controller.but here we are passing list from controller so you just have defined as list of your model.

Reference:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=618


Wednesday 28 November 2012

View Last Excuted Quries in Sql Server


View Last Excuted Quries in Sql Server
SELECT DEQS.LAST_EXECUTION_TIME AS [TIME]
,SUBSTRING(DEST.TEXT,(DEQS.STATEMENT_START_OFFSET/2)+1
,((CASE DEQS.STATEMENT_END_OFFSET WHEN -1 THEN DATALENGTH(DEST.TEXT)ELSE DEQS.STATEMENT_END_OFFSET
END - DEQS.STATEMENT_START_OFFSET)/2) + 1) AS STATEMENT_TEXT
,DEST.*
FROM SYS.DM_EXEC_QUERY_STATS AS DEQS
CROSS APPLY SYS.DM_EXEC_SQL_TEXT(DEQS.SQL_HANDLE) AS DEST
ORDER BY DEQS.LAST_EXECUTION_TIME DESC

Thursday 24 May 2012

Comma seperated records in sql without loop or cursor

SELECT STUFF
(
(

SELECT ',' + T1.FULLNAME AS [text()]

FROM DBO.TABLE_1 AS T1

INNER JOIN DBO.TABLE_2 AS T2 ON T1.ID = T2.ID

FOR XML PATH('')
)
,1,1,''
)


DECLARE @COLS NVARCHAR(2000)

SELECT @COLS = COALESCE(@COLS + ',[' + CONVERT(NVARCHAR(100),T1.FULLNAME ) + ']','[' + CONVERT(NVARCHAR(100),T1.FULLNAME) + ']')

FROM DBO.TABLE_1 AS T1

INNER JOIN DBO.TABLE_2 AS T2 ON T1.ID = T2.ID

Friday 11 November 2011

Insert and update data Using Xml file in Sql Server

'Making Xml 
 Dim sb As New System.Text.StringBuilder
sb.Append("")
For i = 0 To dt.Rows.Count - 1
sb.Append(" sb.Append("PQty=""" & dt.Rows(i).Item("PQty") & """")
sb.Append("PWeight=""" & ClearWhiteSpace(dt.Rows(i).Item("PWeight")) & """")
sb.Append("/>")
Next
sb.Append("
")
-- Making Stored Procedure
CREATE PROCEDURE [dbo].[TestMasterInsert]    
    @MId Int,    
    @GId Int,
    @PId Int,
    @Name varchar(50),
    @Data text,
    @TranType  Char(1)
AS
BEGIN    
    SET NOCOUNT ON;    
    
    Declare @id As Int 
        SET @id = 0
        
        DECLARE @hDoc int exec sp_xml_preparedocument @hDoc OUTPUT, @Data
        
    IF @TranType = 'I'    
        BEGIN        
            Insert Into TestMaster Values (@GId,@PId,@Name)
        
            Select @id = SCOPE_IDENTITY()  
        
            INSERT INTO TestDetail
                SELECT @id,PQty,PWeight
                FROM   OPENXML (@hDoc, '/ROOT/SI',2)          
                WITH (
                       PQty       Decimal(18,3) '@PQty',
                       PWeight    Decimal(18,3) '@PWeight'
                     )   
          
             EXEC sp_xml_removedocument @hDoc
        END
    ELSE IF @TranType = 'U'        
        BEGIN
            
            UPDATE TestDetail     
            SET     
                  TestDetail.PQty = XMLTEST.PQty,    
                  TestDetail.PWeight = XMLTEST.PWeight
            FROM OPENXML(@hDoc, '/ROOT/SI',2)
                        WITH (DId Int '@DId',PQty Decimal(18,3) '@PQty',PWeight Decimal(18,3) '@PWeight') XMLTEST
            WHERE  TestDetail.DId = XMLTEST.DId
            
            EXEC sp_xml_removedocument @hDoc        
        END    
END

Friday 4 November 2011


Imports System.ServiceProcess
Imports System.IO
Public Class Service1
    Inherits System.ServiceProcess.ServiceBase
    Public Shared DailyTime As String = "DailyTime.txt"
    Public Shared errlogfile As String = "Error.err"


    Protected Overrides Sub OnStart(ByVal args() As String)
        Try


        Catch ex As Exception
            [Error]("OnStart:-" + ex.Message + DateTime.Now.ToString())
        End Try
    End Sub


    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub


    Protected Overrides Sub OnSessionChange(ByVal changeDescription As SessionChangeDescription)
        Try


            Select Case changeDescription.Reason
                Case SessionChangeReason.SessionLogon


                    [InsertDailyTime]("Session Logon:-" + DateTime.Now.ToString())


                    Exit Select
                Case SessionChangeReason.SessionLogoff
                    [InsertDailyTime]("Session Logoff:-" + DateTime.Now.ToString())
                    Exit Select
                Case SessionChangeReason.RemoteConnect
                    'Remote Connect 
                    Exit Select
                Case SessionChangeReason.RemoteDisconnect
                    'Remote Disconnect 
                    Exit Select
                Case SessionChangeReason.SessionLock
                    [InsertDailyTime]("Session Lock:-" + DateTime.Now.ToString())
                    Exit Select
                Case SessionChangeReason.SessionUnlock
                    [InsertDailyTime]("Session Unlock:-" + DateTime.Now.ToString())
                    Exit Select
                Case Else
                    Exit Select
            End Select


        Catch ex As Exception
            [Error]("OnSessionChange:-" + ex.Message + DateTime.Now.ToString())
        End Try
    End Sub


    Public Shared Sub [InsertDailyTime](ByVal message As String)
        Dim datewisefile As String = ""
        Dim dt As DateTime = DateTime.Now
        Dim fs As System.IO.FileStream = Nothing
        Dim info As Byte() = Nothing
        Try
            If Not System.IO.Directory.Exists(Path.GetDirectoryName("D:\Projects\TimeManager")) Then
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName("D:\Projects\TimeManager"))
            End If
            'logfile = logfile.Split('.')[0] + System.DateTime.Now.ToString("yyyyMMddHHmm") + '.' + logfile.Split('.')[1]; 
            datewisefile = ((dt.Year & "") + "-" + (If(dt.Month <= 9, "0" & dt.Month & "", dt.Month & "")) & "") + "-" + (If(dt.Day <= 9, "0" & dt.Day & "", dt.Day & ""))
            DailyTime = "\Nik's_" & datewisefile & ".txt"
            fs = System.IO.File.Open(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs" + DailyTime, System.IO.FileMode.Append)
            info = New System.Text.UTF8Encoding(True).GetBytes((System.DateTime.Now.ToString() & ":") + message & vbLf)
            ' fs.Close(); 
            fs.Write(info, 0, info.Length)
            fs.Flush()
            fs.Close()
            fs = Nothing
            info = Nothing
        Catch ex As Exception
            [Error]("InsertDailyTime:-" + ex.Message + DateTime.Now.ToString())
        Finally
            'GC.SuppressFinalize(Me)
        End Try
    End Sub


    Public Shared Sub [Error](ByVal message As String)
        Dim datewisefile As String = ""
        Dim dt As DateTime = DateTime.Now
        Dim fs As System.IO.FileStream = Nothing
        Dim info As Byte() = Nothing
        Try
            If Not System.IO.Directory.Exists(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs") Then
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs")
            End If
            'logfile = logfile.Split('.')[0] + System.DateTime.Now.ToString("yyyyMMddHHmm") + '.' + logfile.Split('.')[1]; 
            datewisefile = ((dt.Year & "") + "-" + (If(dt.Month <= 9, "0" & dt.Month & "", dt.Month & "")) & "") + "-" + (If(dt.Day <= 9, "0" & dt.Day & "", dt.Day & ""))
            errlogfile = "\TimeManager_" & datewisefile & ".Log"
            fs = System.IO.File.Open(Path.GetDirectoryName("D:\Projects\TimeManager") & "\logs" + errlogfile, System.IO.FileMode.Append)
            info = New System.Text.UTF8Encoding(True).GetBytes((System.DateTime.Now.ToString() & ":") + message & vbLf)
            ' fs.Close(); 
            fs.Write(info, 0, info.Length)
            fs.Flush()
            fs.Close()
            fs = Nothing
            info = Nothing
        Catch ex As Exception
            'Write("Error:"+ex.Message); 
        Finally
            'GC.SuppressFinalize(Me)
        End Try
    End Sub


End Class

Thursday 29 September 2011

Open task manager on remote computer even explorer.exe is not running

sometime happens that when we take remote computer and it gets hangs and we end process the explorer.exe and may be task manager also closed.at that time you can use Ctrl+Alt+End t for opening task manager.