Tuesday, December 18, 2012

sp_who and sp_who2 Blocking processes

From
http://stackoverflow.com/questions/2234691/sql-server-filter-output-of-sp-who2 and
http://sqlserverplanet.com/dba/a-better-sp_who2-using-dmvs-sp_who3

With sp_who and sp_who2 we can determine what process is blocking a table for example. We can use the following script to filter out the sp_who2 output:
DECLARE @Table TABLE(
        SPID INT,
        Status VARCHAR(MAX),
        LOGIN VARCHAR(MAX),
        HostName VARCHAR(MAX),
        BlkBy VARCHAR(MAX),
        DBName VARCHAR(MAX),
        Command VARCHAR(MAX),
        CPUTime INT,
        DiskIO INT,
        LastBatch VARCHAR(MAX),
        ProgramName VARCHAR(MAX),
        SPID_1 INT,
        REQUESTID INT
)

INSERT INTO @Table EXEC sp_who2

SELECT  *
FROM    @Table
WHERE ....

Another way is to use a custom sp_who3 sp for this:
CREATE PROCEDURE [dbo].[sp_who3] 

AS
BEGIN

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT
    SPID                = er.session_id
    ,BlkBy              = er.blocking_session_id      
    ,ElapsedMS          = er.total_elapsed_time
    ,CPU                = er.cpu_time
    ,IOReads            = er.logical_reads + er.reads
    ,IOWrites           = er.writes     
    ,Executions         = ec.execution_count  
    ,CommandType        = er.command         
    ,ObjectName         = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)  
    ,SQLStatement       =
        SUBSTRING
        (
            qt.text,
            er.statement_start_offset/2,
            (CASE WHEN er.statement_end_offset = -1
                THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
                ELSE er.statement_end_offset
                END - er.statement_start_offset)/2
        )        
    ,STATUS             = ses.STATUS
    ,[Login]            = ses.login_name
    ,Host               = ses.host_name
    ,DBName             = DB_Name(er.database_id)
    ,LastWaitType       = er.last_wait_type
    ,StartTime          = er.start_time
    ,Protocol           = con.net_transport
    ,transaction_isolation =
        CASE ses.transaction_isolation_level
            WHEN 0 THEN 'Unspecified'
            WHEN 1 THEN 'Read Uncommitted'
            WHEN 2 THEN 'Read Committed'
            WHEN 3 THEN 'Repeatable'
            WHEN 4 THEN 'Serializable'
            WHEN 5 THEN 'Snapshot'
        END
    ,ConnectionWrites   = con.num_writes
    ,ConnectionReads    = con.num_reads
    ,ClientAddress      = con.client_net_address
    ,Authentication     = con.auth_scheme
FROM sys.dm_exec_requests er
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
OUTER APPLY 
(
    SELECT execution_count = MAX(cp.usecounts)
    FROM sys.dm_exec_cached_plans cp
    WHERE cp.plan_handle = er.plan_handle
) ec
ORDER BY
    er.blocking_session_id DESC,
    er.logical_reads + er.reads DESC,
    er.session_id
 
END

Thursday, October 4, 2012

SQL Assembly Error

Exception:
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65536. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues
Possible solution:
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

ALTER DATABASE database_name SET TRUSTWORTHY ON 

USE database_name
GO

EXEC sp_changedbowner 'sa'

Thursday, June 7, 2012

Create CLR Assembly SQL Function

Create a cs code file with the desired functionality. Example:
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;

public class TimeZoneHelper
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static DateTime MountainToUtc(DateTime mountainDateTime)
    {
         TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); // "Mountain Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

         DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(mountainDateTime, zone); // it automatically takes care of daylight saving time

         return utcTime;
    }
      
    [Microsoft.SqlServer.Server.SqlFunction]
    public static DateTime PacificToUtc(DateTime pacificDateTime)
    {
         TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); // "Pacific Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

         DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(pacificDateTime, zone); // it automatically takes care of daylight saving time

         return utcTime;
    }
}
Save the file as TimeZoneHelper.cs
Open the Visual Studio 2008 Command Prompt (I also tried the 2010 version but it didnt work) and run the following:
csc /target:library C:\Users\jon.connor\Downloads\TimeZoneHelper.cs
This will create a TimeZoneHelper.dll in the same directory where the source file is in.
In SQL Server run the following to enable CLR code to run:
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

ALTER DATABASE Northwind SET TRUSTWORTHY ON;
GO
You also have to grant permissions to a SQL Server login:
GRANT UNSAFE ASSEMBLY TO some_user;
GO
Now you can create the assembly in the Northwind database
CREATE ASSEMBLY TimeZoneHelperAssembly 
FROM 'C:\Users\jon.connor\Downloads\TimeZoneHelper.dll' 
WITH PERMISSION_SET = UNSAFE
GO
Finally create functions based on the assembly methods.
CREATE FUNCTION dbo.MountainToUTC(@mountainDateTime datetime) 
RETURNS datetime 
AS EXTERNAL NAME 
[TimeZoneHelperAssembly].[TimeZoneHelper].[MountainToUtc]
GO

CREATE FUNCTION dbo.PacificToUTC(@pacificDateTime datetime) 
RETURNS datetime 
AS EXTERNAL NAME 
[TimeZoneHelperAssembly].[TimeZoneHelper].[PacificToUtc]
GO

