Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1,测试
2,监控
3,预案建立,防止问题出现时思维混乱
出现问题时想彻底解决方案!杜绝再次发生。
对于技术,如网站与系统,关键就是做好三点,速度、稳定性、安全性
安全性:可能发生的一定会发生
1,学好攻,做检测
2,做好防,服务器限制IP访问,策略,权限,默认端口,账号更改(sa,administrator)
3,做好预警,异常系统登陆日志,异常数据库连接,服务器新文件添加

关于监控,对于功能来说,核心功能在上线后要做好数据统计,分析是否有异常数据产生。
如一次上线积分产品,功能完成后,基本数据未修改,造成本不是积分产品的产品当成积分产品下,造成损失!

上线阶段:
1,开发:代码审查与TDD测试
2,上线:eventvwr分析与IIS日志
3,上线后:总结

对于新的项目流程
1,确定流程图
2,画出原型图
3,开发,代码审核与TDD
4,上线
5, 定期召集开会,看现有什么问题,改进【监控】


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

整个时代都建立在爱因斯坦的理论之上,知识改变世界。
爱因斯坦记录片


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

算法原理

1)将长网址md5生成32位签名串,分为4段, 每段8个字节;

2)对这四段循环处理, 取8个字节, 将他看成16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理;

3)这30位分成6段, 每5位的数字作为字母表的索引取得特定字符, 依次进行获得6位字符串;

4)总的md5串可以获得4个6位串; 取里面的任意一个就可作为这个长url的短url地址;

 算法描述:使用6个字符来表示短链接,我们使用ASCII字符中的'a'-'z','0'-'5',共计32个字符做为集合。每个字符有32种状态,六个字符就可以表示32^6(1073741824),那么如何得到这六个字符,描述如下:

对传入的长URL进行Md5,得到一个32位的字符串,这个字符串变化很多,是16的32次方,基本上可以保证唯一性。将这32位分成四份,每一份8个字符,这时机率变成了16的8次方,是4294967296,这个数字碰撞的机率也比较小啦,关键是后面的一次处理。我们将这个8位的字符认为是16进制整数,也就是1*('0x'.$val),然后取0-30位,每5个一组,算出他的整数值,然后映射到我们准备的32个字符中,最后就能够得到一个6位的短链接地址。
 

 

 

参考:

 

短链接算法收集与分析

关于微博内容中的短地址ShortURL

各大微博短网址(ShortUrl)的算法 C#


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
普通单元测试:测试类方法,如值是否相等,逻辑判断是否正确等
顺序单元测试:按指定顺序执行测试
UI界面测试:可以录制操作步骤测试
数据库测试:测试数据库表数据合法
压力测试:测试性能
Generic测试:与其他测试工具混合使用


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
修改SQLServer默认端口
1,在TCP/IP协议属性的全部侦听为“是”时,修改IPALL的端口即可
2,在TCP/IP协议属性的全部侦听为“否”时,单独设置每个IP的端口
 
默认情况下:
TCP/IP协议属性的全部侦听值为“是”
意为:在IP地址的配置中,由IPALL统管一切,
IP地址中的TCP端口、活动、启用都是无效的,只要配置上IP,都会启用的,端口是IPALL配置的端口
即:IP地址中只配置IP地址。
 
当将TCP/IP协议属性的全部侦听值为“否”时
在IP地址的配置中,自己配置自己的,决定自己的端口,是否启用等。
 
注:SQL Server 数据库引擎可以侦听同一 IP 地址的多个端口,端口以逗号分隔的格式列出:1433,1500,1501。本字段最多允许 2047 个字符。
若要配置单个 IP 地址以侦听多个端口,还必须将“TCP/IP 属性”对话框的“协议”选项卡上的“全部侦听”参数设置为“否”。
 
静态端口与动态端口
SQL Server 的默认实例侦听端口 1433 的传入连接。可以出于安全性原因或根据客户端应用程序的请求来更改该端口。
默认情况下,命名实例(包含 SQL Server Express)被配置为侦听动态端口。若要配置静态端口,请将“TCP 动态端口”框保留为空,并在“TCP 端口”框中提供一个可用的端口号。
 
动态端口

如果未启用动态端口,则为空。若要使用动态端口,请设置为 0。
对于“IPAll”,将显示所用动态端口的端口号。
如果某个 SQL Server 实例已配置为侦听动态端口,则在启动时,该实例将检查操作系统中的可用端口,并为该端口打开一个端点。传入连接必须指定要连接的端口号。
由于每次启动 SQL Server 时端口号都可能会改变,因此 SQL Server 提供 SQL Server Browser 服务监视端口,
并将传入连接指向该实例的当前端口。使用动态端口会增加通过防火墙连接 SQL Server 的复杂性,因为重新启动 SQL Server 时端口号可能会改变,从而需要更改防火墙设置。
若要避免通过防火墙连接的问题,请将 SQL Server 配置为使用静态端口。

 
 


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
Service Broker:多服务器单信息传递,大小写敏感
组成:
Message:信内容,为便于区分保证唯一性,信息的前缀用域名好一些。
Contracts:信头,组合message及message由哪边发送,发起者或者接收者
Queue:信封,收到的信息存储的位置

建立方式:
1,定义 SERVICE:将上面三者组合
2,信息发送:
BEGIN TRY
 BEGIN TRANSACTION;
  DECLARE @ch UNIQUEIDENTIFIER
  DECLARE @msg NVARCHAR(MAX);

  BEGIN DIALOG CONVERSATION @ch
   FROM SERVICE [InitiatorService]
   TO SERVICE 'TargetService'
   ON CONTRACT [http://ssb.csharp.at/SSB_Book/c03/HelloWorldContract]
   WITH ENCRYPTION = OFF;

  SET @msg = 
   '<HelloWorldRequest>
     Klaus Aschenbrenner
   </HelloWorldRequest>';

  SEND ON CONVERSATION @ch MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/RequestMessage] (@msg);
 COMMIT
END TRY
BEGIN CATCH
 ROLLBACK TRANSACTION
END CATCH
GO
3,接收信息
--***********************************************************************************
--*  Retrieve the sent message from the queue "TargetQueue" with a WAITFOR statement
--***********************************************************************************
DECLARE @cg UNIQUEIDENTIFIER
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE @messagebody XML;

BEGIN TRY
 BEGIN TRANSACTION;

  WAITFOR (
   RECEIVE TOP (1)
    @cg = conversation_group_id,
    @ch = conversation_handle,
    @messagetypename = message_type_name,
    @messagebody = CAST(message_body AS XML)
   FROM TargetQueue
  ), TIMEOUT 60000

  IF (@@ROWCOUNT > 0)
  BEGIN
   PRINT 'Conversation group: ' + CAST(@cg AS NVARCHAR(MAX))
   PRINT 'Conversation handle: ' + CAST(@ch AS NVARCHAR(MAX))
   PRINT 'Message type: ' + @messagetypename
   PRINT 'Message body: ' + CAST(@messagebody AS NVARCHAR(MAX))
  END

 COMMIT
END TRY
BEGIN CATCH
 ROLLBACK TRANSACTION
END CATCH
GO
4,监控对列
CREATE EVENT NOTIFICATION PoisonMessageNotification ON QUEUE TargetQueue
FOR Broker_Queue_Disabled
TO SERVICE 'PoisonMessageNotifyService', 'current database'
GO


---------------------------明细
USE master;

IF EXISTS (SELECT * FROM sys.databases WHERE name = 'Chapter3_HelloWorldSvc')
BEGIN
	PRINT 'Dropping database ''Chapter3_HelloWorldSvc''';
	DROP DATABASE Chapter3_HelloWorldSvc;
END
GO

CREATE DATABASE Chapter3_HelloWorldSvc
GO

USE Chapter3_HelloWorldSvc
GO

--*********************************************
--*  Create the message type "RequestMessage"
--*********************************************
CREATE MESSAGE TYPE
[http://ssb.csharp.at/SSB_Book/c03/RequestMessage]
VALIDATION = NONE
GO

--*********************************************
--*  Create the message type "ResponseMessage"
--*********************************************
CREATE MESSAGE TYPE
[http://ssb.csharp.at/SSB_Book/c03/ResponseMessage]
VALIDATION = NONE
GO

--*********************************************
--*  Show the created message types
--*********************************************
SELECT * FROM sys.service_message_types 
GO

--************************************************
--*  Changing the validation of the message types
--************************************************
ALTER MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/RequestMessage]
VALIDATION = WELL_FORMED_XML
GO

ALTER MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/ResponseMessage]
VALIDATION = WELL_FORMED_XML
GO