And now you can start using these functions as you would normally do:
select dbo.MountainToUTC('2012-04-13 16:00:00'), 
       dbo.PacificToUTC('2012-04-13 16:00:00')


Thanks to http://goo.gl/W4u42

Monday, April 16, 2012

WCF MSMQ Message Retries

Using this settings (maxRetryCycles="50", retryCycleDelay="00:01:30", receiveRetryCount="0") it will retry the message 50 times with a delay of 90 seconds between every retry.

< binding name="DasBinding"
exactlyOnce="true"
durable="true"
maxRetryCycles="50"
retryCycleDelay="00:01:30"
receiveRetryCount="0"
...

In this page (http://msdn.microsoft.com/en-us/library/ms731380.aspx) there's more information about the settings for the MSMQ binding in WCF. Here I list a few of them and their descriptions:

maxRetryCycles

An integer that indicates the number of retry cycles used by the poison-message detection feature. A message becomes a poison message when it fails all delivery attempts of all cycles. The default is 3. For more information, see MaxRetryCycles.

retryCycleDelay

A TimeSpan value that specifies the time delay between retry cycles when attempting to deliver a message that could not be delivered immediately. The value defines only the minimum wait time because actual wait time can be longer. The default value is 00:10:00. For more information, see RetryCycleDelay.

receiveRetryCount

An integer that specifies the maximum number of times the queue manager should attempt to send a message before transferring it to the retry queue. The maximum number of immediate delivery attempts. The default is 5.

Monday, April 2, 2012

Nullable int in Xml Schema

If you want to be able to submit something like


< Counter1 >0< / Counter1 >
< Counter2 / >


then you need to define the following in the XSD file:


< xs:element name="Counter1" type="xs:integer" minOccurs="0" default="0" / >
< xs:element name="Counter2" type="xs:integer" minOccurs="0" default="0" / >

Tuesday, February 28, 2012

Group by Date SQL Query

From: http://goo.gl/LfvLO
The following queries group the result set by month:


select Year(CreatedOnUTC), Month(CreatedOnUTC), COUNT(1) cont
from ServiceLog
group by Year(CreatedOnUTC), Month(CreatedOnUTC)
order by Year(CreatedOnUTC) desc, Month(CreatedOnUTC) desc


select dateadd(month, datediff(month, 0, CreatedOnUTC),0), COUNT(1) cont
from ServiceLog
group by dateadd(month, datediff(month, 0, CreatedOnUTC),0)
order by dateadd(month, datediff(month, 0, CreatedOnUTC),0) desc

Monday, February 27, 2012

Log4net Exclude messages from log

In the config file add a StringMatchFilter with the string to discard/filter.

Example:


...










...

Monday, February 20, 2012

Undo TFS changes

Note: You must be an administrator in the repository where you want to perform the following commands.

1. Open a Visual Studio Command Prompt console.
2. Run tf undo {file path} /workspace:{workspace};{username} /server:{TFS name/IP}
Example:
tf undo $/Dorms/Develoment/src/Mein.Solution/Mein.Solution.vsmdi /workspace:"Jon's PC";jon.connor /server:maintfs-dev01

Note: The user and workstation info can be found by right-clicking on the file in the TFS' Source Control Explorer and then selecting Properties. A window will appear and the user and Workstation info will be listed under the Status tab.

Friday, January 20, 2012

Linq NOT IN clause

To emulate a SQL "NOT IN" clause like the following:

SELECT * FROM Clients WHERE ClientID NOT IN (select ClientID from AssignedClients)

We can do the following in Linq:

IEnumerable< Client > assignedClients = _repo.GetAssignedClients();
IEnumerable< Client > allClients = _repo.GetAllClients();
IEnumerable< Client > availableClients = from c in allClients
where !(assignedClients.Any(a => a.ClientID == c.ClientID))
select c;

Where Client has the following definition:

public class Client {
public int ClientID { get; set; }
public string ClientName { get; set; }
public bool IsActive { get; set; }
}


Another example:
var clientids = new int[] {1, 2, 3}; // IEnumerable of integers
var records = new Record[] { new Record{ClientId = 1}, new Record{ClientId = 9}, new Record{ClientId = 8}, new Record{ClientId = 2} };

var theRest = from r in records
              where !(clientids.Any(id => id == r.ClientId))
              select r;

And this is another way of obtaining the same
var theRest = records.Where(r => !clientids.Contains(r.ClientId));

They both will return the records whose ClientId is not in the list of clientids.

Wednesday, January 4, 2012

MapPath ASP.NET

MapPath sometimes refers to the directory the .NET solution is in and not the website and sometimes it does refers to the website itself. If we add the tilde character (~) it will return the website's path.

For example I have my solution at C:\Projects\src\MeinApp and inside that directory is the website (C:\Projects\src\MeinApp\WebService).
MapPath("/Schemas") will return 'C:\Projects\src\MeinApp\Schemas\' but
MapPath("~/Schemas") will return 'C:\Projects\src\MeinApp\WebService\Schemas'
which is what we finally want.

string dir = HostingEnvironment.MapPath("~/Schemas");

Kill All Active Connections To A Database

use master

ALTER DATABASE [Northwind] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

ALTER DATABASE [Northwind] SET MULTI_USER

Thanks to:
http://goo.gl/QqmX2
http://goo.gl/xNM2m