--************************************************
--*  Create the contract "HelloWorldContract"
--************************************************
CREATE CONTRACT [http://ssb.csharp.at/SSB_Book/c03/HelloWorldContract]
(
	[http://ssb.csharp.at/SSB_Book/c03/RequestMessage] SENT BY INITIATOR,
	[http://ssb.csharp.at/SSB_Book/c03/ResponseMessage] SENT BY TARGET
)
GO

--*************************************************************
--*  Getting some information about the newly created contract
--*************************************************************
SELECT 
	sc.name AS 'Contract', 
	mt.name AS 'Message type', 
	cm.is_sent_by_initiator,
	cm.is_sent_by_target,
	mt.validation
FROM sys.service_contract_message_usages cm 
	INNER JOIN sys.service_message_types mt ON cm.message_type_id = mt.message_type_id
	INNER JOIN sys.service_contracts sc ON sc.service_contract_id = cm.service_contract_id
GO

--********************************************************
--*  Create the queues "InitiatorQueue" and "TargetQueue"
--********************************************************
CREATE QUEUE InitiatorQueue
WITH STATUS = ON
GO

CREATE QUEUE TargetQueue
WITH STATUS = ON
GO

--*************************************************************
--*  Getting some information about the newly created queues
--*************************************************************
SELECT * FROM sys.service_queues
GO

--************************************************************
--*  Create the queues "InitiatorService" and "TargetService"
--************************************************************
CREATE SERVICE InitiatorService
ON QUEUE InitiatorQueue 
(
	[http://ssb.csharp.at/SSB_Book/c03/HelloWorldContract]
)
GO

CREATE SERVICE TargetService
ON QUEUE TargetQueue
(
	[http://ssb.csharp.at/SSB_Book/c03/HelloWorldContract]
)
GO

--*************************************************************
--*  Getting some information about the newly created services
--*************************************************************
SELECT
	sv.name AS 'Service',
	sc.name AS 'Contract'
FROM sys.services sv
	INNER JOIN sys.service_contract_usages scu ON scu.service_id = sv.service_id
	INNER JOIN sys.service_contracts sc ON sc.service_contract_id = scu.service_contract_id
GO

--********************************************************************
--*  Sending a message from the InitiatorService to the TargetService
--********************************************************************
BEGIN TRY
	BEGIN TRANSACTION;
		DECLARE @ch UNIQUEIDENTIFIER
		DECLARE @msg NVARCHAR(MAX);

		BEGIN DIALOG CONVERSATION @ch
			FROM SERVICE [InitiatorService]
			TO SERVICE 'TargetService'
			ON CONTRACT [http://ssb.csharp.at/SSB_Book/c03/HelloWorldContract]
			WITH ENCRYPTION = OFF;

		SET @msg = 
			'<HelloWorldRequest>
					Klaus Aschenbrenner
			</HelloWorldRequest>';

		SEND ON CONVERSATION @ch MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/RequestMessage] (@msg);
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO

--********************************************************************
--*  View the sent message on the queue "TargetQueue"
--********************************************************************
SELECT * FROM TargetQueue
GO

--********************************************************************
--*  View the created conversation endpoints
--********************************************************************
SELECT * FROM sys.conversation_endpoints
GO

--********************************************************************
--*  Retrieve the sent message from the queue "TargetQueue"
--********************************************************************
DECLARE @cg UNIQUEIDENTIFIER
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML;

BEGIN TRY
	BEGIN TRANSACTION;

		RECEIVE TOP(1)
			@cg = conversation_group_id,
			@ch = conversation_handle,
			@messagetypename = message_type_name,
			@messagebody = CAST(message_body AS XML)
		FROM TargetQueue

		PRINT 'Conversation group: ' + CAST(@cg AS NVARCHAR(MAX))
		PRINT 'Conversation handle: ' + CAST(@ch AS NVARCHAR(MAX))
		PRINT 'Message type: ' + @messagetypename
		PRINT 'Message body: ' + CAST(@messagebody AS NVARCHAR(MAX))

	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO

--***********************************************************************************
--*  Retrieve the sent message from the queue "TargetQueue" with a WAITFOR statement
--***********************************************************************************
DECLARE @cg UNIQUEIDENTIFIER
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML;

BEGIN TRY
	BEGIN TRANSACTION;

		WAITFOR (
			RECEIVE TOP (1)
				@cg = conversation_group_id,
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM TargetQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT > 0)
		BEGIN
			PRINT 'Conversation group: ' + CAST(@cg AS NVARCHAR(MAX))
			PRINT 'Conversation handle: ' + CAST(@ch AS NVARCHAR(MAX))
			PRINT 'Message type: ' + @messagetypename
			PRINT 'Message body: ' + CAST(@messagebody AS NVARCHAR(MAX))
		END

	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO

--**************************************************
--*  Create a table to store the processed messages
--**************************************************
CREATE TABLE ProcessedMessages
(
	ID UNIQUEIDENTIFIER NOT NULL,
	MessageBody XML NOT NULL,
	ServiceName NVARCHAR(MAX) NOT NULL
)
GO

--*******************************************************************
--*  Send a response message back to the service "InitiatorService"
--*******************************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML
DECLARE @responsemessage XML;

BEGIN TRY
	BEGIN TRANSACTION
		WAITFOR (
			RECEIVE TOP (1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM TargetQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT > 0)
		BEGIN
			IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/RequestMessage')
			BEGIN
				-- Store the received request message in a table
				INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'TargetService')

				-- Construct the response message
				SET @responsemessage = '<HelloWorldResponse>' + @messagebody.value('/HelloWorldRequest[1]', 'NVARCHAR(MAX)') + '</HelloWorldResponse>';

				-- Send the response message back to the initiating service
				SEND ON CONVERSATION @ch MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/ResponseMessage] (@responsemessage);

				-- End the conversation on the target's side
				END CONVERSATION @ch;
			END
		END
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO


--********************************************************************
--*  View the sent message on the queue "InitiatorQueue"
--********************************************************************
SELECT * FROM InitiatorQueue
GO

--********************************************************************
--*  View the processed message in the table "ProcessedMessages"
--********************************************************************
SELECT * FROM ProcessedMessages
GO

--*******************************************************************
--*  Service program for the service "InitiatorService"
--*******************************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML;

BEGIN TRY
	BEGIN TRANSACTION
		WAITFOR (
			RECEIVE TOP (1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM InitiatorQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT > 0)
		BEGIN
			IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/ResponseMessage')
			BEGIN
				-- Store the received response) message in a table
				INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'InitiatorService')
			END

			IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
			BEGIN
				-- End the conversation on the initiator's side
				END CONVERSATION @ch;
			END
		END
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO

--***********************************************************************************
--*  Endless receive loop for processing incoming messages on the initiator's queue
--***********************************************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML;

WHILE (1=1)
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		WAITFOR (
			RECEIVE TOP (1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM InitiatorQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT = 0)
		BEGIN
			ROLLBACK TRANSACTION
			BREAK
		END

		IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/ResponseMessage')
		BEGIN
			-- Store the received response) message in a table
			INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'InitiatorService')
		END

		IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
		BEGIN
			-- End the conversation on the initiator's side
			END CONVERSATION @ch;
		END

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
	END CATCH
END
GO

--********************************************************************************
--*  Endless receive loop for processing incoming messages on the target's queue
--********************************************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML
DECLARE @responsemessage XML;

WHILE (1=1)
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		WAITFOR (
			RECEIVE TOP (1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM TargetQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT = 0)
		BEGIN
			ROLLBACK TRANSACTION
			BREAK
		END

		IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/RequestMessage')
		BEGIN
			-- Store the received request message in a table
			INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'TargetService')

			-- Construct the response message
			SET @responsemessage = '<HelloWorldResponse>' + @messagebody.value('/HelloWorldRequest[1]', 'nvarchar(max)') + '</HelloWorldResponse>';

			-- Send the response message back to the initiating service
			SEND ON CONVERSATION @ch MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/ResponseMessage] (@responsemessage);

			-- End the conversation on the target's side
			END CONVERSATION @ch;
		END

		IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
		BEGIN
			-- End the conversation
			END CONVERSATION @ch;
		END

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
	END CATCH
END
GO

--**********************************************************
--*  Error handling with a savepoint on the target's queue
--**********************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML
DECLARE @responsemessage XML;

WHILE (1=1)
BEGIN
	BEGIN TRANSACTION

	WAITFOR (
		RECEIVE TOP (1)
			@ch = conversation_handle,
			@messagetypename = message_type_name,
			@messagebody = CAST(message_body AS XML)
		FROM TargetQueue
	), TIMEOUT 60000

	IF (@@ROWCOUNT = 0)
	BEGIN
		ROLLBACK TRANSACTION
		BREAK
	END

	SAVE TRANSACTION MessageReceivedSavepoint

	IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/RequestMessage')
	BEGIN
		BEGIN TRY
			-- Store the received request message in a table
			INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'TargetService')

			-- Construct the response message
			SET @responsemessage = '<HelloWorldResponse>' + @messagebody.value('/HelloWorldRequest[1]', 'nvarchar(max)') + '</HelloWorldResponse>';

			-- Send the response message back to the initiating service
			SEND ON CONVERSATION @ch MESSAGE TYPE [http://ssb.csharp.at/SSB_Book/c03/ResponseMessage] (@responsemessage);

			-- End the conversation on the target's side
			END CONVERSATION @ch;
		END TRY
		BEGIN CATCH
			IF (ERROR_NUMBER() = 1205) 
			BEGIN
				-- A deadlock occurred. 
				-- We can try it again...
				ROLLBACK TRANSACTION
				CONTINUE
			END
			ELSE
			BEGIN
				-- A other error occurred.
				-- The message can't be processed successfully, because it's a poison message
				ROLLBACK TRANSACTION MessageReceivedSavepoint
				PRINT 'Error occured: ' + CAST(@messagebody AS NVARCHAR(MAX))
			END
		END CATCH
	END

	IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
	BEGIN
		-- End the conversation
		END CONVERSATION @ch;
	END

	COMMIT TRANSACTION
END
GO

--**************************************
--*  Poison messages in Service Broker
--**************************************
-- Reactivating the queue
ALTER QUEUE TargetQueue WITH STATUS = ON
GO

-- Service program for handling the poison message
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML

WHILE (1=1)
BEGIN
	BEGIN TRANSACTION

	WAITFOR (
		RECEIVE TOP (1)
			@ch = conversation_handle,
			@messagetypename = message_type_name,
			@messagebody = CAST(message_body AS XML)
		FROM TargetQueue
	), TIMEOUT 60000

	IF (@@ROWCOUNT = 0)
	BEGIN
		ROLLBACK TRANSACTION
		BREAK
	END

	-- Rollling back the current transaction
	PRINT 'Rollback the current transaction - simulating a poison message...'
	ROLLBACK TRANSACTION
END
GO

--**********************************************************
--*  Setting up the event notification for poison messages
--**********************************************************
-- Create the queue which stores the event notification messages
CREATE QUEUE PoisonMessageNotifyQueue
GO

-- Create the service that accepts the event notification messages
CREATE SERVICE PoisonMessageNotifyService ON QUEUE PoisonMessageNotifyQueue
(
	[http://schemas.microsoft.com/SQL/Notifications/PostEventNotification]
);
GO

-- Create the event notification itself
CREATE EVENT NOTIFICATION PoisonMessageNotification ON QUEUE TargetQueue
FOR Broker_Queue_Disabled
TO SERVICE 'PoisonMessageNotifyService', 'current database'
GO

-- Select the received event notification message
SELECT * FROM PoisonMessageNotifyQueue
GO

--**********************************************************
--*  End an conversation with an error
--**********************************************************
DECLARE @ch UNIQUEIDENTIFIER
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML

BEGIN TRY
	BEGIN TRANSACTION
		WAITFOR (
			RECEIVE TOP (1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM TargetQueue
		), TIMEOUT 60000

		IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/RequestMessage')
		BEGIN
			-- End the conversation with an error
			END CONVERSATION @ch WITH ERROR = 4242 DESCRIPTION = 'My custom error message'
		END
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO

-- Table that stores error information
CREATE TABLE ErrorLog
(
	ID UNIQUEIDENTIFIER NOT NULL,
	ErrorCode INT NOT NULL,
	ErrorMessage NVARCHAR(MAX) NOT NULL
)
GO

-- Service program for the InitiatorService, that handles also error message types
DECLARE @ch UNIQUEIDENTIFIER 
DECLARE @messagetypename NVARCHAR(256)
DECLARE	@messagebody XML
DECLARE @errorcode INT
DECLARE @errormessage NVARCHAR(3000);

BEGIN TRY
	BEGIN TRANSACTION
		WAITFOR (
			RECEIVE TOP(1)
				@ch = conversation_handle,
				@messagetypename = message_type_name,
				@messagebody = CAST(message_body AS XML)
			FROM InitiatorQueue
		), TIMEOUT 60000

		IF (@@ROWCOUNT > 0)
		BEGIN
			IF (@messagetypename = 'http://ssb.csharp.at/SSB_Book/c03/ResponseMessage')
			BEGIN
				-- Store the received response) message in a table
				INSERT INTO ProcessedMessages (ID, MessageBody, ServiceName) VALUES (NEWID(), @messagebody, 'InitiatorService')
			END

			IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
			BEGIN
				-- End the conversation on the initiator's side
				END CONVERSATION @ch;
			END

			IF (@messagetypename = 'http://schemas.microsoft.com/SQL/ServiceBroker/Error')
			BEGIN
				-- Extract the error information from the sent message
				SET @errorcode = (SELECT @messagebody.value(
					N'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"; 
					(/brokerns:Error/brokerns:Code)[1]', 'int'));
				SET @errormessage = (SELECT @messagebody.value(
					'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error";
					(/brokerns:Error/brokerns:Description)[1]', 'nvarchar(3000)'));

				-- Log the error
				INSERT INTO ErrorLog(ID, ErrorCode, ErrorMessage)
				VALUES (NEWID(), @errorcode, @errormessage)

				-- End the conversation on the initiator's side
				END CONVERSATION @ch;
			END
		END
	COMMIT
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION
END CATCH
GO


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
--find SQL login with blank passwords
select name,type_desc,create_date from sys.sql_logins where pwdcompare('', password_hash) = 1

--find SQL login with password same as name
select name,type_desc,create_date from sys.sql_logins where pwdcompare(name, password_hash) = 1

--比对sa的密码是否为123abc
SELECT TOP 50 * 
FROM sys.sql_logins sl
WHERE name = 'sa' AND pwdcompare('123abc', password_hash) = 1


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
with(nolock)并意味着没有锁,实际上在查询一张表时,还是有锁,会对对象增加架构锁,
防止表会修改,会对数据库增加共享锁。若使用drop index,则要等到架构锁释放。

sql server2005提供了快照隔离和读取已提交快照这两种新的不加锁、无阻塞的事务隔离级别,可使用
快照:每次从数据进行修改时,会在teampdb上存储上一版本
好处:
select不要求锁,会大大降低整个库的锁负载量
nolock会读取到未提交事务时修改的数据,而读快照读取的是修改之前的数据,故nolock易读取到脏数据
读快照与nolock相同的地方在于都不加共享锁,但都会加对象架构锁与数据库的共享锁,区别在于,nolock需要
在每个sql语句后加,而读快照不用,并用读快照不会读到未提交事务的数据。
行版本控制:在任何一个修改之前,先对修改前的版本做一个复制 ,后续的一切读操作都会去读这个复制的版本,修改将创建一个新的版本。在这种处理方式下,读、写操作不会相互阻塞。使用这种行版本控制机制的好处,是程序的并发性比较高,但是缺点是用户读到的虽然不是一个脏数据,但是可能是个正在被修改马上就要过期的数据值
【注:加上行版本控制后,会最大限度降低死锁,但不是没有死锁】

相关存储过程:select * from sys.dm_tran_version_store


把SQL Server数据库事务隔离级别设置为已提交读快照隔离:
如果直接运行下面的语句:
ALTER Database [mydbname] SET READ_COMMITTED_SNAPSHOT ON
会可能被阻塞很长时间。
你可以选择运行下面的语句:
if(charindex('Microsoft SQL Server 2005',@@version) > 0)
begin
declare @sql varchar(8000)
select @sql = '
ALTER DATABASE ' + DB_NAME() + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE ;
ALTER DATABASE ' + DB_NAME() + ' SET READ_COMMITTED_SNAPSHOT ON;
ALTER DATABASE ' + DB_NAME() + ' SET MULTI_USER;'
Exec(@sql)
end
通过查询 sys.databases的 is_read_committed_snapshot_on字段
select is_read_committed_snapshot_on from sys.databases where name = DB_Name()
is_read_committed_snapshot_on如果为1表示目前为已提交读快照隔离级别

引用:
7 Things Developers Should Know About SQL Server
Using Read-Committed Snapshot Isolation - Mini-Lab
SQL Server已提交读快照隔离级别的设置
SQL Server 2005使用基于行版本控制的隔离级别初探


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1、.NET 框架支持两种程序集:强命名程序集(strongly named assembly)非强命名程序集。
      强命名程序集有一个发布者的公钥/私钥对签名,其中的公钥/私钥对唯一地标识了程序集的发布者。利用公钥/私钥对我们可以对程序集进行唯一的标识、安全策略和版本策略。(由于简单地用文件名导致了目前所谓的DLL Hell,强命名程序集就是CLR用来唯一地标识一个程序集的机制。)

2、一个程序集有两种部署方式:私有方式和全局方式。
     非强命名程序集只能进行私有部署。
     全局部署方式将程序集部署在一些CLR确知的地方,当CLR搜索程序集时,它会知道到这些地方去查找。强命名程序集既可以进行私有部署,也可以进行全局部署。它提供多个应用程序域访问同一个程序集的能力,特别地,内存中只存在该程序集的同一份副本,这种非特定于域的代码共享极大节省了内存资源占用。并且,在大多数情况下,共享程序集安装在全局程序集高速缓冲存储器(Global Assembly Cache)中而不存在于应用程序相关目录下,对它的引用不会产生文件复制,自然也不会产生额外的副本。因而,共享程序集不能简单通过XCOPY命令实现部署,而应使用MSI(Microsoft Windows Installer)进行。当组件和主应用程序不由同一个开发商建立,或者一个大应用程序分布在几个小工程中时,常常需要使用共享程序集。

3,引用流程: 如果文件名包含了完整路径,则 CSC.exe 加载指定路径下的文件。如果指定的是不带路径的文件,它将在以下目录中查找引用的程序集:
       a、当前工作路径;
       b、编译器目前使用的CLR所在的目录。MSCorLib.dll总是包含在该目录中(System.Object就定义在这个程序集中)。该目录类似于:
       C:/Windows/Micorsoft.NET/Framework/v1.0.3427 ;
       c、任何用CSC.exe的 /lib 命令行开关指定的目录;
       d、任何LIB环境变量中指定的目录

       安装.NET框架时,微软的程序集文件会被分别拷贝到 CLR所在目录及 GAC目录中。在CLR所在目录中拷贝是使我们能够方便的生成自己的程序集;GAC中的拷贝则是用于运行时加载这些程序集。

       CSC.exe 不在GAC 中查找所引用的程序集的原因是因为需要指定的路径比较麻烦。
4,可用vs自带的合成日志查看器查看程序集加载过程

5,创建与部署:用SN工具生成强签名,用GACUti部署到全局,这样一个程序集可被多个应用程序访问


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

编译出现这个错误:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

操作:使用微软企业库,修改了Microsoft.Practices.EnterpriseLibrary.Common.dll,Microsoft.Practices.EnterpriseLibrary.Data.dll
(一个知识点是修改了这种dll后,微软的强签名就没了,由PublicKeyToken=31bf3856ad364e35变成了PublicKeyToken=null)

问题引发场景:
新项目中引用了修改的企业库Common.dll,Data.dll,未改的企业库Caching.dll,问题就来了:
微软的企业库Caching.dll里面还是引用原来的带有强签名的Common.dll(可通过Reflector查看此引用),而我们在这个新项目中引用的是自己修改的Common.dll,在编译时造成Caching.dll找不到微软的Common.dll,从而引发上述错误。
解决方法:
1,修改Caching.dll,将其引用的Common.dll改为自已修改后的Common.dll
2,因本项目中没有用到Caching.dll的地方,去掉此Caching.dll,解决问题
3,因微软的Common.dll是强签名,可注册到GAC全局

注:
1,引用Common.dll的微软企业库还有
Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.dll
Microsoft.Practices.EnterpriseLibrary.Caching.Database.dll
Microsoft.Practices.EnterpriseLibrary.Caching.dll
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll
2,一个被忽略的基本事实是:打包的dll如father.dll 里面引用了son.dll,那么在新项目中若引用father.dll,那么在bin下也要有son.dll的存在。


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

在sqlserver服务器有一个名为SQL Server Browser的服务,一直没用到,最近一台服务器安装了多个实例,其中一个实例在外部怎么都访问不了,这时查资料才明白需要开启SQL Server Browser服务。
如果一个物理服务器上面有多个SQL Server实例,那么为了确保客户端能访问到正确的实例,所以SQL Server 2005以后提供了一个新的Browser服务。
参考:SQL Server : Browser服务是干什么的


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
--只有mdf文件,没有ldf文件,可通过选项来恢复。FOR ATTACH_REBUILD_LOG;
--有日志文件则附加上,若无,则新建
CREATE DATABASE AdventureWorks2012
ON (FILENAME = 'M:\Program Files\Microsoft SQL Server201201\MSSQL11.MSSQLSERVER\MSSQL\DATA\AdventureWorks2012_Data.mdf')
FOR ATTACH_REBUILD_LOG;


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Repl_DropArticlePeer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Repl_DropArticlePeer]
GO

/*对等复制删除Article
 EXEC LS_DropArticlePeer 'testrepl'
*/
CREATE PROCEDURE Repl_DropArticlePeer
@article AS sysname
AS 
BEGIN 
	IF ISNULL(@article,'') = ''
	BEGIN
		RETURN
	END  

       DECLARE @publication AS sysname;  
	SET @publication =DB_NAME(); 
	--SET @article = N'testRepl'

	--删除对应订阅
	IF @@SERVERNAME = 'DataBaseC' --在哪台机器上运行,就不删除自己
	BEGIN
		--exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'databasec'
		exec sp_dropsubscription @publication =@publication, @article =@article, @subscriber = 'DataBaseD'
		exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'sqlcluster'
	END
	ELSE IF @@SERVERNAME = 'DataBaseD'
	BEGIN
		exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'databasec'
		--exec sp_dropsubscription @publication =@publication, @article =@article, @subscriber = 'DataBaseD'
		exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'sqlcluster'
	END
	ELSE IF @@SERVERNAME = 'SQLCLUSTER'
	BEGIN
		exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'databasec'
		exec sp_dropsubscription @publication =@publication, @article =@article, @subscriber = 'DataBaseD'
		--exec sp_dropsubscription @publication = @publication, @article = @article, @subscriber = 'sqlcluster'
	END


	EXEC sp_droparticle 
	  @publication = @publication, 
	  @article = @article,
	  @force_invalidate_snapshot = 1;
END 


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Repl_AddArticlePeer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Repl_AddArticlePeer]
GO

/*对等复制增加Article
 EXEC Repl_AddArticlePeer 'testrepl'
*/

CREATE PROCEDURE Repl_AddArticlePeer
@article AS sysname
AS 
BEGIN 
	IF ISNULL(@article,'') = ''
	BEGIN
		RETURN
	END  

	DECLARE @publication AS sysname;  
	SET @publication =DB_NAME(); 

	DECLARE
        @ins_cmd	nvarchar (255),
        @del_cmd	nvarchar (255),
        @upd_cmd	nvarchar (255) 

	SET @ins_cmd = 'CALL sp_MS' + 'ins' + '_dbo' + @article
	SET @del_cmd = 'CALL sp_MS' + 'del' + '_dbo' + @article
	SET @upd_cmd = 'CALL sp_MS' + 'upd' + '_dbo' + @article

	EXEC sp_addarticle @publication = @publication, @article = @article, @source_owner = N'dbo', 
	@source_object =@article, @type = N'logbased', @description = null,@creation_script = null,
	@pre_creation_cmd = N'drop', @schema_option = 0x0000000008035DDB, @force_invalidate_snapshot = 1, @identityrangemanagementoption = N'manual', 
	@destination_table = @article, @status = 16,@vertical_partition = N'false', @ins_cmd = @ins_cmd, @del_cmd = @del_cmd, @upd_cmd = @upd_cmd
END 


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
系统信息级别:http://blog.sqlauthority.com/2007/04/25/sql-server-error-messages-sysmessages-error-severity-level/

测试:
BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;

当sqlserver有用户级错误时记录
CREATE event session xEvents_Session on server
add event sqlserver.error_reported
(
action
(
sqlserver.session_id, -- SPID which raises the error
sqlserver.plan_handle, -- Plan handle which can be used to retrieve the graphical plan
sqlserver.tsql_stack, -- T-SQL stack for extended debugging purposes
package0.callstack, -- Callstack for extended debugging purposes
sqlserver.sql_text, -- T-SQL query which encountered the error
sqlserver.username, -- Name of the user that reported the error
sqlserver.client_app_name, -- Client application name
sqlserver.client_hostname, -- Host which initiated the query
sqlserver.database_name -- Database against which the query was being executed
) 
 WHERE severity >= 11 AND Severity <=16
)
add target package0.ring_buffer
with (max_dispatch_latency=1seconds)
GO
-- start the tracing
alter event session xEvents_Session on server state = start

--alter event session xEvents_Session on server state = stop
--drop event session xEvents_Session on SERVER



--查看

SELECT 
    n.value('(event/@name)[1]', 'varchar(50)') AS event_name,
    n.value('(event/@package)[1]', 'varchar(50)') AS package_name,
    DATEADD(hh, 
            DATEDIFF(hh, GETUTCDATE(), CURRENT_TIMESTAMP), 
            n.value('(event/@timestamp)[1]', 'datetime2')) AS [timestamp],  
n.value('(event/action[@name="database_name"]/value)[1]', 'nvarchar(128)') AS [database_name],
    n.value('(event/action[@name="sql_text"]/value)[1]', 'nvarchar(max)') AS [sql_text],
n.value('(event/data[@name="message"]/value)[1]', 'nvarchar(max)') AS [message],
n.value('(event/action[@name="username"]/value)[1]', 'nvarchar(max)') AS [username],
n.value('(event/action[@name="client_hostname"]/value)[1]', 'nvarchar(max)') AS [client_hostname],
n.value('(event/action[@name="client_app_name"]/value)[1]', 'nvarchar(max)') AS [client_app_name],
n.value('(event/action[@name="session_id"]/value)[1]', 'nvarchar(max)') AS [session_id],
n.value('(event/action[@name="plan_handle"]/value)[1]', 'nvarchar(max)') AS [plan_handle],
n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@handle)[1]', 'varchar(max)') AS [tsql_stack],
n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@offsetStart)[1]', 'int') AS [statement_start_offset],
n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@offsetEnd)[1]', 'int') AS [statement_end_offset],
n.value('(event/action[@name="callstack"]/value)[1]', 'nvarchar(max)') AS [callstack],
n.value('(event/data[@name="object_id"]/value)[1]', 'int') AS [object_id],
    n.value('(event/data[@name="object_type"]/value)[1]', 'nvarchar(128)') AS [object_type],
    n.value('(event/data[@name="duration"]/value)[1]', 'int') AS [duration],
    n.value('(event/data[@name="cpu"]/value)[1]', 'int') AS [cpu],
    n.value('(event/data[@name="reads"]/value)[1]', 'int') AS [reads],
    n.value('(event/data[@name="writes"]/value)[1]', 'int') AS [writes] into #1120
FROM
(    SELECT td.query('.') as n
    FROM 
    (
        SELECT CAST(target_data AS XML) as target_data
        FROM sys.dm_xe_sessions AS s 
        JOIN sys.dm_xe_session_targets AS t 
            ON t.event_session_address = s.address
        WHERE s.name = 'xEvents_Session'
          --AND t.target_name = 'ring_buffer'
    ) AS sub
    CROSS APPLY target_data.nodes('RingBufferTarget/event') AS q(td)
) as TAB

--查看有sql的
SELECT TIMESTAMP,database_name,[message],sql_text,username,client_hostname,client_app_name
FROM #1120 a
WHERE a.sql_text != ''


--查看应用执行的
SELECT TIMESTAMP,database_name,[message],
SUBSTRING(qt.text,a.statement_start_offset/2+1,
(case when a.statement_end_offset = -1
then DATALENGTH(qt.text) 
else a.statement_end_offset end -a.statement_start_offset)/2 + 1) sql_text,qt.text alltext,
username,client_hostname,client_app_name
FROM #1120 a
CROSS APPLY sys.dm_exec_sql_text(CONVERT(VARBINARY(max),a.tsql_stack,1) )  qt
WHERE a.sql_text IS NULL AND tsql_stack != '' AND client_app_name = '.Net SqlClient Data Provider'
ORDER BY TIMESTAMP DESC


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
--以下xevent记录了通过sqlserver查询工具直接更新,删除表数据时的记录。
IF NOT EXISTS( SELECT 1 FROM sys.dm_xe_sessions dxs(NOLOCK) WHERE name = 'EventErrorMonitor' )
BEGIN 
	CREATE EVENT session EventErrorMonitor on server
	ADD EVENT sqlserver.error_reported
	(
	ACTION
	(
	sqlserver.session_id, -- SPID which raises the error
	sqlserver.plan_handle, -- Plan handle which can be used to retrieve the graphical plan
	sqlserver.tsql_stack, -- T-SQL stack for extended debugging purposes
	package0.callstack, -- Callstack for extended debugging purposes
	sqlserver.sql_text, -- T-SQL query which encountered the error
	sqlserver.username, -- Name of the user that reported the error
	sqlserver.client_app_name, -- Client application name
	sqlserver.client_hostname, -- Host which initiated the query
	sqlserver.database_name -- Database against which the query was being executed
	) 
	 WHERE severity >= 11 AND Severity <=16
	)
	ADD TARGET package0.ring_buffer
	WITH (max_dispatch_latency=1seconds)

	ALTER EVENT SESSION EventErrorMonitor on server state = START
  
END 
ELSE
BEGIN

	SELECT 
		 DATEADD(hh, 
				DATEDIFF(hh, GETUTCDATE(), CURRENT_TIMESTAMP), 
				n.value('(event/@timestamp)[1]', 'datetime2')) AS [timestamp],  
		n.value('(event/action[@name="database_name"]/value)[1]', 'nvarchar(128)') AS [database_name],
		n.value('(event/action[@name="sql_text"]/value)[1]', 'nvarchar(max)') AS [sql_text],
		n.value('(event/data[@name="message"]/value)[1]', 'nvarchar(max)') AS [message],
		n.value('(event/action[@name="username"]/value)[1]', 'nvarchar(max)') AS [username],
		n.value('(event/action[@name="client_hostname"]/value)[1]', 'nvarchar(max)') AS [client_hostname],
		n.value('(event/action[@name="client_app_name"]/value)[1]', 'nvarchar(max)') AS [client_app_name],
		n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@handle)[1]', 'varchar(max)') AS [tsql_stack],
		n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@offsetStart)[1]', 'int') AS [statement_start_offset],
		n.value('(event/action[@name="tsql_stack"]/value/frames/frame/@offsetEnd)[1]', 'int') AS [statement_end_offset]
	into #ErrorMonitor
	FROM
	(    SELECT td.query('.') as n
		FROM 
		(
			SELECT CAST(target_data AS XML) as target_data
			FROM sys.dm_xe_sessions AS s 
			JOIN sys.dm_xe_session_targets AS t 
				ON t.event_session_address = s.address
			WHERE s.name = 'EventErrorMonitor'
			  --AND t.target_name = 'ring_buffer'
		) AS sub
		CROSS APPLY target_data.nodes('RingBufferTarget/event') AS q(td)
	) as TAB
  
	INSERT INTO PerfLogicMessage(StartTime,database_name,message,sql_text,alltext,username,client_hostname,client_app_name)
	SELECT TIMESTAMP,database_name,[message],sql_text,'',username,client_hostname,client_app_name
	FROM #ErrorMonitor a
	WHERE a.sql_text != '' AND client_app_name !='Microsoft SQL Server Management Studio - 查询'

	INSERT INTO PerfLogicMessage(StartTime,database_name,message,sql_text,alltext,username,client_hostname,client_app_name)
	--查看应用执行的
	SELECT  TIMESTAMP,database_name,[message],
	SUBSTRING(qt.text,a.statement_start_offset/2+1,
				(case when a.statement_end_offset = -1
				then DATALENGTH(qt.text) 
				else a.statement_end_offset end -a.statement_start_offset)/2 + 1) sql_text,qt.text alltext,
	username,client_hostname,client_app_name
	FROM #ErrorMonitor a
	CROSS APPLY sys.dm_exec_sql_text(CONVERT(VARBINARY(max),a.tsql_stack,1) )  qt
	WHERE a.sql_text IS NULL AND tsql_stack != '' AND client_app_name = '.Net SqlClient Data Provider'

	DROP TABLE #ErrorMonitor

	--重启以清空
	ALTER EVENT SESSION EventErrorMonitor ON SERVER STATE = STOP
	ALTER EVENT SESSION EventErrorMonitor on server state = START
END 


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
XEVENT:在指定事件发生时记录,可将日志放在内存或文件中,效率比sqlprofile高。
参考:
Introduction to Extended Events
Troubleshooting Error 511 using XEvents

相关DMV1
相关DMV2

相关DMV:

Events
-- Event objects
SELECT p.name AS package_name,
       o.name AS event_name,
       o.description
FROM sys.dm_xe_packages AS p
JOIN sys.dm_xe_objects AS o 
     ON p.guid = o.package_guid
WHERE (p.capabilities IS NULL OR p.capabilities & 1 = 0)
  AND (o.capabilities IS NULL OR o.capabilities & 1 = 0)
  AND o.object_type = 'event'
Actions

-- Actions
SELECT p.name AS package_name,
       o.name AS action_name,
       o.description
FROM sys.dm_xe_packages AS p
JOIN sys.dm_xe_objects AS o 
     ON p.guid = o.package_guid
WHERE (p.capabilities IS NULL OR p.capabilities & 1 = 0)
  AND (o.capabilities IS NULL OR o.capabilities & 1 = 0)
  AND o.object_type = 'action' 
Targets

--Event获取的数据

select * from sys.dm_xe_object_columns
where object_name = 'lock_acquired' and column_type = 'data'


-- Targets
SELECT p.name AS package_name,
       o.name AS target_name,
       o.description
FROM sys.dm_xe_packages AS p
JOIN sys.dm_xe_objects AS o ON p.guid = o.package_guid
WHERE (p.capabilities IS NULL OR p.capabilities & 1 = 0)
  AND (o.capabilities IS NULL OR o.capabilities & 1 = 0)
  AND o.object_type = 'target'
 


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
--varchar -> varbinary
declare @hexstring varchar(64),@binstring varbinary(64)
set @hexstring = '0x01000200A09EFC30B04A69DE02000000000000000000000000000000000000';
SET @binstring = CONVERT(varbinary(64), @hexstring, 1);
SELECT @binstring
go

--varbinary -> varchar
declare @hexstring varchar(64),@binstring varbinary(64)
set @binstring = 0x01000200A09EFC30B04A69DE02000000000000000000000000000000000000
SET @hexstring = master.dbo.fn_varbintohexstr(@binstring)
SELECT @hexstring


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
一、实现IHttpModule类,见后。

二、修改web.config
添加域名
<appSettings><add key="RootDomain" value=""/></appSettings>
RootDomain cookie域名,若是本地则写空
by design domain names must have at least two dots otherwise browser will say they are invalid 
when working on localhost (!) the cookie-domain must be set to "" or NULL or FALSE instead of "localhost"

增加过滤
<system.web>
<sessionState mode="StateServer" stateNetworkTimeout="10" timeout="120" stateConnectionString="tcpip=127.0.0.1:42424" />
 <httpModules>

      <add name="SessionSharedHttpModule" type="ClassLibrary.BasePage.MakeSessionIDOneOnly,ClassLibrary"/>

    </httpModules>
</system.web>

三、附类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Reflection;
using System.Configuration;

namespace ClassLibrary.BasePage
{
    public class MakeSessionIDOneOnly : IHttpModule
    {
        private string m_RootDomain = string.Empty;

        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            m_RootDomain = ConfigurationManager.AppSettings["RootDomain"];

            Type stateServerSessionProvider = typeof(HttpSessionState).Assembly.GetType("System.Web.SessionState.OutOfProcSessionStateStore");
            FieldInfo uriField = stateServerSessionProvider.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);

            if (uriField == null)
                throw new ArgumentException("UriField was not found");

            uriField.SetValue(null, m_RootDomain);

            context.EndRequest += new System.EventHandler(context_EndRequest);
        }

        void context_EndRequest(object sender, System.EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            for (int i = 0; i < app.Context.Response.Cookies.Count; i++)
            {
                if (app.Context.Response.Cookies[i].Name == "ASP.NET_SessionId")
                {
                    app.Context.Response.Cookies[i].Domain = m_RootDomain;
                }
            }
        }

        #endregion
    }
}






参考:Session共享的解决方案