/****** Object:  Table [dbo].[b_RolesCache]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_RolesCache](
	[roleId] [int] NOT NULL,
	[subRoleId] [int] NOT NULL,
 CONSTRAINT [PK_b_RolesCache] PRIMARY KEY CLUSTERED 
(
	[roleId] ASC,
	[subRoleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Search_ContentStemIndex]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Search_ContentStemIndex](
	[contentId] [int] NOT NULL,
	[languageId] [char](2) NOT NULL,
	[stem] [nvarchar](128) NOT NULL,
	[frequency] [float] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_BX_b_Search_ContentStemIndex] ON [b_Search_ContentStemIndex] 
(
	[stem] ASC,
	[languageId] ASC,
	[contentId] ASC
)
INCLUDE ( [frequency]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_BX_b_Search_ContentStemIndex_Content] ON [b_Search_ContentStemIndex] 
(
	[contentId] ASC,
	[languageId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Search_ContentSites]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Search_ContentSites](
	[contentId] [int] NOT NULL,
	[siteId] [varchar](50) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE CLUSTERED INDEX [IX_BX_b_Search_ContentSiteIds_Content] ON [b_Search_ContentSites] 
(
	[contentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_Search_ContentSites] ON [b_Search_ContentSites] 
(
	[contentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_BX_b_Search_ContentSites_Full] ON [b_Search_ContentSites] 
(
	[siteId] ASC,
	[contentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Search_ContentFileRoles]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Search_ContentFileRoles](
	[contentId] [int] NOT NULL,
	[roleId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Search_Content]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Search_Content](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[moduleId] [varchar](128) NOT NULL,
	[itemGroup] [nvarchar](64) NOT NULL,
	[itemId] [nvarchar](300) NOT NULL,
	[contentDate] [datetime] NOT NULL,
	[title] [nvarchar](max) NULL,
	[body] [ntext] NULL,
	[searchableContent] [ntext] NULL,
	[dateFrom] [datetime] NULL,
	[dateTo] [datetime] NULL,
	[operationLoweredName] [nvarchar](128) NULL,
	[operationModuleId] [varchar](50) NOT NULL,
	[operationExternalId] [varchar](50) NOT NULL,
	[filePermission] [nvarchar](256) NULL,
	[param1] [nvarchar](1024) NULL,
	[param2] [nvarchar](1024) NULL,
 CONSTRAINT [PK_b_search_content] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [IX_BX_b_Search_Content] UNIQUE NONCLUSTERED 
(
	[moduleId] ASC,
	[itemGroup] ASC,
	[itemId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Scheduler]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Scheduler](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](128) NOT NULL,
	[classname] [nvarchar](128) NOT NULL,
	[assembly] [nvarchar](128) NOT NULL,
	[parameters] [nvarchar](max) NOT NULL,
	[starttime] [datetime] NOT NULL,
	[periodic] [bit] NOT NULL,
	[period] [int] NOT NULL,
	[active] [bit] NOT NULL,
	[last_updated] [datetime] NOT NULL,
 CONSTRAINT [PK__b_scheduler__id] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_scheduler_active] ON [b_Scheduler] 
(
	[active] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_b_scheduler_name] ON [b_Scheduler] 
(
	[name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_scheduler_starttime] ON [b_Scheduler] 
(
	[starttime] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Modules]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Modules](
	[ID] [varchar](128) NOT NULL,
	[Type] [nvarchar](256) NULL,
	[DateAdd] [datetime] NOT NULL,
 CONSTRAINT [PK_b_Modules] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_MailerTemplates_Sites]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_MailerTemplates_Sites](
	[templateId] [int] NOT NULL,
	[siteId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_MailerTemplates_Sites] PRIMARY KEY CLUSTERED 
(
	[templateId] ASC,
	[siteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_MailerTemplates_Sites_site] ON [b_MailerTemplates_Sites] 
(
	[siteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_MailerTemplates_Sites_template] ON [b_MailerTemplates_Sites] 
(
	[templateId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_MailerTemplates]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_MailerTemplates](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](128) NOT NULL,
	[last_updated] [datetime] NOT NULL,
	[active] [bit] NOT NULL,
	[email_from] [nvarchar](256) NOT NULL,
	[email_to] [nvarchar](256) NOT NULL,
	[subject] [nvarchar](256) NOT NULL,
	[message] [text] NOT NULL,
	[body_type] [char](4) NOT NULL,
	[bcc] [varchar](256) NOT NULL,
 CONSTRAINT [PK_b_MailerTemplates] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_MailerTemplates_Name] ON [b_MailerTemplates] 
(
	[name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_ForumUser]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_ForumUser](
	[ID] [int] NOT NULL,
	[Posts] [int] NOT NULL,
	[Signature] [nvarchar](400) NULL,
 CONSTRAINT [PK_b_ForumUser] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_MailerEvents]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_MailerEvents](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[template] [nvarchar](128) NOT NULL,
	[site] [nvarchar](128) NOT NULL,
	[parameters] [nvarchar](max) NOT NULL,
	[duplicate] [char](1) NOT NULL,
	[status] [char](1) NOT NULL,
	[last_updated] [datetime] NOT NULL,
	[template_id] [int] NOT NULL,
 CONSTRAINT [PK_b_MailerEvents] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Log]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Log](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[type] [tinyint] NOT NULL,
	[code] [int] NOT NULL,
	[source] [nvarchar](128) NOT NULL,
	[title] [nvarchar](512) NOT NULL,
	[message] [text] NOT NULL,
	[occured] [datetime] NOT NULL,
	[text_type] [char](4) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Template_Condition]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Template_Condition](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[SiteId] [varchar](50) NOT NULL,
	[Condition] [nvarchar](255) NOT NULL,
	[ConditionType] [int] NOT NULL,
	[Sort] [int] NOT NULL,
	[Template] [nvarchar](255) NOT NULL,
 CONSTRAINT [PK_b_Template_Condition] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Site_Domain]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Site_Domain](
	[ID] [varchar](50) NOT NULL,
	[Domain] [varchar](255) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesTasks]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_RolesTasks](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TaskName] [nvarchar](128) NOT NULL,
	[LoweredTaskName] [nvarchar](128) NOT NULL,
	[Comment] [ntext] NULL,
	[Title] [nvarchar](255) NULL,
 CONSTRAINT [PK_b_RolesTasks] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE UNIQUE CLUSTERED INDEX [IX_b_RolesTasks] ON [b_RolesTasks] 
(
	[LoweredTaskName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Language]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Language](
	[ID] [char](2) NOT NULL,
	[Sort] [int] NOT NULL,
	[Default] [bit] NOT NULL,
	[Active] [bit] NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Culture] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_Language] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesOperationsCache]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_RolesOperationsCache](
	[RoleID] [int] NOT NULL,
	[OperationID] [int] NOT NULL,
	[ModuleID] [varchar](50) NOT NULL,
	[ExternalID] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_RolesOperationsCache] PRIMARY KEY CLUSTERED 
(
	[RoleID] ASC,
	[OperationID] ASC,
	[ExternalID] ASC,
	[ModuleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesOperations]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_RolesOperations](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[OperationName] [nvarchar](128) NOT NULL,
	[LoweredOperationName] [nvarchar](128) NOT NULL,
	[OperationType] [nvarchar](128) NULL,
	[ModuleID] [varchar](50) NOT NULL,
	[Comment] [ntext] NULL,
 CONSTRAINT [PK_b_RolesOperations] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE CLUSTERED INDEX [IX_b_RolesOperations] ON [b_RolesOperations] 
(
	[LoweredOperationName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Roles]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Roles](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[RoleName] [nvarchar](128) NOT NULL,
	[LoweredRoleName] [nvarchar](128) NOT NULL,
	[Active] [bit] NOT NULL,
	[Comment] [ntext] NULL,
	[Policy] [xml] NULL,
	[EffectivePolicy] [xml] NULL,
	[Title] [nvarchar](255) NULL,
 CONSTRAINT [PK_b_roles] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE UNIQUE CLUSTERED INDEX [IX_b_Roles] ON [b_Roles] 
(
	[LoweredRoleName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_IBlockType]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlockType](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NULL,
	[HaveSections] [char](1) NOT NULL,
	[Sort] [int] NOT NULL,
 CONSTRAINT [PK_b_IBlock_Type] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Custom_Field]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Custom_Field](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[EntityID] [nvarchar](50) NOT NULL,
	[FieldName] [nvarchar](255) NOT NULL,
	[CustomTypeID] [nvarchar](255) NOT NULL,
	[XmlID] [nvarchar](255) NULL,
	[Sort] [int] NOT NULL,
	[Multiple] [bit] NOT NULL,
	[Mandatory] [bit] NOT NULL,
	[ShowInFilter] [int] NOT NULL,
	[ShowInList] [bit] NOT NULL,
	[EditInList] [bit] NOT NULL,
	[IsSearchable] [bit] NOT NULL,
	[Settings] [nvarchar](max) NULL,
 CONSTRAINT [PK_b_Custom_Fields] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_ComponentEvents]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_ComponentEvents](
	[message] [nvarchar](128) NOT NULL,
	[siteId] [varchar](50) NOT NULL,
	[path] [nvarchar](256) NOT NULL,
	[componentName] [varchar](128) NOT NULL,
	[parameters] [nvarchar](max) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE CLUSTERED INDEX [IX_b_ComponentEvents] ON [b_ComponentEvents] 
(
	[message] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_FileAction]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_FileAction](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FileName] [nvarchar](255) NOT NULL,
	[Folder] [nvarchar](255) NULL,
	[Action] [char](1) NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[ExecDate] [datetime] NULL,
	[SuccessExec] [char](1) NULL,
	[RequestDate] [datetime] NULL,
 CONSTRAINT [PK_b_FileAction] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_File]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_File](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UpdateDate] [datetime] NOT NULL,
	[ModuleId] [varchar](128) NOT NULL,
	[Height] [int] NULL,
	[Width] [int] NULL,
	[FileSize] [int] NOT NULL,
	[ContentType] [varchar](255) NOT NULL,
	[Folder] [varchar](255) NULL,
	[FileName] [nvarchar](255) NOT NULL,
	[FileNameOriginal] [nvarchar](255) NOT NULL,
	[Description] [nvarchar](255) NULL,
 CONSTRAINT [PK_b_File] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_BlogCategory]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_BlogCategory](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](256) NOT NULL,
	[Sort] [int] NOT NULL,
	[XmlId] [varchar](256) NULL,
 CONSTRAINT [PK_b_BlogCategory] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[Search_DeleteAll]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Search_DeleteAll]
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRAN
  	TRUNCATE TABLE b_Search_Content
	TRUNCATE TABLE b_Search_ContentSites
	TRUNCATE TABLE b_Search_ContentFileRoles
	TRUNCATE TABLE b_Search_ContentStemIndex
	TRUNCATE TABLE b_Search_ContentTags
	COMMIT TRAN
END
GO
/****** Object:  Table [dbo].[b_AdvSpace]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_AdvSpace](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Code] [nvarchar](256) NOT NULL,
	[Active] [bit] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[LastModificationAuthorId] [int] NOT NULL,
	[DateLastModified] [datetime] NOT NULL,
	[Name] [nvarchar](256) NOT NULL,
	[Description] [nvarchar](2048) NULL,
	[Sort] [int] NOT NULL,
	[XmlId] [varchar](256) NULL,
 CONSTRAINT [PK_b_AdvSpace] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Search_ContentTags]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Search_ContentTags](
	[contentId] [int] NOT NULL,
	[tagId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_BX_b_Search_ContentTags_Content] ON [b_Search_ContentTags] 
(
	[contentId] ASC,
	[tagId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Search_Tags]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Search_Tags](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[nameLower] [nvarchar](64) NOT NULL,
	[status] [int] NOT NULL,
 CONSTRAINT [PK_b_Search_Tags] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_ForumCategory]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_ForumCategory](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[Sort] [int] NOT NULL,
	[XmlId] [nvarchar](255) NULL,
 CONSTRAINT [PK_b_ForumCategory] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[IBlock_SortSections]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [IBlock_SortSections]
(
	@IBlockId int,
	@SectionId int = 0,
	@Num int = 0,
	@Depth int = 0,
	@Active char(1) = 'Y'
)
AS
BEGIN
	IF (@SectionId > 0)
	BEGIN
		UPDATE b_IBlockSection SET
			UpdateDate = UpdateDate,
			LeftMargin = @Num
		WHERE ID = @SectionId
			AND IBlockId = @IBlockId
	END

	SET @Num = @Num + 1

	DECLARE @TempId int, @TempActive char(1), @TempActive1 char(1), @Depth1 int

	SET @Depth1 = @Depth + 1

	DECLARE tempCursor CURSOR LOCAL FOR 
		SELECT ID, Active
		FROM b_IBlockSection
		WHERE IBlockId = @IBlockId
			AND ((SectionId IS NULL AND @SectionId = 0)
				OR (SectionId = @SectionId AND @SectionId > 0))
		ORDER BY Sort, Name

	OPEN tempCursor

	FETCH NEXT FROM tempCursor INTO @TempId, @TempActive
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		SET @TempActive1 = 'N'
		IF (@Active = 'Y' AND @TempActive = 'Y')
			SET @TempActive1 = 'Y'

		EXEC @Num = IBlock_SortSections @IBlockId, @TempId, @Num, @Depth1, @TempActive1

		FETCH NEXT FROM tempCursor INTO @TempId, @TempActive
	END

	CLOSE tempCursor
	DEALLOCATE tempCursor

	IF (@SectionId > 0)
	BEGIN
		UPDATE b_IBlockSection SET
			UpdateDate = UpdateDate,
			RightMargin = @Num,
			DepthLevel = @Depth,
			ActiveGlobal = @Active
		WHERE ID = @SectionId
			AND IBlockId = @IBlockId
	END

	SET @Num = @Num + 1
	        
	return @Num
END
GO
/****** Object:  UserDefinedFunction [dbo].[Roles_ComputePolicyL]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [Roles_ComputePolicyL] 
	(
	@Policy1 xml,
	@Policy2 xml
	)
RETURNS xml
AS
BEGIN
	DECLARE @Result xml
	SET @Result = NULL

	DECLARE @Policy xml
	SET @Policy = NULL

	DECLARE @PolicySTring1 varchar(1000)
	SELECT @PolicySTring1 = CONVERT(varchar(1000), @Policy1.query('/child::Policy/child::*'))

	DECLARE @PolicySTring2 varchar(1000)
	SELECT @PolicySTring2 = CONVERT(varchar(1000), @Policy2.query('/child::Policy/child::*'))

	IF (@PolicySTring1 IS NULL)
	BEGIN
		SET @PolicySTring1 = ''
	END

	IF (@PolicySTring2 IS NULL)
	BEGIN
		SET @PolicySTring2 = ''
	END

	SELECT @Policy = CONVERT(xml, '<Policy>' + @PolicySTring1 + @PolicySTring2 + '</Policy>')


	SELECT @Result = @Policy.query('
		<Policy>
			{
			if (empty(/Policy/SlidingExpiration/@value)) then ()
			else <SlidingExpiration value="{ min(/Policy/SlidingExpiration/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/SessionTimeout/@value)) then ()
			else <SessionTimeout value="{ min(/Policy/SessionTimeout/@value) cast as xs:integer? }"/>
			}
			{
			if (count(/Policy/SessionIPMask/@value) < 1) then ()
			else 
				if (count(/Policy/SessionIPMask/@value) = 1) then 
					<SessionIPMask value="{/Policy/SessionIPMask[1]/@value}"/>
				else
					if (string-length(string((/Policy/SessionIPMask)[1]/@value)) < string-length(string((/Policy/SessionIPMask)[2]/@value))) then 
						<SessionIPMask value="{/Policy/SessionIPMask[1]/@value}"/>
					else
						<SessionIPMask value="{/Policy/SessionIPMask[2]/@value}"/>
			}
			{
			if (empty(/Policy/MaxStoreNum/@value)) then ()
			else <MaxStoreNum value="{ min(/Policy/MaxStoreNum/@value) cast as xs:integer? }"/>
			}
			{
			if (count(/Policy/StoreIPMask/@value) < 1) then ()
			else 
				if (count(/Policy/StoreIPMask/@value) = 1) then 
					<StoreIPMask value="{/Policy/StoreIPMask[1]/@value}"/>
				else
					if (string-length(string((/Policy/StoreIPMask)[1]/@value)) < string-length(string((/Policy/StoreIPMask)[2]/@value))) then 
						<StoreIPMask value="{/Policy/StoreIPMask[1]/@value}"/>
					else
						<StoreIPMask value="{/Policy/StoreIPMask[2]/@value}"/>
			}
			{
			if (empty(/Policy/StoreTimeout/@value)) then ()
			else <StoreTimeout value="{ min(/Policy/StoreTimeout/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/CheckwordTimeout/@value)) then ()
			else <CheckwordTimeout value="{ min(/Policy/CheckwordTimeout/@value) cast as xs:integer? }"/>
			}
		</Policy>
	')

	RETURN @Result
END
GO
/****** Object:  UserDefinedFunction [dbo].[Roles_ComputePolicy]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [Roles_ComputePolicy] 
	(
	@Policy1 xml,
	@Policy2 xml
	)
RETURNS xml
AS
BEGIN
	DECLARE @Result xml
	SET @Result = NULL

	DECLARE @Policy xml
	SET @Policy = NULL

	DECLARE @PolicySTring1 varchar(1000)
	SELECT @PolicySTring1 = CONVERT(varchar(1000), @Policy1.query('/child::Policy/child::*'))

	DECLARE @PolicySTring2 varchar(1000)
	SELECT @PolicySTring2 = CONVERT(varchar(1000), @Policy2.query('/child::Policy/child::*'))

	IF (@PolicySTring1 IS NULL)
	BEGIN
		SET @PolicySTring1 = ''
	END

	IF (@PolicySTring2 IS NULL)
	BEGIN
		SET @PolicySTring2 = ''
	END

	SELECT @Policy = CONVERT(xml, '<Policy>' + @PolicySTring1 + @PolicySTring2 + '</Policy>')


	SELECT @Result = @Policy.query('
		<Policy>
			{
			if (empty(/Policy/SlidingExpiration/@value)) then ()
			else <SlidingExpiration value="{ ((/Policy/SlidingExpiration)[1]/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/SessionTimeout/@value)) then ()
			else <SessionTimeout value="{ ((/Policy/SessionTimeout)[1]/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/SessionIPMask/@value)) then ()
			else <SessionIPMask value="{ (/Policy/SessionIPMask)[1]/@value }"/>
			}
			{
			if (empty(/Policy/MaxStoreNum/@value)) then ()
			else <MaxStoreNum value="{ ((/Policy/MaxStoreNum)[1]/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/StoreIPMask/@value)) then ()
			else <StoreIPMask value="{ (/Policy/StoreIPMask)[1]/@value }"/>
			}
			{
			if (empty(/Policy/StoreTimeout/@value)) then ()
			else <StoreTimeout value="{ ((/Policy/StoreTimeout)[1]/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/CheckwordTimeout/@value)) then ()
			else <CheckwordTimeout value="{ ((/Policy/CheckwordTimeout)[1]/@value) cast as xs:integer? }"/>
			}
		</Policy>
	')

/*
	SELECT @Result = @Policy.query('
		<Policy>
			{
			if (empty(/Policy/SlidingExpiration/@value)) then ()
			else <SlidingExpiration value="{ min(/Policy/SlidingExpiration/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/SessionTimeout/@value)) then ()
			else <SessionTimeout value="{ min(/Policy/SessionTimeout/@value) cast as xs:integer? }"/>
			}
			{
			if (count(/Policy/SessionIPMask/@value) < 1) then ()
			else 
				if (count(/Policy/SessionIPMask/@value) = 1) then 
					<SessionIPMask value="{/Policy/SessionIPMask[1]/@value}"/>
				else
					if (string-length(string((/Policy/SessionIPMask)[1]/@value)) < string-length(string((/Policy/SessionIPMask)[2]/@value))) then 
						<SessionIPMask value="{/Policy/SessionIPMask[1]/@value}"/>
					else
						<SessionIPMask value="{/Policy/SessionIPMask[2]/@value}"/>
			}
			{
			if (empty(/Policy/MaxStoreNum/@value)) then ()
			else <MaxStoreNum value="{ min(/Policy/MaxStoreNum/@value) cast as xs:integer? }"/>
			}
			{
			if (count(/Policy/StoreIPMask/@value) < 1) then ()
			else 
				if (count(/Policy/StoreIPMask/@value) = 1) then 
					<SessionIPMask value="{/Policy/StoreIPMask[1]/@value}"/>
				else
					if (string-length(string((/Policy/StoreIPMask)[1]/@value)) < string-length(string((/Policy/StoreIPMask)[2]/@value))) then 
						<SessionIPMask value="{/Policy/StoreIPMask[1]/@value}"/>
					else
						<SessionIPMask value="{/Policy/StoreIPMask[2]/@value}"/>
			}
			{
			if (empty(/Policy/StoreTimeout/@value)) then ()
			else <StoreTimeout value="{ min(/Policy/StoreTimeout/@value) cast as xs:integer? }"/>
			}
			{
			if (empty(/Policy/CheckwordTimeout/@value)) then ()
			else <CheckwordTimeout value="{ min(/Policy/CheckwordTimeout/@value) cast as xs:integer? }"/>
			}
		</Policy>
	')
*/
	RETURN @Result
END
GO
/****** Object:  Table [dbo].[b_Forum]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Forum](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Active] [bit] NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[DateCreate] [datetime] NOT NULL,
	[Description] [nvarchar](255) NULL,
	[CategoryId] [int] NOT NULL,
	[Sort] [int] NOT NULL,
	[Topics] [int] NOT NULL,
	[QueuedTopics] [int] NOT NULL,
	[Replies] [int] NOT NULL,
	[QueuedReplies] [int] NOT NULL,
	[Code] [nvarchar](255) NULL,
	[XmlId] [varchar](255) NULL,
	[AllowBBCode] [bit] NOT NULL,
	[AllowSmiles] [bit] NOT NULL,
	[LastPostId] [bigint] NOT NULL,
	[LastPostDate] [datetime] NULL,
	[LastPosterId] [int] NOT NULL,
	[LastPosterName] [nvarchar](256) NULL,
	[IndexContent] [bit] NOT NULL,
 CONSTRAINT [PK_b_Forum] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_UsersOptions]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_UsersOptions](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [int] NULL,
	[Category] [nvarchar](50) NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[Value] [nvarchar](max) NULL,
	[Common] [char](1) NOT NULL,
 CONSTRAINT [PK_b_UsersOptions] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_UsersOptions] ON [b_UsersOptions] 
(
	[Category] ASC,
	[Name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_ForumPost]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_ForumPost](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[TopicId] [int] NOT NULL,
	[ForumId] [int] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[ParentPostId] [bigint] NOT NULL,
	[AuthorName] [nvarchar](256) NOT NULL,
	[AuthorEmail] [nvarchar](256) NULL,
	[AuthorIp] [varchar](255) NULL,
	[Post] [nvarchar](max) NOT NULL,
	[Approved] [bit] NOT NULL,
	[DateCreate] [datetime] NOT NULL,
	[AllowSmiles] [bit] NOT NULL,
	[XmlId] [varchar](255) NULL,
 CONSTRAINT [PK_b_ForumPost] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumPost_ForumId] ON [b_ForumPost] 
(
	[ForumId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumPost_PostList] ON [b_ForumPost] 
(
	[TopicId] ASC,
	[ForumId] ASC,
	[Approved] ASC,
	[ID] ASC,
	[AuthorId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumPost_TopicId] ON [b_ForumPost] 
(
	[TopicId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Site]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Site](
	[ID] [varchar](50) NOT NULL,
	[Sort] [int] NOT NULL,
	[Default] [bit] NOT NULL,
	[Active] [bit] NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Directory] [nvarchar](50) NOT NULL,
	[LanguageId] [char](2) NOT NULL,
	[DocRoot] [nvarchar](255) NULL,
	[DomainLimited] [bit] NOT NULL,
	[ServerName] [varchar](255) NULL,
	[SiteName] [nvarchar](255) NULL,
	[Email] [varchar](255) NULL,
	[Culture] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_Site] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_IBlockTypeLang]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlockTypeLang](
	[TypeId] [int] NOT NULL,
	[LanguageId] [char](2) NOT NULL,
	[Name] [nvarchar](128) NOT NULL,
	[SectionName] [nvarchar](128) NULL,
	[ElementName] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_b_IBlock_TypeLang] PRIMARY KEY CLUSTERED 
(
	[TypeId] ASC,
	[LanguageId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesTasksInTasks]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_RolesTasksInTasks](
	[TaskID] [int] NOT NULL,
	[SubTaskID] [int] NOT NULL,
 CONSTRAINT [PK_b_RolesTasksInTasks] PRIMARY KEY CLUSTERED 
(
	[TaskID] ASC,
	[SubTaskID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_RolesTasksInOperations]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_RolesTasksInOperations](
	[TaskID] [int] NOT NULL,
	[OperationID] [int] NOT NULL,
 CONSTRAINT [PK_b_RolesTasksInOperations] PRIMARY KEY CLUSTERED 
(
	[TaskID] ASC,
	[OperationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_RolesInTasks]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_RolesInTasks](
	[RoleID] [int] NOT NULL,
	[TaskID] [int] NOT NULL,
	[ModuleID] [varchar](50) NOT NULL,
	[ExternalID] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_RolesInTasks] PRIMARY KEY CLUSTERED 
(
	[RoleID] ASC,
	[TaskID] ASC,
	[ExternalID] ASC,
	[ModuleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesInOperations]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_RolesInOperations](
	[RoleID] [int] NOT NULL,
	[OperationID] [int] NOT NULL,
	[ModuleID] [varchar](50) NOT NULL,
	[ExternalID] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_RolesInOperations] PRIMARY KEY CLUSTERED 
(
	[RoleID] ASC,
	[OperationID] ASC,
	[ExternalID] ASC,
	[ModuleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_RolesInRoles]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_RolesInRoles](
	[RoleID] [int] NOT NULL,
	[SubRoleID] [int] NOT NULL,
 CONSTRAINT [PK_b_RolesInRoles] PRIMARY KEY CLUSTERED 
(
	[RoleID] ASC,
	[SubRoleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_AdvBannerInRole]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_AdvBannerInRole](
	[BannerId] [int] NOT NULL,
	[RoleId] [int] NOT NULL,
 CONSTRAINT [PK_b_AdvBannerInRole] PRIMARY KEY CLUSTERED 
(
	[BannerId] ASC,
	[RoleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_UsersInRoles]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_UsersInRoles](
	[UserID] [int] NOT NULL,
	[RoleID] [int] NOT NULL,
	[ActiveFrom] [datetime] NULL,
	[ActiveTo] [datetime] NULL,
 CONSTRAINT [PK_b_UsersInRoles] PRIMARY KEY CLUSTERED 
(
	[UserID] ASC,
	[RoleID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_IBlock]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlock](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TypeId] [int] NOT NULL,
	[UpdateDate] [datetime] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[Code] [nvarchar](128) NULL,
	[Name] [nvarchar](255) NOT NULL,
	[Active] [char](1) NOT NULL,
	[Sort] [int] NOT NULL,
	[ImageId] [int] NULL,
	[Description] [nvarchar](max) NULL,
	[DescriptionType] [char](1) NOT NULL,
	[XmlId] [varchar](255) NULL,
	[SectionsName] [nvarchar](255) NULL,
	[SectionName] [nvarchar](255) NULL,
	[ElementsName] [nvarchar](255) NULL,
	[ElementName] [nvarchar](255) NULL,
	[IndexContent] [char](1) NOT NULL,
	[XmlCaptionsInfo] [xml] NULL,
 CONSTRAINT [PK_b_IBlock] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_IBlock] ON [b_IBlock] 
(
	[TypeId] ASC,
	[Active] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Custom_Field_Localization]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Custom_Field_Localization](
	[FieldID] [int] NOT NULL,
	[LanguageId] [char](2) NOT NULL,
	[EditFormLabel] [nvarchar](255) NULL,
	[ListColumnLabel] [nvarchar](255) NULL,
	[ListFilterLabel] [nvarchar](255) NULL,
	[ErrorMessage] [nvarchar](255) NULL,
	[HelpMessage] [nvarchar](255) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Custom_Field_Enum]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_Custom_Field_Enum](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FieldID] [int] NOT NULL,
	[Value] [nvarchar](255) NOT NULL,
	[Default] [bit] NOT NULL,
	[Sort] [int] NOT NULL,
	[XmlID] [nvarchar](255) NULL,
 CONSTRAINT [PK_b_Custom_Field_Enum] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_AdvBanner]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_AdvBanner](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Code] [nvarchar](256) NOT NULL,
	[Active] [bit] NOT NULL,
	[SpaceId] [int] NOT NULL,
	[Status] [tinyint] NOT NULL,
	[Weight] [int] NOT NULL,
	[EnableFixedRotation] [bit] NOT NULL,
	[EnableUniformRotationVelocity] [bit] NOT NULL,
	[EnableRedirectionCount] [bit] NOT NULL,
	[EnableRotationForVisitorRoles] [bit] NOT NULL,
	[DisplayCount] [int] NOT NULL,
	[VisitorCount] [int] NOT NULL,
	[RedirectionCount] [int] NOT NULL,
	[MaxVisitorCount] [int] NOT NULL,
	[MaxDisplayCount] [int] NOT NULL,
	[MaxDisplayCountPerVisitor] [int] NOT NULL,
	[MaxRedirectionCount] [int] NOT NULL,
	[DateOfRotationStart] [datetime] NULL,
	[DateOfRotationFinish] [datetime] NULL,
	[DateOfFirstDisplay] [datetime] NULL,
	[DateOfLastDisplay] [datetime] NULL,
	[Name] [nvarchar](256) NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateLastModified] [datetime] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[LastModificationAuthorId] [int] NOT NULL,
	[ContentType] [tinyint] NOT NULL,
	[ContentFileId] [int] NULL,
	[LinkUrl] [nvarchar](2048) NULL,
	[LinkTarget] [nvarchar](64) NULL,
	[ToolTip] [nvarchar](512) NULL,
	[FlashWMode] [nvarchar](128) NULL,
	[FlashDynamicCreation] [bit] NULL,
	[FlashVersion] [nvarchar](128) NULL,
	[FlashAltImageFileId] [int] NULL,
	[FlashUseCustomUrl] [bit] NULL,
	[TextContentType] [tinyint] NULL,
	[TextContent] [nvarchar](4000) NULL,
	[NotifyStatusChange] [bit] NOT NULL,
	[RequiredPathList] [nvarchar](4000) NULL,
	[IgnoredPathList] [nvarchar](4000) NULL,
	[Description] [nvarchar](2048) NULL,
	[XmlId] [varchar](256) NULL,
 CONSTRAINT [PK_b_AdvBanner] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_Users]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Users](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [nvarchar](256) NOT NULL,
	[LoweredUserName] [nvarchar](256) NOT NULL,
	[Password] [nvarchar](128) NOT NULL,
	[PasswordFormat] [int] NOT NULL,
	[PasswordSalt] [nvarchar](128) NOT NULL,
	[ProviderName] [nvarchar](128) NOT NULL,
	[LoweredProviderName] [nvarchar](128) NOT NULL,
	[LastActivityDate] [datetime] NOT NULL,
	[Email] [nvarchar](256) NULL,
	[LoweredEmail] [nvarchar](256) NULL,
	[PasswordQuestion] [nvarchar](256) NULL,
	[PasswordAnswer] [nvarchar](128) NULL,
	[CheckWord] [nvarchar](50) NULL,
	[CheckWordWindowStart] [datetime] NULL,
	[IsApproved] [bit] NOT NULL,
	[IsLockedOut] [bit] NOT NULL,
	[CreationDate] [datetime] NOT NULL,
	[LastLoginDate] [datetime] NOT NULL,
	[LastPasswordChangedDate] [datetime] NOT NULL,
	[LastLockoutDate] [datetime] NOT NULL,
	[FailedPasswordAttemptCount] [int] NOT NULL,
	[FailedPasswordAttemptWindowStart] [datetime] NOT NULL,
	[FailedPasswordAnswerAttemptCount] [int] NOT NULL,
	[FailedPasswordAnswerAttemptWindowStart] [datetime] NOT NULL,
	[Comment] [ntext] NULL,
	[FirstName] [nvarchar](50) NULL,
	[SecondName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[SiteID] [varchar](50) NULL,
	[BirthdayDate] [datetime] NULL,
	[DisplayName] [nvarchar](256) NULL,
	[ImageId] [int] NULL,
	[Gender] [char](1) NULL,
 CONSTRAINT [PK_b_users] PRIMARY KEY NONCLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE CLUSTERED INDEX [IX_b_Users] ON [b_Users] 
(
	[LoweredProviderName] ASC,
	[LoweredUserName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Options]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Options](
	[EntityId] [nvarchar](50) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Value] [nvarchar](max) NULL,
	[Description] [nvarchar](255) NULL,
	[SiteId] [varchar](50) NULL,
 CONSTRAINT [IX_b_Options] UNIQUE NONCLUSTERED 
(
	[EntityId] ASC,
	[Name] ASC,
	[SiteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_IBlockInSite]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlockInSite](
	[IBlockId] [int] NOT NULL,
	[SiteId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_IBlock_Site] PRIMARY KEY CLUSTERED 
(
	[IBlockId] ASC,
	[SiteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_AdvBannerInSite]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_AdvBannerInSite](
	[BannerId] [int] NOT NULL,
	[SiteId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_AdvBannerInSite] PRIMARY KEY CLUSTERED 
(
	[BannerId] ASC,
	[SiteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_BlogCategoryInSite]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_BlogCategoryInSite](
	[CategoryId] [int] NOT NULL,
	[SiteId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_BlogCategoryInSite] PRIMARY KEY CLUSTERED 
(
	[CategoryId] ASC,
	[SiteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_ForumInSite]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_ForumInSite](
	[ForumId] [int] NOT NULL,
	[SiteId] [varchar](50) NOT NULL,
 CONSTRAINT [PK_b_ForumInSite] PRIMARY KEY CLUSTERED 
(
	[ForumId] ASC,
	[SiteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[b_BlogInCategory]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_BlogInCategory](
	[BlogId] [int] NOT NULL,
	[CategoryId] [int] NOT NULL,
 CONSTRAINT [PK_b_BlogInCategory] PRIMARY KEY CLUSTERED 
(
	[BlogId] ASC,
	[CategoryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_Blog]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_Blog](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](256) NOT NULL,
	[Description] [nvarchar](2048) NULL,
	[OwnerId] [int] NOT NULL,
	[Active] [bit] NOT NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateLastPosted] [datetime] NOT NULL,
	[Slug] [nvarchar](128) NOT NULL,
	[Sort] [int] NOT NULL,
	[NotifyOfComments] [bit] NOT NULL,
	[XmlId] [varchar](256) NULL,
	[PostCount] [int] NULL,
	[CommentCount] [int] NULL,
 CONSTRAINT [PK_b_Blog] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_Blog_Active] ON [b_Blog] 
(
	[Active] ASC,
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_Blog_NewBlogList] ON [b_Blog] 
(
	[DateCreated] DESC,
	[Name] ASC,
	[Active] ASC
)
INCLUDE ( [ID],
[Description],
[OwnerId],
[DateLastPosted],
[Slug],
[Sort],
[NotifyOfComments],
[XmlId],
[PostCount],
[CommentCount]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_Blog_OwnerId] ON [b_Blog] 
(
	[OwnerId] ASC,
	[Active] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_Blog_PostCountList] ON [b_Blog] 
(
	[PostCount] DESC,
	[Name] ASC,
	[Active] ASC
)
INCLUDE ( [ID],
[Description],
[OwnerId],
[DateCreated],
[DateLastPosted],
[Slug],
[Sort],
[NotifyOfComments],
[XmlId],
[CommentCount]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_BlogPost]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_BlogPost](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[BlogId] [int] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[AuthorName] [nvarchar](256) NOT NULL,
	[AuthorEmail] [nvarchar](320) NULL,
	[AuthorIP] [varchar](64) NULL,
	[Title] [nvarchar](512) NULL,
	[Contents] [nvarchar](max) NULL,
	[DateCreated] [datetime] NOT NULL,
	[IsPublished] [bit] NOT NULL,
	[DatePublished] [datetime] NOT NULL,
	[NotifyOfComments] [bit] NOT NULL,
	[CommentCount] [int] NOT NULL,
	[ViewCount] [int] NOT NULL,
	[XmlId] [varchar](256) NULL,
 CONSTRAINT [PK_b_BlogPost] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_AuthorId] ON [b_BlogPost] 
(
	[AuthorId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_BlogId] ON [b_BlogPost] 
(
	[BlogId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_CommentedPosts] ON [b_BlogPost] 
(
	[IsPublished] ASC,
	[DatePublished] ASC,
	[CommentCount] ASC,
	[BlogId] ASC,
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_NewPosts] ON [b_BlogPost] 
(
	[IsPublished] ASC,
	[DatePublished] ASC,
	[BlogId] ASC,
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_PopularPosts] ON [b_BlogPost] 
(
	[ViewCount] ASC,
	[DatePublished] ASC,
	[IsPublished] ASC,
	[ID] ASC,
	[BlogId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogPost_PostList] ON [b_BlogPost] 
(
	[BlogId] ASC,
	[IsPublished] ASC,
	[DatePublished] ASC
)
INCLUDE ( [ID]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_BlogComment]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_BlogComment](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[PostId] [int] NOT NULL,
	[BlogId] [int] NOT NULL,
	[ParentId] [int] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[AuthorName] [nvarchar](256) NOT NULL,
	[AuthorEmail] [nvarchar](320) NULL,
	[AuthorWebsite] [nvarchar](2048) NULL,
	[AuthorIP] [varchar](64) NULL,
	[Contents] [nvarchar](max) NULL,
	[DateCreated] [datetime] NOT NULL,
	[DateModified] [datetime] NOT NULL,
	[IsApproved] [bit] NOT NULL,
	[MarkedForDelete] [bit] NOT NULL,
	[LeftMargin] [int] NOT NULL,
	[RightMargin] [int] NOT NULL,
	[DepthLevel] [int] NOT NULL,
	[RootNodeIndex] [int] NOT NULL,
	[LiveRootNodeIndex] [int] NULL,
	[XmlId] [varchar](256) NULL,
	[AuthorBlogId] [int] NOT NULL,
 CONSTRAINT [PK_b_BlogComment] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogComment_AuthorBlogId] ON [b_BlogComment] 
(
	[AuthorBlogId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogComment_BlogId] ON [b_BlogComment] 
(
	[MarkedForDelete] ASC,
	[BlogId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogComment_CommentList] ON [b_BlogComment] 
(
	[PostId] ASC,
	[MarkedForDelete] ASC,
	[ID] ASC
)
INCLUDE ( [ParentId],
[LiveRootNodeIndex]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_BlogComment_CommentTree] ON [b_BlogComment] 
(
	[PostId] ASC,
	[LiveRootNodeIndex] ASC,
	[AuthorId] ASC,
	[AuthorBlogId] ASC,
	[LeftMargin] ASC
)
INCLUDE ( [ID],
[BlogId],
[ParentId],
[AuthorName],
[AuthorEmail],
[AuthorWebsite],
[AuthorIP],
[Contents],
[DateCreated],
[DateModified],
[IsApproved],
[MarkedForDelete],
[RightMargin],
[DepthLevel],
[RootNodeIndex],
[XmlId]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_BlogUser]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_BlogUser](
	[ID] [int] NOT NULL,
	[PostCount] [int] NOT NULL,
 CONSTRAINT [PK_b_BlogUser] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_UsersControlsOptions]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_UsersControlsOptions](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserID] [int] NOT NULL,
	[Common] [nvarchar](1) NOT NULL,
	[ControlID] [nvarchar](128) NOT NULL,
	[PageID] [nvarchar](256) NOT NULL,
	[Parameters] [nvarchar](max) NULL,
 CONSTRAINT [IID] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IUserID] ON [b_UsersControlsOptions] 
(
	[UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_AdvBannerWeekScheduleHourSpan]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_AdvBannerWeekScheduleHourSpan](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[BannerId] [int] NOT NULL,
	[FromHourOfWeek] [tinyint] NOT NULL,
	[TillHourOfWeek] [tinyint] NOT NULL,
 CONSTRAINT [PK_b_AdvBannerRotationPeriod] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_AdvBannerUrlTemplate]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_AdvBannerUrlTemplate](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[BannerId] [int] NOT NULL,
	[IsPermitted] [bit] NOT NULL,
	[UrlTemplate] [nvarchar](2048) NOT NULL,
 CONSTRAINT [PK_b_AdvBannerUrlTemplate] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_IBlockSection]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlockSection](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UpdateDate] [datetime] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[IBlockId] [int] NOT NULL,
	[SectionId] [int] NULL,
	[Active] [char](1) NOT NULL,
	[ActiveGlobal] [char](1) NOT NULL,
	[Sort] [int] NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[ImageId] [int] NULL,
	[DetailImageId] [int] NULL,
	[LeftMargin] [int] NULL,
	[RightMargin] [int] NULL,
	[DepthLevel] [int] NULL,
	[Description] [nvarchar](max) NULL,
	[DescriptionType] [char](1) NOT NULL,
	[Code] [varchar](255) NULL,
	[XmlId] [varchar](255) NULL,
 CONSTRAINT [PK_b_IBlockSection] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_IBlockSection] ON [b_IBlockSection] 
(
	[IBlockId] ASC,
	[SectionId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_IBlockSection_1] ON [b_IBlockSection] 
(
	[IBlockId] ASC,
	[LeftMargin] ASC,
	[RightMargin] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_IBlockElement]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_IBlockElement](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UpdateDate] [datetime] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[ModifiedBy] [int] NULL,
	[CreatedBy] [int] NULL,
	[IBlockID] [int] NOT NULL,
	[Active] [char](1) NOT NULL,
	[ActiveFromDate] [datetime] NULL,
	[ActiveToDate] [datetime] NULL,
	[Sort] [int] NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[PreviewImageId] [int] NULL,
	[PreviewText] [nvarchar](max) NULL,
	[PreviewTextType] [char](1) NOT NULL,
	[DetailImageId] [int] NULL,
	[DetailText] [nvarchar](max) NULL,
	[DetailTextType] [char](1) NOT NULL,
	[XmlId] [varchar](255) NULL,
	[Code] [varchar](255) NULL,
	[Tags] [nvarchar](1024) NULL,
	[ViewsCount] [int] NOT NULL,
 CONSTRAINT [PK_b_IBlockElement] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_BX_b_IBlockElement_IBlock] ON [b_IBlockElement] 
(
	[IBlockID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_IBlockElementInSection]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [b_IBlockElementInSection](
	[SectionId] [int] NOT NULL,
	[ElementId] [int] NOT NULL,
 CONSTRAINT [PK_b_IBlockElementInSection] PRIMARY KEY CLUSTERED 
(
	[SectionId] ASC,
	[ElementId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[b_ForumTopic]    Script Date: 10/01/2009 19:30:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [b_ForumTopic](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ForumId] [int] NOT NULL,
	[Name] [nvarchar](255) NOT NULL,
	[Description] [nvarchar](255) NULL,
	[DateCreate] [datetime] NOT NULL,
	[AuthorId] [int] NOT NULL,
	[AuthorName] [nvarchar](256) NOT NULL,
	[Closed] [bit] NOT NULL,
	[Approved] [bit] NOT NULL,
	[StickyIndex] [int] NOT NULL,
	[Replies] [int] NOT NULL,
	[QueuedReplies] [int] NOT NULL,
	[Views] [bigint] NOT NULL,
	[MovedTo] [int] NOT NULL,
	[FirstPostId] [bigint] NOT NULL,
	[LastPostId] [bigint] NOT NULL,
	[LastPostDate] [datetime] NULL,
	[LastPosterId] [int] NOT NULL,
	[LastPosterName] [nvarchar](256) NULL,
	[XmlId] [varchar](255) NULL,
 CONSTRAINT [PK_b_ForumTopic] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumTopic_ForumId] ON [b_ForumTopic] 
(
	[ForumId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumTopic_TopicCount] ON [b_ForumTopic] 
(
	[ForumId] ASC,
	[Approved] ASC,
	[MovedTo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_b_ForumTopic_TopicList] ON [b_ForumTopic] 
(
	[ForumId] ASC,
	[Approved] ASC,
	[StickyIndex] ASC,
	[LastPostDate] ASC,
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[Roles_FillRolesCache]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_FillRolesCache]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	BEGIN TRANSACTION

	DELETE FROM b_RolesCache;
	IF (@@ERROR <> 0)
    BEGIN
        ROLLBACK TRANSACTION
        RETURN (-1)
    END;

	WITH rolesCache(roleId, subRoleId)
	AS
	(
		SELECT ID, ID FROM [dbo].[b_Roles]
		UNION ALL
		SELECT c.roleId, r.SubRoleID  FROM
			rolesCache c inner join b_RolesInRoles r 
			ON c.subRoleId = r.RoleID
	) 
	INSERT INTO b_RolesCache 
	SELECT DISTINCT roleId, subRoleId FROM rolesCache;

	IF (@@ERROR <> 0)
    BEGIN
        ROLLBACK TRANSACTION
        RETURN (-1)
    END;

	COMMIT TRANSACTION
END
GO
/****** Object:  StoredProcedure [dbo].[Search_DeleteContent]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Search_DeleteContent] 
	@id int = -1 
AS
BEGIN
	DELETE FROM b_Search_Content WHERE id = @id;	
	SET NOCOUNT ON;
	DELETE FROM b_Search_ContentSites WHERE contentId = @id;
	DELETE FROM b_Search_ContentFileRoles WHERE contentId = @id;
	DELETE FROM b_Search_ContentTags WHERE contentId = @id
END
GO
/****** Object:  StoredProcedure [dbo].[Forum_SynchronizeUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Forum_SynchronizeUser]
	@UsersId varchar(2000)
AS
BEGIN

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @Pos int, @NextPos int, @Id nvarchar(15)
	DECLARE @Posts int
	SET @Pos = 1
	
	WHILE (@Pos <= LEN(@UsersId))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @UsersId,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@UsersId) + 1
			
		SELECT @Id = RTRIM(LTRIM(SUBSTRING(@UsersId, @Pos, @NextPos - @Pos)))
		
		SELECT	@Posts = COUNT(ID)
		FROM	b_ForumPost Post
		WHERE	Post.AuthorId = @Id AND 
			Post.Approved = 1 AND 
			Post.ForumId IN (SELECT ID FROM b_Forum WHERE Active = 1)
		
		UPDATE b_ForumUser SET Posts = @Posts WHERE ID = @Id
		IF @@ROWCOUNT = 0 AND NOT EXISTS(SELECT ID FROM b_ForumUser WHERE ID = @Id)
			INSERT INTO b_ForumUser (ID, Posts) VALUES(@Id, @Posts)
		
		SET @Pos = @NextPos + 1
	END

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
	
END
GO
/****** Object:  StoredProcedure [dbo].[Forum_SynchronizeTopic]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Forum_SynchronizeTopic] 
	@TopicId int = 0
AS
BEGIN
	
	DECLARE @FirstPostId bigint
	SET @FirstPostId = 0
	
	SELECT
		@FirstPostId = FirstPostId
	FROM 
		b_ForumTopic
	WHERE 
		ID = @TopicId
	
	IF @@ROWCOUNT = 0
		RETURN
	
	DECLARE @ApprovedPosts int, @QueuedPosts int, @LastPostDate datetime, @LastPostId int, @LastPosterId int, @LastPosterName nvarchar(256)

	SELECT 
		@ApprovedPosts = SUM(CASE POST.Approved WHEN 1 THEN 1 ELSE 0 END),
		@QueuedPosts = SUM(CASE POST.Approved WHEN 0 THEN 1 ELSE 0 END)
	FROM 
		b_ForumPost POST
	WHERE 
		POST.TopicId = @TopicId AND POST.ID <> @FirstPostId  

	SELECT TOP 1
		@LastPostDate = POST.DateCreate,
		@LastPostId = POST.ID, 
		@LastPosterId = POST.AuthorId, 
		@LastPosterName = POST.AuthorName
	FROM
		b_ForumPost POST
	WHERE
		POST.TopicId = @TopicId AND POST.Approved = 1
	ORDER BY
		POST.ID DESC
	
	IF @ApprovedPosts IS NULL SET @ApprovedPosts = 0
	IF @QueuedPosts IS NULL SET @QueuedPosts = 0	
	IF @LastPostId IS NULL SET @LastPostId = 0
	IF @LastPosterId IS NULL SET @LastPosterId = 0	

	UPDATE 
		b_ForumTopic
	SET
		Replies = @ApprovedPosts,
		QueuedReplies = @QueuedPosts,
		LastPostDate = @LastPostDate,
		LastPostId = @LastPostId, 
		LastPosterId = @LastPosterId, 
		LastPosterName = @LastPosterName
	WHERE
		ID = @TopicId
END
GO
/****** Object:  StoredProcedure [dbo].[Forum_SynchronizeForum]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Forum_SynchronizeForum]
	@ForumId int 
AS
BEGIN
	DECLARE @AllTopics int, @ApprovedTopics int, @Replies int, @QueuedReplies int

	SELECT
		@AllTopics = COUNT(TOPIC.ID), 
		@ApprovedTopics = SUM(CASE TOPIC.Approved WHEN 1 THEN 1 ELSE 0 END), 
		@Replies = SUM(CASE TOPIC.Approved WHEN 1 THEN TOPIC.Replies ELSE 0 END),
		@QueuedReplies = SUM(TOPIC.QueuedReplies)
	FROM 
		b_ForumTopic TOPIC
	WHERE 
		TOPIC.ForumId = @ForumId AND TOPIC.MovedTo = 0

	IF @ApprovedTopics IS NULL SET @ApprovedTopics = 0
	IF @Replies IS NULL SET @Replies = 0
	IF @QueuedReplies IS NULL SET @QueuedReplies = 0	
	
	DECLARE @LastPostDate datetime, @LastPostId int, @LastPosterId int, @LastPosterName nvarchar(256)

	SELECT TOP 1
		@LastPostDate = TOPIC.LastPostDate,
		@LastPostId = TOPIC.LastPostId, 
		@LastPosterId = TOPIC.LastPosterId, 
		@LastPosterName = TOPIC.LastPosterName
	FROM
		b_ForumTopic TOPIC
	WHERE
		TOPIC.ForumId = @ForumId AND TOPIC.MovedTo = 0 AND TOPIC.Approved = 1
	ORDER BY
		TOPIC.LastPostDate DESC

	IF @LastPostId IS NULL SET @LastPostId = 0
	IF @LastPosterId IS NULL SET @LastPosterId = 0	

	UPDATE 
		b_Forum
	SET
		Replies = @Replies,
		QueuedReplies = @QueuedReplies,
		Topics = @ApprovedTopics,
		QueuedTopics = @AllTopics - @ApprovedTopics,
		LastPostDate = @LastPostDate,
		LastPostId = @LastPostId, 
		LastPosterId = @LastPosterId, 
		LastPosterName = @LastPosterName
	WHERE
		ID = @ForumId
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_CreateTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_CreateTask]
    @TaskName nvarchar(128),
    @TaskTitle nvarchar(255) = null,
    @Comment ntext = null,
    @TaskId int OUTPUT
AS
BEGIN
	SELECT @TaskId = NULL

    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    IF (EXISTS( SELECT ID FROM dbo.b_RolesTasks WHERE LoweredTaskName = LOWER(@TaskName) ))
    BEGIN
        SET @ErrorCode = 8
        GOTO Cleanup
    END

    INSERT INTO dbo.b_RolesTasks(TaskName, Title, LoweredTaskName, Comment)
         VALUES (@TaskName, @TaskTitle, LOWER(@TaskName), @Comment)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	SELECT @TaskId = @@IDENTITY

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetTasksInRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetTasksInRole]
	@RoleName nvarchar(256),
	@ModuleId varchar(128) = NULL,
	@ExternalId varchar(128) = NULL
AS
BEGIN

	DECLARE @RoleId int
	SELECT @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
	 RETURN(2)

	SELECT r.TaskName
	FROM dbo.b_RolesTasks r, dbo.b_RolesInTasks rr
	WHERE r.ID = rr.TaskID
		AND @RoleId = rr.RoleID
		AND (@ModuleId IS NULL AND rr.ModuleID = ''
			OR @ModuleId IS NOT NULL AND rr.ModuleID = @ModuleId AND rr.ExternalID = @ExternalId)
	ORDER BY r.TaskName

	RETURN(0)

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetTasksInTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetTasksInTask]
	@TaskName nvarchar(128)
AS
BEGIN

	DECLARE @TaskId int
	SELECT @TaskId = NULL

	SELECT @TaskId = ID
	FROM dbo.b_RolesTasks
	WHERE LOWER(@TaskName) = LoweredTaskName

	IF (@TaskId IS NULL)
	 RETURN(9)

	SELECT r.TaskName
	FROM dbo.b_RolesTasks r, dbo.b_RolesTasksInTasks rr
	WHERE r.ID = rr.SubTaskID
		AND @TaskId = rr.TaskID
	ORDER BY r.TaskName

	RETURN(0)

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetTaskByID]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetTaskByID]
	@TaskId int
AS
BEGIN

	SELECT r.TaskName, r.ID, r.Comment,
		(
		SELECT COUNT(*) 
		FROM b_RolesTasksInTasks uir 
		WHERE uir.TaskID = r.ID 
		) as TasksCount,
		(
		SELECT COUNT(*) 
		FROM b_RolesTasksInOperations rir 
		WHERE rir.TaskID = r.ID 
		) as OperationsCount
	FROM dbo.b_RolesTasks r
	WHERE r.ID = @TaskId

    IF (@@ROWCOUNT = 0)
       RETURN -1

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetAllTasks]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetAllTasks]
	@PageIndex int = 0,
	@PageSize int = -1,
	@ModuleId varchar(128) = NULL
AS
BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @TotalRecords int
	
	IF (@PageSize = -1)
	BEGIN
		SELECT r.TaskName
		FROM dbo.b_RolesTasks r
		WHERE (@ModuleId IS NULL 
			OR @ModuleId IS NOT NULL AND r.ID IN (
				SELECT rto.TaskID
				FROM b_RolesTasksInOperations rto
					INNER JOIN b_RolesOperations ro ON (rto.OperationID = ro.ID)
				WHERE ro.ModuleID = @ModuleId
			)
		)
		ORDER BY r.TaskName
		
		RETURN 0
	END
	ELSE
	BEGIN
		SET @PageLowerBound = @PageSize * @PageIndex
		SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

		CREATE TABLE #PageIndexForTasks
		(
			IndexId int IDENTITY (0, 1) NOT NULL,
			TaskId int
		)

		INSERT INTO #PageIndexForTasks (TaskId)
		SELECT r.ID
		FROM dbo.b_RolesTasks r
		ORDER BY r.TaskName

		SELECT @TotalRecords = @@ROWCOUNT

		SELECT r.TaskName, r.ID, r.Comment,
			(
			SELECT COUNT(*) 
			FROM b_RolesTasksInTasks uir 
			WHERE uir.TaskID = r.ID 
			) as TasksCount,
			(
			SELECT COUNT(*) 
			FROM b_RolesTasksInOperations rir 
			WHERE rir.TaskID = r.ID 
			) as OperationsCount
		FROM dbo.b_RolesTasks r, #PageIndexForTasks p
		WHERE r.ID = p.TaskId
			AND p.IndexId >= @PageLowerBound
			AND p.IndexId <= @PageUpperBound
		ORDER BY r.TaskName
	END

	RETURN @TotalRecords
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetOperationsInTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetOperationsInTask]
	@TaskName nvarchar(128)
AS
BEGIN

	DECLARE @TaskId int
	SELECT @TaskId = NULL

	SELECT @TaskId = ID
	FROM dbo.b_RolesTasks
	WHERE LOWER(@TaskName) = LoweredTaskName

	IF (@TaskId IS NULL)
	 RETURN(9)

	SELECT r.OperationName
	FROM dbo.b_RolesOperations r, dbo.b_RolesTasksInOperations rr
	WHERE r.ID = rr.OperationID
		AND @TaskId = rr.TaskID
	ORDER BY r.OperationName

	RETURN(0)

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_FillOperationsCache]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_FillOperationsCache]
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END

	DELETE FROM b_RolesOperationsCache
	WHERE 1 = 1

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END


	DECLARE @tbRoles table(RoleId int NOT NULL, SubRoleId int NOT NULL, PRIMARY KEY (RoleId, SubRoleId))

	DECLARE @RoleId int

	DECLARE roles_cursor CURSOR FOR
	SELECT ID
	FROM [dbo].[b_Roles]

	OPEN roles_cursor
	
	FETCH NEXT FROM roles_cursor INTO @RoleId
	
	WHILE @@FETCH_STATUS = 0
	BEGIN

		WITH tmp_Roles(ID, Way) AS (
			SELECT ID, ',' + CAST(ID AS VARCHAR(MAX)) + ',' AS Way
			FROM [dbo].[b_Roles] AS r
			WHERE (ID = @RoleId)
			UNION ALL
			SELECT r.ID, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesInRoles AS rir
				INNER JOIN [dbo].[b_Roles] AS r ON r.ID = rir.SubRoleID
				INNER JOIN tmp_Roles AS tr ON tr.ID = rir.RoleID
			WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		INSERT INTO @tbRoles (RoleId, SubRoleId)
		SELECT DISTINCT @RoleId, ID
		FROM tmp_Roles
	
		FETCH NEXT FROM roles_cursor INTO @RoleId
	END

	CLOSE roles_cursor
	DEALLOCATE roles_cursor

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	DECLARE @tbTasks table(TaskId int NOT NULL, SubTaskId int NOT NULL, PRIMARY KEY (TaskId, SubTaskId))

	DECLARE @TaskId int

	DECLARE tasks_cursor CURSOR FOR
	SELECT ID
	FROM b_RolesTasks

	OPEN tasks_cursor
	
	FETCH NEXT FROM tasks_cursor INTO @TaskId
	
	WHILE @@FETCH_STATUS = 0
	BEGIN

		WITH tmp_Tasks(ID, Way) AS (
			SELECT ID, ',' + CAST(ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesTasks AS r
			WHERE (ID = @TaskId)
			UNION ALL
			SELECT r.ID, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesTasksInTasks AS rir
				INNER JOIN dbo.b_RolesTasks AS r ON r.ID = rir.SubTaskID
				INNER JOIN tmp_Tasks AS tr ON tr.ID = rir.TaskID
			WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		INSERT INTO @tbTasks (TaskId, SubTaskId)
		SELECT DISTINCT @TaskId, ID
		FROM tmp_Tasks
	
		FETCH NEXT FROM tasks_cursor INTO @TaskId
	END

	CLOSE tasks_cursor
	DEALLOCATE tasks_cursor

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	INSERT INTO b_RolesOperationsCache (RoleID, OperationID, ModuleID, ExternalID)
	SELECT DISTINCT tr.RoleId, rtio.OperationID, rit.ModuleID, rit.ExternalID
	FROM @tbRoles tr
		INNER JOIN b_RolesInTasks rit ON (tr.SubRoleId = rit.RoleID)
		INNER JOIN @tbTasks tt ON (rit.TaskID = tt.TaskId)
		INNER JOIN b_RolesTasksInOperations rtio ON (tt.SubTaskId = rtio.TaskID)
	UNION
	SELECT DISTINCT tr.RoleId, rio.OperationID, rio.ModuleID, rio.ExternalID
	FROM @tbRoles tr
		INNER JOIN b_RolesInOperations rio ON (tr.SubRoleId = rio.RoleID)


    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetUserOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetUserOperations]
	@UserId int = NULL,
	@UserName nvarchar(256) = NULL,
	@ProviderName nvarchar(128) = NULL,
	@OperationNames nvarchar(4000) = NULL
AS
BEGIN
	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		SELECT @UserId = NULL
	END

	IF (@UserId IS NULL AND @UserName IS NOT NULL)
	BEGIN
		SELECT @UserId = u.ID
		FROM dbo.b_Users u
		WHERE u.LoweredUserName = LOWER(@UserName)
			AND u.LoweredProviderName = LOWER(@ProviderName)
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(128)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@OperationNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @OperationNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@OperationNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@OperationNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (LOWER(@Name))
		SET @Num = @Num + 1
	END

	IF (@UserId = 1)
	BEGIN

		SELECT ro.ID, ro.OperationName, ro.OperationType, ro.ModuleID, ro.Comment, '', ''
		FROM dbo.b_RolesOperations ro
		WHERE @OperationNames IS NULL
			OR (@OperationNames IS NOT NULL AND ro.LoweredOperationName IN (SELECT Name FROM @tbNames))

	END
	ELSE
	BEGIN

		SELECT ro.ID, ro.OperationName, ro.OperationType, ro.ModuleID, ro.Comment, roc.ModuleID, roc.ExternalID
		FROM dbo.b_RolesOperationsCache roc, dbo.b_RolesOperations ro
		WHERE roc.OperationID = ro.ID
			AND (@OperationNames IS NULL
				OR (@OperationNames IS NOT NULL AND ro.LoweredOperationName IN (SELECT Name FROM @tbNames)))
			AND (roc.RoleID = 2
				OR @UserId IS NOT NULL AND (roc.RoleID IN (
						SELECT uir.RoleID
						FROM dbo.b_UsersInRoles uir
						WHERE uir.UserID = @UserId
							AND (uir.ActiveFrom IS NULL OR uir.ActiveFrom <= GETDATE())
							AND (uir.ActiveTo IS NULL OR uir.ActiveTo >= GETDATE())
					) OR roc.RoleID = 3)
				)

	END

	RETURN (0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_IsUserCanOperate]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_IsUserCanOperate]
    @Operation nvarchar(128),
	@UserId int = NULL,
    @UserName nvarchar(256) = NULL,
    @ProviderName nvarchar(128) = null,
    @ModuleID varchar(50) = null,
    @ExternalID varchar(50) = null
AS
BEGIN
    DECLARE @OperationId int
    SELECT @OperationId = NULL

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	IF (@ModuleID IS NULL OR @ModuleID = '' OR @ExternalID IS NULL OR @ExternalID = '')
	BEGIN
		SELECT @ModuleID = ''
		SELECT @ExternalID = ''
	END

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		SELECT @UserId = NULL
	END

	IF (@UserId IS NULL AND @UserName IS NOT NULL)
	BEGIN
		SELECT @UserId = ID
		FROM dbo.b_Users
		WHERE LoweredUserName = LOWER(@UserName)
			AND LoweredProviderName = LOWER(@ProviderName)
	END

	IF (@UserId = 1)
		RETURN(1)

    SELECT @OperationId = ID
    FROM dbo.b_RolesOperations
    WHERE LoweredOperationName = LOWER(@Operation)

    IF (@OperationId IS NULL)
        RETURN(3)

    IF (EXISTS( 
			SELECT * 
			FROM dbo.b_RolesOperationsCache roc
			WHERE roc.OperationID = @OperationId
				AND (roc.ModuleID = @ModuleID AND roc.ExternalID = @ExternalID
					OR roc.ModuleID = '' AND roc.ExternalID = '')
				AND (roc.RoleID = 2
					OR @UserId IS NOT NULL AND (roc.RoleID IN (
							SELECT uir.RoleID
							FROM dbo.b_UsersInRoles uir
							WHERE uir.UserID = @UserId
								AND (uir.ActiveFrom IS NULL OR uir.ActiveFrom <= GETDATE())
								AND (uir.ActiveTo IS NULL OR uir.ActiveTo >= GETDATE())
						) OR roc.RoleID = 3)
					)
		))
        RETURN(1)
    ELSE
        RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetOperationsForUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetOperationsForUser]
	@UserId int = NULL,
	@UserName nvarchar(256) = NULL,
	@ProviderName nvarchar(128) = NULL,
	@OperationNames nvarchar(4000) = NULL
AS
BEGIN
	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		SELECT @UserId = NULL
	END

	IF (@UserId IS NULL AND @UserName IS NOT NULL)
	BEGIN
		SELECT @UserId = u.ID
		FROM dbo.b_Users u
		WHERE u.LoweredUserName = LOWER(@UserName)
			AND u.LoweredProviderName = LOWER(@ProviderName)
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(128)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@OperationNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @OperationNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@OperationNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@OperationNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (LOWER(@Name))
		SET @Num = @Num + 1
	END

	IF (@UserId = 1)
	BEGIN

		SELECT ro.OperationName, '', ''
		FROM dbo.b_RolesOperations ro
		WHERE @OperationNames IS NULL
			OR (@OperationNames IS NOT NULL AND ro.LoweredOperationName IN (SELECT Name FROM @tbNames))

	END
	ELSE
	BEGIN

		SELECT ro.OperationName, roc.ModuleID, roc.ExternalID
		FROM dbo.b_RolesOperationsCache roc, dbo.b_RolesOperations ro
		WHERE roc.OperationID = ro.ID
			AND (@OperationNames IS NULL
				OR (@OperationNames IS NOT NULL AND ro.LoweredOperationName IN (SELECT Name FROM @tbNames)))
			AND (roc.RoleID = 2
				OR @UserId IS NOT NULL AND (roc.RoleID IN (
						SELECT uir.RoleID
						FROM dbo.b_UsersInRoles uir
						WHERE uir.UserID = @UserId
							AND (uir.ActiveFrom IS NULL OR uir.ActiveFrom <= GETDATE())
							AND (uir.ActiveTo IS NULL OR uir.ActiveTo >= GETDATE())
					) OR roc.RoleID = 3)
				)

	END

	RETURN (0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetOperationsInRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetOperationsInRole]
	@RoleName nvarchar(256),
	@ModuleID varchar(128) = NULL,
	@ExternalId varchar(128) = NULL
AS
BEGIN

	DECLARE @RoleId int
	SELECT @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
	 RETURN(2)

	SELECT r.OperationName
	FROM dbo.b_RolesOperations r, dbo.b_RolesInOperations rr
	WHERE r.ID = rr.OperationID
		AND @RoleId = rr.RoleID
		AND (@ModuleID IS NULL AND rr.ModuleID = ''
			OR @ModuleID IS NOT NULL AND rr.ModuleID = @ModuleID AND rr.ExternalID = @ExternalId
		)
	ORDER BY r.OperationName

	RETURN(0)

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetOperationByID]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetOperationByID]
	@OperationId int
AS
BEGIN

	SELECT r.OperationName, r.ID, r.Comment, r.OperationType, r.ModuleID
	FROM dbo.b_RolesOperations r
	WHERE r.ID = @OperationId

    IF (@@ROWCOUNT = 0)
       RETURN -1

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetAllOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetAllOperations]
	@PageIndex int = 0,
	@PageSize int = -1,
	@ModuleId varchar(128) = null
AS
BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @TotalRecords int
	
	IF (@ModuleId = '')
		SELECT @ModuleId = NULL
	
	IF (@PageSize = -1)
	BEGIN
		SELECT r.OperationName, r.ID, r.Comment, r.OperationType, r.ModuleID
		FROM dbo.b_RolesOperations r
		WHERE (@ModuleId IS NULL OR @ModuleId IS NOT NULL AND r.ModuleID = @ModuleId)
		ORDER BY r.ModuleID, r.OperationName
		
		RETURN 0
	END
	ELSE
	BEGIN
		SET @PageLowerBound = @PageSize * @PageIndex
		SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

		CREATE TABLE #PageIndexForOperations
		(
			IndexId int IDENTITY (0, 1) NOT NULL,
			OperationId int
		)

		INSERT INTO #PageIndexForOperations (OperationId)
		SELECT r.ID
		FROM dbo.b_RolesOperations r
		ORDER BY r.OperationName

		SELECT @TotalRecords = @@ROWCOUNT

		SELECT r.OperationName, r.ID, r.Comment, r.OperationType, r.ModuleID
		FROM dbo.b_RolesOperations r, #PageIndexForOperations p
		WHERE r.ID = p.OperationId
			AND p.IndexId >= @PageLowerBound
			AND p.IndexId <= @PageUpperBound
		ORDER BY r.OperationName
	END

	RETURN @TotalRecords
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_CreateOperation]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_CreateOperation]
	@OperationName nvarchar(128),
	@OperationType nvarchar(128),
	@ModuleId nvarchar(128),
    @Comment ntext = null,
    @OperationId int OUTPUT
AS
BEGIN
    SET @OperationId = NULL

    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    IF (EXISTS( SELECT ID FROM dbo.b_RolesOperations WHERE LoweredOperationName = LOWER(@OperationName) ))
    BEGIN
        SET @ErrorCode = 11
        GOTO Cleanup
    END

    INSERT INTO dbo.b_RolesOperations(OperationName, LoweredOperationName, OperationType, ModuleID, Comment)
         VALUES (@OperationName, LOWER(@OperationName), @OperationType, @ModuleId, @Comment)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	SELECT @OperationId = @@IDENTITY

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetAllRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetAllRoles]
	@PageIndex int = 0,
	@PageSize int = -1
AS
BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @TotalRecords int
	
	IF (@PageSize = -1)
	BEGIN
		SELECT r.RoleName
		FROM [dbo].[b_Roles] r
		ORDER BY r.RoleName
		
		RETURN 0
	END
	ELSE
	BEGIN
		SET @PageLowerBound = @PageSize * @PageIndex
		SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

		CREATE TABLE #PageIndexForRoles
		(
			IndexId int IDENTITY (0, 1) NOT NULL,
			RoleId int
		)

		INSERT INTO #PageIndexForRoles (RoleId)
		SELECT r.ID
		FROM [dbo].[b_Roles] r
		ORDER BY r.RoleName

		SELECT @TotalRecords = @@ROWCOUNT

		SELECT r.RoleName, r.ID, r.Active, r.Comment, r.Policy, r.EffectivePolicy,
			(
			SELECT COUNT(*) 
			FROM b_UsersInRoles uir 
			WHERE uir.RoleID = r.ID 
			) as UsersCount,
			(
			SELECT COUNT(*) 
			FROM b_RolesInRoles rir 
			WHERE rir.RoleID = r.ID 
			) as RolesCount
		FROM [dbo].[b_Roles] r, #PageIndexForRoles p
		WHERE r.ID = p.RoleId
			AND p.IndexId >= @PageLowerBound
			AND p.IndexId <= @PageUpperBound
		ORDER BY r.RoleName
	END

	RETURN @TotalRecords
END
GO
/****** Object:  Trigger [b_Roles_Delete]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_Roles_Delete]
ON [b_Roles] 
FOR DELETE
AS
	IF (SELECT COUNT(*) FROM deleted WHERE ID in (1, 2, 3)) > 0
	BEGIN
		ROLLBACK
		RAISERROR('Can not delete the roles #1, #2 and #3', 16, 1)
	END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetRoleByID]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetRoleByID] 
    @RoleId int
AS
BEGIN

	SELECT r.RoleName, r.ID, r.Active, r.Comment, r.Policy, r.EffectivePolicy,
		(
		SELECT COUNT(*) 
		FROM b_UsersInRoles uir 
		WHERE uir.RoleID = r.ID 
		) as UsersCount,
		(
		SELECT COUNT(*) 
		FROM b_RolesInRoles rir 
		WHERE rir.RoleID = r.ID 
		) as RolesCount
	FROM [dbo].[b_Roles] r
	WHERE r.ID = @RoleId

    IF (@@ROWCOUNT = 0)
       RETURN -1

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddUserToRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddUserToRole]
	@UserName nvarchar(256),
	@ProviderName nvarchar(128),
	@RoleName nvarchar(128),
	@ActiveFrom datetime = NULL,
	@ActiveTo datetime = NULL
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

    DECLARE @UserId int
    SELECT @UserId = NULL

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

	IF (@UserId IS NULL)
	BEGIN
		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(1)
	END

	DECLARE @RoleId int
	SELECT @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
	BEGIN
		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(2)
	END

	IF (@RoleId = 2 OR @RoleId = 3)
	BEGIN
		IF (@TranStarted = 1)
			COMMIT TRANSACTION

		RETURN(0)
	END

	IF (EXISTS(SELECT * FROM dbo.b_UsersInRoles ur WHERE ur.UserID = @UserId AND ur.RoleID = @RoleId))
	BEGIN
		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(3)
	END

	INSERT INTO dbo.b_UsersInRoles (UserID, RoleID, ActiveFrom, ActiveTo)
	VALUES (@UserId, @RoleId, @ActiveFrom, @ActiveTo)

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddUsersToRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddUsersToRoles]
	@UserNames		  nvarchar(4000),
	@RoleNames		  nvarchar(4000),
	@CurrentTimeUtc   datetime
AS
BEGIN
	DECLARE @TranStarted   bit
	SET @TranStarted = 0

	IF( @@TRANCOUNT = 0 )
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames	table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles	table(RoleId int NOT NULL PRIMARY KEY)
	DECLARE @tbUsers	table(UserId int NOT NULL PRIMARY KEY)
	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	  SELECT r.ID
	  FROM   [dbo].[b_Roles] r, @tbNames t
	  WHERE  LOWER(t.Name) = r.LoweredRoleName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (
				SELECT r.LoweredRoleName 
				FROM [dbo].[b_Roles] r, @tbRoles tr 
				WHERE tr.RoleId = r.ID)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(2)
	END

	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1

	WHILE (@Pos <= LEN(@UserNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @UserNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@UserNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@UserNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbUsers
	  SELECT u.ID
	  FROM   dbo.b_users u, @tbNames t
	  WHERE  LOWER(t.Name) = u.LoweredUserName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (
				SELECT u.LoweredUserName
				FROM dbo.b_users u, @tbUsers tu 
				WHERE tu.UserId = u.ID)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(1)
	END

	IF (EXISTS (SELECT * FROM dbo.b_UsersInRoles ur, @tbUsers tu, @tbRoles tr WHERE tu.UserId = ur.UserID AND tr.RoleId = ur.RoleID))
	BEGIN
		SELECT TOP 1 UserName, RoleName
		FROM dbo.b_UsersInRoles ur, @tbUsers tu, @tbRoles tr, dbo.b_users u, [dbo].[b_Roles] r
		WHERE u.ID = tu.UserId 
			AND r.ID = tr.RoleId
			AND tu.UserId = ur.UserId
			AND tr.RoleId = ur.RoleId

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(3)
	END

	INSERT INTO dbo.b_UsersInRoles (UserID, RoleID)
	SELECT UserId, RoleId
	FROM @tbUsers, @tbRoles
	WHERE NOT RoleId IN (2, 3)

	IF (@TranStarted = 1)
		COMMIT TRANSACTION
	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RoleExists]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RoleExists]
    @RoleName nvarchar(128)
AS
BEGIN
    IF (EXISTS (SELECT RoleName FROM [dbo].[b_Roles] WHERE LOWER(@RoleName) = LoweredRoleName))
        RETURN(1)
    ELSE
        RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_SynchronizeProviderRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_SynchronizeProviderRoles]
	@ProviderName varchar(128),
	@RoleNames nvarchar(4000)
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(FName nvarchar(128) NOT NULL PRIMARY KEY)

	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(128)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@ProviderName + N'\' + @Name)
		SET @Num = @Num + 1
	END

	INSERT INTO [dbo].[b_Roles](RoleName, LoweredRoleName, Active, Comment, Policy, EffectivePolicy)
	SELECT t.FName, LOWER(t.FName), 1, null, '<Policy/>', null
	FROM @tbNames t
	WHERE LOWER(t.FName) NOT IN (SELECT r.LoweredRoleName FROM [dbo].[b_Roles] r)

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetRolesInRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetRolesInRole] 
	@RoleName nvarchar(256)
AS
BEGIN

     DECLARE @RoleId int
     SELECT @RoleId = NULL

     SELECT @RoleId = ID
     FROM [dbo].[b_Roles]
     WHERE LOWER(@RoleName) = LoweredRoleName

     IF (@RoleId IS NULL)
         RETURN(2)

    SELECT r.RoleName
    FROM [dbo].[b_Roles] r, dbo.b_RolesInRoles rr
    WHERE r.ID = rr.SubRoleID
		AND @RoleId = rr.RoleID
    ORDER BY r.RoleName

    RETURN(0)

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_DropEffectivePolicy]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_DropEffectivePolicy]
	(
	@RoleId int
	)
AS
BEGIN

	/*
	Null effective policy of all roles that depend on @RoleId role
	*/

	WITH tmp_Roles(ID, Way) AS (
		SELECT ID, ',' + CAST(ID AS VARCHAR(MAX)) + ',' AS Way
		FROM [dbo].[b_Roles] AS r
		WHERE (ID = @RoleId)
		UNION ALL
		SELECT r.ID, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
		FROM dbo.b_RolesInRoles AS rir
			INNER JOIN [dbo].[b_Roles] AS r ON r.ID = rir.RoleID
			INNER JOIN tmp_Roles AS tr ON tr.ID = rir.SubRoleID
		WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%')
	)
	UPDATE [dbo].[b_Roles] SET
		EffectivePolicy = NULL
	FROM [dbo].[b_Roles] ur, tmp_Roles utr
	WHERE ur.ID = utr.ID

	RETURN
END
GO
/****** Object:  View [dbo].[recurse_view]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [recurse_view]
AS
WITH tmp_Roles(ID, RoleName, Way) AS (SELECT        ID, RoleName, ',' + CAST(ID AS VARCHAR(MAX)) + ',' AS Way
                                                                                           FROM            [dbo].[b_Roles] AS r
                                                                                           WHERE        (ID = 1)
                                                                                           UNION ALL
                                                                                           SELECT        r.ID, r.RoleName, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
                                                                                           FROM            dbo.b_RolesInRoles AS rir INNER JOIN
                                                                                                                    [dbo].[b_Roles] AS r ON r.ID = rir.SubRoleID INNER JOIN
                                                                                                                    tmp_Roles AS tr ON tr.ID = rir.RoleID
                                                                                           WHERE        (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
    SELECT        ID, RoleName, Way
     FROM            tmp_Roles AS tmp_Roles_1
GO
/****** Object:  StoredProcedure [dbo].[Roles_FillEffectivePolicy]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_FillEffectivePolicy]
AS
BEGIN

	/*
	Fill effective policy of all roles where effective policy is not set
	*/

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @RoleId int
	DECLARE @Policy xml

	DECLARE @tbRoles table(RoleId int NOT NULL, Policy xml NULL, PRIMARY KEY (RoleId))

	INSERT INTO @tbRoles(RoleId, Policy)
	SELECT r.ID, r.Policy
	FROM [dbo].[b_Roles] r
	WHERE r.EffectivePolicy IS NULL
		AND NOT EXISTS(
			SELECT 'x'
			FROM b_RolesInRoles rir, [dbo].[b_Roles] r1
			WHERE rir.RoleID = r.ID
				AND rir.SubRoleID = r1.ID
				AND r1.EffectivePolicy IS NULL
		)

	WHILE (EXISTS( SELECT RoleId FROM @tbRoles ))
	BEGIN

		DECLARE roles_cursor CURSOR LOCAL FOR
		SELECT tr.RoleId, r.EffectivePolicy
		FROM @tbRoles tr
			LEFT JOIN b_RolesInRoles rir ON (tr.RoleId = rir.RoleID)
			LEFT JOIN [dbo].[b_Roles] r ON (rir.SubRoleID = r.ID)

		OPEN roles_cursor

		FETCH NEXT FROM roles_cursor INTO @RoleId, @Policy

		WHILE @@FETCH_STATUS = 0
		BEGIN

			UPDATE @tbRoles SET
				Policy = dbo.Roles_ComputePolicy(Policy, @Policy)
			WHERE RoleId = @RoleId

			FETCH NEXT FROM roles_cursor INTO @RoleId, @Policy
		END

		CLOSE roles_cursor
		DEALLOCATE roles_cursor

		UPDATE [dbo].[b_Roles] SET
			EffectivePolicy = tr.Policy
		FROM [dbo].[b_Roles] r, @tbRoles tr
		WHERE r.ID = tr.RoleId


		DELETE FROM @tbRoles WHERE 1 = 1

		INSERT INTO @tbRoles(RoleId, Policy)
		SELECT r.ID, r.Policy
		FROM [dbo].[b_Roles] r
		WHERE r.EffectivePolicy IS NULL
			AND NOT EXISTS(
				SELECT 'x'
				FROM b_RolesInRoles rir, [dbo].[b_Roles] r1
				WHERE rir.RoleID = r.ID
					AND rir.SubRoleID = r1.ID
					AND r1.EffectivePolicy IS NULL
			)

	END

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetRolesForUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetRolesForUser]
	@UserName nvarchar(256) = NULL,
	@ProviderName nvarchar(128) = NULL,
	@RecursiveCheck bit = 1,
	@AllRoles bit = 0
AS
BEGIN
    DECLARE @UserId int
    SELECT @UserId = NULL

	IF (@UserName IS NULL)
	BEGIN
		IF (@RecursiveCheck = 0)
		BEGIN

			SELECT r.RoleName
			FROM [dbo].[b_Roles] r
			WHERE r.ID = 2
			ORDER BY r.RoleName

		END
		ELSE
		BEGIN

			WITH tmp_Roles(ID, RoleName, Way) AS (
				SELECT r.ID, r.RoleName, ',' + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
				FROM [dbo].[b_Roles] r
				WHERE r.ID = 2
				UNION ALL
				SELECT r.ID, r.RoleName, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
				FROM dbo.b_RolesInRoles rir
					INNER JOIN [dbo].[b_Roles] r ON r.ID = rir.SubRoleID
					INNER JOIN tmp_Roles tr ON tr.ID = rir.RoleID
				WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
			SELECT DISTINCT tmpr.RoleName
			FROM tmp_Roles tmpr

		END

		RETURN (0)
	END

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

    IF (@UserId IS NULL)
        RETURN(1)

	IF (@RecursiveCheck = 0)
	BEGIN

		IF (@AllRoles = 0)
		BEGIN
			SELECT r.RoleName
			FROM [dbo].[b_Roles] r
			WHERE r.ID IN (2, 3) OR r.ID IN (
				SELECT ur.RoleID
				FROM dbo.b_UsersInRoles ur
				WHERE ur.UserID = @UserId
					AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
					AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
				)
			ORDER BY r.RoleName

--			SELECT r.RoleName
--			FROM dbo.b_Roles r, dbo.b_UsersInRoles ur
--			WHERE r.ID = ur.RoleID
--				AND ur.UserID = @UserId
--				AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
--				AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
--			ORDER BY r.RoleName
		END
		ELSE
		BEGIN
			SELECT r.RoleName, ur.ActiveFrom, ur.ActiveTo
			FROM [dbo].[b_Roles] r
				LEFT JOIN dbo.b_UsersInRoles ur ON (r.ID = ur.RoleID)
			WHERE r.ID IN (2, 3)
				OR ur.UserID = @UserId
			ORDER BY r.RoleName

--			SELECT r.RoleName, ur.ActiveFrom, ur.ActiveTo
--			FROM dbo.b_Roles r, dbo.b_UsersInRoles ur
--			WHERE r.ID = ur.RoleID
--				AND ur.UserID = @UserId
--			ORDER BY r.RoleName
		END

	END
	ELSE
	BEGIN

		WITH tmp_Roles(ID, RoleName, Way) AS (
			SELECT r.ID, r.RoleName, ',' + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM [dbo].[b_Roles] r
				LEFT JOIN dbo.b_UsersInRoles ur ON (r.ID = ur.RoleID)
			WHERE r.ID IN (2, 3)
				OR (ur.UserID = @UserId
				AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
				AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE()))
			UNION ALL
			SELECT r.ID, r.RoleName, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesInRoles rir
				INNER JOIN [dbo].[b_Roles] r ON r.ID = rir.SubRoleID
				INNER JOIN tmp_Roles tr ON tr.ID = rir.RoleID
			WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		SELECT DISTINCT tmpr.RoleName
		FROM tmp_Roles tmpr

	END

    RETURN (0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetUsersInRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetUsersInRoles]
    @RoleName nvarchar(256)
AS
BEGIN
	DECLARE @RoleId int
	SELECT @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
         RETURN(2)

	SELECT u.UserName
	FROM dbo.b_Users u, dbo.b_UsersInRoles ur
	WHERE u.ID = ur.UserID
		AND @RoleId = ur.RoleID
		AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
		AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
	ORDER BY u.UserName

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetRoleByName]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetRoleByName]
    @RoleName nvarchar(128)
AS
BEGIN

	SELECT r.RoleName, r.ID, r.Active, r.Comment, r.Policy, r.EffectivePolicy,
		(
		SELECT COUNT(*) 
		FROM b_UsersInRoles uir 
		WHERE uir.RoleID = r.ID 
		) as UsersCount,
		(
		SELECT COUNT(*) 
		FROM b_RolesInRoles rir 
		WHERE rir.RoleID = r.ID 
		) as RolesCount
	FROM [dbo].[b_Roles] r
	WHERE r.RoleName = @RoleName

    IF (@@ROWCOUNT = 0)
       RETURN -1

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetEffectivePolicyForUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetEffectivePolicyForUser] 
    @UserName nvarchar(256),
    @ProviderName nvarchar(128)
AS
BEGIN
    DECLARE @UserId int
    SELECT @UserId = NULL

	DECLARE @ResultPolicy xml
	SELECT @ResultPolicy = NULL

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

    IF (@UserId IS NULL)
        RETURN(1)

	DECLARE @Policy xml

	DECLARE roles_cursor CURSOR LOCAL FOR
	SELECT r.EffectivePolicy
	FROM [dbo].[b_Roles] r, dbo.b_UsersInRoles ur
	WHERE r.ID IN (2, 3)
		OR r.ID = ur.RoleID
		AND ur.UserID = @UserId
		AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
		AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())

	OPEN roles_cursor

	FETCH NEXT FROM roles_cursor INTO @Policy

	WHILE @@FETCH_STATUS = 0
	BEGIN

		SELECT @ResultPolicy = dbo.Roles_ComputePolicyL(@ResultPolicy, @Policy)

		FETCH NEXT FROM roles_cursor INTO @Policy
	END

	CLOSE roles_cursor
	DEALLOCATE roles_cursor

	SELECT @ResultPolicy

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_FindUsersInRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_FindUsersInRole]
    @RoleName nvarchar(256),
    @UserNameToMatch  nvarchar(256)
AS
BEGIN
     DECLARE @RoleId int
     SELECT @RoleId = NULL

     SELECT @RoleId = ID
     FROM [dbo].[b_Roles]
     WHERE LOWER(@RoleName) = LoweredRoleName

     IF (@RoleId IS NULL)
         RETURN(2)

    SELECT u.UserName
    FROM dbo.b_Users u, dbo.b_UsersInRoles ur
    WHERE u.ID = ur.UserID
		AND @RoleId = ur.RoleID
		AND LoweredUserName LIKE LOWER(@UserNameToMatch)
    ORDER BY u.UserName

    RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetAllRolesForUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetAllRolesForUser]
	@UserName nvarchar(256) = NULL,
	@ProviderName nvarchar(128) = NULL,
	@RecursiveCheck bit = 1,
	@AllRoles bit = 0
AS
BEGIN
    DECLARE @UserId int
    SELECT @UserId = NULL

	IF (@UserName IS NULL)
	BEGIN
		IF (@RecursiveCheck = 0)
		BEGIN

			SELECT r.RoleName
			FROM [dbo].[b_Roles] r
			WHERE r.ID = 2
			ORDER BY r.RoleName

		END
		ELSE
		BEGIN

			WITH tmp_Roles(ID, RoleName, Way) AS (
				SELECT r.ID, r.RoleName, ',' + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
				FROM [dbo].[b_Roles] r
				WHERE r.ID = 2
				UNION ALL
				SELECT r.ID, r.RoleName, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
				FROM dbo.b_RolesInRoles rir
					INNER JOIN [dbo].[b_Roles] r ON r.ID = rir.SubRoleID
					INNER JOIN tmp_Roles tr ON tr.ID = rir.RoleID
				WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
			SELECT DISTINCT tmpr.RoleName
			FROM tmp_Roles tmpr

		END

		RETURN (0)
	END

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

    IF (@UserId IS NULL)
        RETURN(1)

	IF (@RecursiveCheck = 0)
	BEGIN

		IF (@AllRoles = 0)
		BEGIN
			SELECT r.RoleName
			FROM [dbo].[b_Roles] r
			WHERE r.ID IN (2, 3) OR r.ID IN (
				SELECT ur.RoleID
				FROM dbo.b_UsersInRoles ur
				WHERE ur.UserID = @UserId
					AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
					AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
				)
			ORDER BY r.RoleName

--			SELECT r.RoleName
--			FROM dbo.b_Roles r, dbo.b_UsersInRoles ur
--			WHERE r.ID = ur.RoleID
--				AND ur.UserID = @UserId
--				AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
--				AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
--			ORDER BY r.RoleName
		END
		ELSE
		BEGIN
			SELECT r.RoleName, ur.ActiveFrom, ur.ActiveTo
			FROM [dbo].[b_Roles] r
				LEFT JOIN dbo.b_UsersInRoles ur ON (r.ID = ur.RoleID)
			WHERE r.ID IN (2, 3)
				OR ur.UserID = @UserId
			ORDER BY r.RoleName

--			SELECT r.RoleName, ur.ActiveFrom, ur.ActiveTo
--			FROM dbo.b_Roles r, dbo.b_UsersInRoles ur
--			WHERE r.ID = ur.RoleID
--				AND ur.UserID = @UserId
--			ORDER BY r.RoleName
		END

	END
	ELSE
	BEGIN

		WITH tmp_Roles(ID, RoleName, Way) AS (
			SELECT r.ID, r.RoleName, ',' + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM [dbo].[b_Roles] r
				LEFT JOIN dbo.b_UsersInRoles ur ON (r.ID = ur.RoleID)
			WHERE r.ID IN (2, 3)
				OR (ur.UserID = @UserId
				AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
				AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE()))
			UNION ALL
			SELECT r.ID, r.RoleName, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesInRoles rir
				INNER JOIN [dbo].[b_Roles] r ON r.ID = rir.SubRoleID
				INNER JOIN tmp_Roles tr ON tr.ID = rir.RoleID
			WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		SELECT DISTINCT tmpr.RoleName
		FROM tmp_Roles tmpr

	END

    RETURN (0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_GetUserRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_GetUserRoles]
	@UserId int = NULL,
	@UserName nvarchar(256) = NULL,
	@ProviderName nvarchar(128) = NULL,
	@RecursiveCheck bit = 1
AS
BEGIN

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		SELECT @UserId = NULL
	END

	IF (@UserId IS NULL AND @UserName IS NOT NULL)
	BEGIN
		SELECT @UserId = u.ID
		FROM b_Users u
		WHERE u.LoweredUserName = LOWER(@UserName)
			AND u.LoweredProviderName = LOWER(@ProviderName)
	END

	IF (@RecursiveCheck = 0)
	BEGIN

		SELECT r.ID, r.RoleName, r.Title, r.Active, r.Comment, r.Policy, r.EffectivePolicy, (SELECT COUNT(*) FROM b_UsersInRoles uir WHERE uir.RoleID = r.ID) as UsersCount, (SELECT COUNT(*) FROM b_RolesInRoles rir WHERE rir.RoleID = r.ID) as RolesCount
		FROM dbo.b_Roles r
		WHERE r.Active = 1
			AND (r.ID = 2
				OR @UserId IS NOT NULL 
					AND (r.ID IN (
						SELECT ur.RoleID
						FROM dbo.b_UsersInRoles ur
						WHERE ur.UserID = @UserId
							AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
							AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
					) OR r.ID = 3)
				)
		ORDER BY r.RoleName

	END
	ELSE
	BEGIN

		WITH tmp_Roles(ID, RoleName, Title, Active, Way) AS (
			SELECT r.ID, r.RoleName, r.Title, r.Active, ',' + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_Roles r
				LEFT JOIN dbo.b_UsersInRoles ur ON (r.ID = ur.RoleID)
			WHERE r.Active = 1
				AND (r.ID = 2
					OR (@UserId IS NOT NULL 
						AND (ur.UserID = @UserId
						AND (ur.ActiveFrom IS NULL OR ur.ActiveFrom <= GETDATE())
						AND (ur.ActiveTo IS NULL OR ur.ActiveTo >= GETDATE())
						OR r.ID = 3)
					)
				)
			UNION ALL
			SELECT r.ID, r.RoleName, r.Title, r.Active, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesInRoles rir
				INNER JOIN dbo.b_Roles r ON r.ID = rir.SubRoleID
				INNER JOIN tmp_Roles tr ON tr.ID = rir.RoleID
			WHERE r.Active = 1 
				AND (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		SELECT DISTINCT tmpr.ID, tmpr.RoleName, tmpr.Title, tmpr.Active, null, null, null, 0, 0
		FROM tmp_Roles tmpr

	END

    RETURN (0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_IsUserInRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_IsUserInRole]
    @UserName nvarchar(256),
    @RoleName nvarchar(256),
    @RecursiveCheck bit = 1,
    @ProviderName nvarchar(128) = null
AS
BEGIN
    DECLARE @UserId int
    SELECT @UserId = NULL

    DECLARE @RoleId int
    SELECT @RoleId = NULL

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

    IF (@UserId IS NULL)
        RETURN(2)

    SELECT @RoleId = ID
    FROM [dbo].[b_Roles]
    WHERE LoweredRoleName = LOWER(@RoleName)

    IF (@RoleId IS NULL)
        RETURN(3)

	IF (@RecursiveCheck = 0)
	BEGIN
		IF (EXISTS( 
			SELECT * 
			FROM dbo.b_UsersInRoles 
			WHERE UserID = @UserId 
				AND RoleID = @RoleId
				AND (ActiveFrom IS NULL OR ActiveFrom <= GETDATE())
				AND (ActiveTo IS NULL OR ActiveTo >= GETDATE())
			))
			RETURN(1)
		ELSE
			RETURN(0)
	END
	ELSE
	BEGIN
	
		DECLARE @cnt int
		SELECT @cnt = null;
	
		WITH tmp_Roles(ID, Way) AS (
			SELECT ID, ',' + CAST(ID AS VARCHAR(MAX)) + ',' AS Way
			FROM [dbo].[b_Roles] AS r
			WHERE (ID = @RoleId)
			UNION ALL
			SELECT r.ID, tr.Way + CAST(r.ID AS VARCHAR(MAX)) + ',' AS Way
			FROM dbo.b_RolesInRoles AS rir
				INNER JOIN [dbo].[b_Roles] AS r ON r.ID = rir.RoleID
				INNER JOIN tmp_Roles AS tr ON tr.ID = rir.SubRoleID
			WHERE (tr.Way NOT LIKE '%,' + CAST(r.ID AS VARCHAR(MAX)) + ',%'))
		SELECT @cnt = count(*)
		FROM tmp_Roles tmpr, dbo.b_UsersInRoles uir
		WHERE uir.UserID = @UserId
			AND tmpr.ID = uir.RoleID
			AND (uir.ActiveFrom IS NULL OR uir.ActiveFrom <= GETDATE())
			AND (uir.ActiveTo IS NULL OR uir.ActiveTo >= GETDATE())
	
		IF (@cnt IS NOT NULL AND @cnt > 0)
			RETURN(1)
		ELSE
			RETURN(0)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveUserFromRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveUserFromRole]
	@UserName nvarchar(256),
	@ProviderName nvarchar(128),
	@RoleName nvarchar(128)
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

    DECLARE @UserId int
    SELECT @UserId = NULL

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LoweredUserName = LOWER(@UserName)
		AND LoweredProviderName = LOWER(@ProviderName)

	IF (@UserId IS NULL)
	BEGIN
		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(1)
	END

	DECLARE @RoleId int
	SELECT @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
	BEGIN
		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(2)
	END

	DELETE FROM dbo.b_UsersInRoles
	WHERE UserID = @UserId
		AND RoleID = @RoleId

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveUsersFromRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveUsersFromRoles]
	@UserNames nvarchar(4000),
	@RoleNames nvarchar(4000)
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles table(RoleId int NOT NULL PRIMARY KEY)
	DECLARE @tbUsers table(UserId int NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(256)
	DECLARE @CountAll int
	DECLARE @CountU int
	DECLARE @CountR int


	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	SELECT ID
	FROM [dbo].[b_Roles] ar, @tbNames t
	WHERE LOWER(t.Name) = ar.LoweredRoleName

	SELECT @CountR = @@ROWCOUNT

	IF (@CountR <> @Num)
	BEGIN
		SELECT TOP 1 N'', Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT ar.LoweredRoleName
			FROM [dbo].[b_Roles] ar, @tbRoles r
			WHERE r.RoleId = ar.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(2)
	END


	DELETE FROM @tbNames
	WHERE 1=1


	SET @Num = 0
	SET @Pos = 1


	WHILE (@Pos <= LEN(@UserNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @UserNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@UserNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@UserNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbUsers
	SELECT ID
	FROM dbo.b_users ar, @tbNames t
	WHERE LOWER(t.Name) = ar.LoweredUserName

	SELECT @CountU = @@ROWCOUNT

	IF (@CountU <> @Num)
	BEGIN
		SELECT TOP 1 Name, N''
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT au.LoweredUserName
			FROM dbo.b_users au, @tbUsers u
			WHERE u.UserId = au.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(1)
	END

	SELECT @CountAll = COUNT(*)
	FROM dbo.b_UsersInRoles ur, @tbUsers u, @tbRoles r
	WHERE ur.UserID = u.UserId
		AND ur.RoleID = r.RoleId

	IF (@CountAll <> @CountU * @CountR)
	BEGIN
		SELECT TOP 1 UserName, RoleName
		FROM @tbUsers tu, @tbRoles tr, dbo.b_users u, [dbo].[b_Roles] r
		WHERE u.ID = tu.UserId
			AND r.ID = tr.RoleId
			AND tu.UserId NOT IN (
				SELECT ur.UserID 
				FROM dbo.b_UsersInRoles ur 
				WHERE ur.RoleID = tr.RoleId)
			AND tr.RoleId NOT IN (
				SELECT ur.RoleID 
				FROM dbo.b_UsersInRoles ur 
				WHERE ur.UserID = tu.UserId)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION
		RETURN(6)
	END

	DELETE FROM dbo.b_UsersInRoles
	WHERE UserID IN (SELECT UserId FROM @tbUsers)
		AND RoleID IN (SELECT RoleId FROM @tbRoles)

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_SynchronizeProviderUserRoles]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_SynchronizeProviderUserRoles]
	@UserName nvarchar(256),
	@ProviderName varchar(128),
	@RoleNames nvarchar(4000)
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(FName nvarchar(128) NOT NULL PRIMARY KEY)

	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(128)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@ProviderName + N'\' + @Name)
		SET @Num = @Num + 1
	END

	DECLARE @UserId int

	SELECT @UserId = u.ID
	FROM b_Users u
	WHERE u.LoweredUserName = LOWER(@UserName)
		AND u.LoweredProviderName = LOWER(@ProviderName)

    IF (@UserId IS NULL)
        RETURN(1)

	DELETE FROM b_UsersInRoles
	WHERE UserID = @UserId
		AND RoleID IN (
			SELECT r.ID
			FROM [dbo].[b_Roles] r
				LEFT JOIN @tbNames n ON (r.LoweredRoleName = LOWER(n.FName))
			WHERE r.LoweredRoleName LIKE LOWER(@ProviderName) + N'\%'
				AND n.FName IS NULL
		)

	INSERT INTO [dbo].[b_Roles](RoleName, LoweredRoleName, Active, Comment, Policy, EffectivePolicy)
	SELECT t.FName, LOWER(t.FName), 1, null, '<Policy/>', null
	FROM @tbNames t
	WHERE LOWER(t.FName) NOT IN (SELECT r.LoweredRoleName FROM [dbo].[b_Roles] r)


	INSERT INTO b_UsersInRoles (UserID, RoleID)
	SELECT @UserId, r.ID
	FROM [dbo].[b_Roles] r, @tbNames n
	WHERE r.LoweredRoleName = LOWER(n.FName)
		AND r.ID NOT IN (SELECT uir.RoleID FROM b_UsersInRoles uir WHERE uir.UserID = @UserId)

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  Trigger [b_File_Update]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_File_Update]
ON [b_File]
FOR UPDATE
AS

	INSERT INTO b_FileAction(FileName, Folder, Action)
	SELECT d.FileName, d.Folder, 'D'
	FROM inserted i, deleted d
	WHERE i.ID = d.ID
		AND (i.FileName <> d.FileName OR i.Folder <> d.Folder)
GO
/****** Object:  Trigger [b_File_Delete]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_File_Delete]
ON [b_File]
FOR DELETE
AS

	INSERT INTO b_FileAction(FileName, Folder, Action)
	SELECT d.FileName, d.Folder, 'D'
	FROM deleted d
GO
/****** Object:  Trigger [b_IBlock_Delete]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlock_Delete]
ON [b_IBlock]
FOR DELETE
AS

	DELETE FROM b_File 
	WHERE ID IN (
		SELECT D.ImageId
		FROM DELETED D
		WHERE D.ImageId IS NOT NULL
	)
GO
/****** Object:  Trigger [b_IBlock_Update]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlock_Update]
ON [b_IBlock]
FOR UPDATE
AS
	IF (NOT UPDATE(UpdateDate))
	BEGIN
		UPDATE b_IBlock SET
			UpdateDate = GETDATE()
		FROM b_IBlock U, INSERTED I, DELETED D
		WHERE U.ID = I.ID
			AND U.ID = D.ID
	END

	IF (UPDATE(ImageId))
	BEGIN

		DELETE FROM b_File 
		WHERE ID IN (
			SELECT D.ImageId
			FROM INSERTED I, DELETED D
			WHERE I.ID = D.ID
				AND I.ImageId <> D.ImageId
				AND D.ImageId IS NOT NULL
		)

	END
GO
/****** Object:  Trigger [b_IBlockSection_Update]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlockSection_Update]
ON [b_IBlockSection] 
FOR UPDATE
AS
	IF (NOT UPDATE(UpdateDate))
	BEGIN
		UPDATE b_IBlockSection SET
			UpdateDate = GETDATE()
		FROM b_IBlockSection U, INSERTED I, DELETED D
		WHERE U.ID = I.ID
			AND U.ID = D.ID
	END

	IF (UPDATE(IBlockId))
	BEGIN
		IF ((SELECT COUNT('x') FROM INSERTED i, DELETED d WHERE i.ID = d.ID AND i.IBlockId <> d.IBlockId) > 0)
		BEGIN
			ROLLBACK
			RAISERROR('Can not change parent infoblock of the section', 16, 1)
		END
	END

	IF (NOT UPDATE(LeftMargin) AND NOT UPDATE(RightMargin))
	BEGIN
		IF (UPDATE(Sort) OR UPDATE(Name) OR UPDATE(SectionId) OR UPDATE(Active))
		BEGIN
			DECLARE @IBlockId int

			UPDATE b_IBlock SET
				UpdateDate = UpdateDate
			WHERE ID IN (SELECT IBlockId FROM inserted)

			DECLARE C1 CURSOR LOCAL FOR
				SELECT DISTINCT IBlockId
				FROM INSERTED i

			OPEN C1
			FETCH NEXT FROM C1 INTO @IBlockId
			WHILE (@@FETCH_STATUS <> -1)
			BEGIN
				EXEC IBlock_SortSections @IBlockId
				FETCH NEXT FROM C1 INTO @IBlockId
			END
		END
	END

	IF (UPDATE(ImageId))
	BEGIN

		DELETE FROM b_File 
		WHERE ID IN (
			SELECT D.ImageId
			FROM INSERTED I, DELETED D
			WHERE I.ID = D.ID
				AND I.ImageId <> D.ImageId
				AND D.ImageId IS NOT NULL
		)

	END

	IF (UPDATE(DetailImageId))
	BEGIN

		DELETE FROM b_File 
		WHERE ID IN (
			SELECT D.DetailImageId
			FROM INSERTED I, DELETED D
			WHERE I.ID = D.ID
				AND I.DetailImageId <> D.DetailImageId
				AND D.DetailImageId IS NOT NULL
		)

	END
GO
/****** Object:  Trigger [b_IBlockSection_Delete]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlockSection_Delete]
ON [b_IBlockSection] 
FOR DELETE
AS
	DECLARE @IBlockId int, @RightMargin int

	IF (SELECT COUNT(DISTINCT IBlockId) FROM deleted) > 1
	BEGIN
		ROLLBACK
		RAISERROR('Can not delete multiple records from more than one catalog', 16, 1)
	END

	UPDATE b_IBlock	SET
		UpdateDate = UpdateDate
	WHERE ID IN (SELECT IBlockId FROM deleted)

	DECLARE C1 CURSOR LOCAL FOR
		SELECT IBlockId, RightMargin
		FROM deleted
		ORDER BY RightMargin DESC

	OPEN C1

	FETCH NEXT FROM C1 INTO @IBlockId, @RightMargin

	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		UPDATE b_IBlockSection SET
			LeftMargin = CASE WHEN s.LeftMargin >= @RightMargin THEN s.LeftMargin - 2 ELSE s.LeftMargin END,
			RightMargin = s.RightMargin - 2,
			UpdateDate = s.UpdateDate
		FROM b_IBlockSection s
		WHERE s.IBlockId = @IBlockId
			AND s.RightMargin >= @RightMargin

		FETCH NEXT FROM C1 INTO @IBlockId, @RightMargin
	END

	CLOSE C1
	DEALLOCATE C1


	DELETE FROM b_File 
	WHERE ID IN (
		SELECT D.ImageId
		FROM DELETED D
		WHERE D.ImageId IS NOT NULL
	)

	DELETE FROM b_File 
	WHERE ID IN (
		SELECT D.DetailImageId
		FROM DELETED D
		WHERE D.DetailImageId IS NOT NULL
	)
GO
/****** Object:  StoredProcedure [dbo].[File_Create]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [File_Create]
	@ModuleId varchar(128),
	@Height int,
	@Width int,
	@FileSize int,
	@ContentType varchar(255),
	@Folder nvarchar(255),
	@FileName nvarchar(255),
	@FileNameOriginal nvarchar(255),
	@Description nvarchar(255)
AS
BEGIN
    DECLARE @FileId int
    SET @FileId = NULL
	
	INSERT INTO b_File (ModuleId, Height, Width, FileSize, ContentType, Folder, FileName, FileNameOriginal, Description)
	VALUES (@ModuleId, @Height, @Width, @FileSize, @ContentType, @Folder, @FileName, @FileNameOriginal, @Description)

	SELECT @FileId = @@IDENTITY
	
	RETURN @FileId
	
END
GO
/****** Object:  StoredProcedure [dbo].[File_Delete]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [File_Delete]
	@oldFileId int,
	@newFileId int
AS
BEGIN
	IF (@oldFileId IS NOT NULL AND ISNULL(@oldFileId, 0) <> isnull(@newFileId, 0))
	BEGIN
		DELETE FROM b_File WHERE ID = @oldFileId
	END
END
GO
/****** Object:  Trigger [b_IBlockElement_Update]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlockElement_Update]
ON [b_IBlockElement] 
FOR UPDATE
AS
	IF (NOT UPDATE(UpdateDate))
	BEGIN
		UPDATE b_IBlockElement SET
			UpdateDate = GETDATE()
		FROM b_IBlockElement U, INSERTED I
		WHERE U.ID = I.ID
	END

	IF (UPDATE(PreviewImageId))
	BEGIN

		DELETE FROM b_File 
		WHERE ID IN (
			SELECT D.PreviewImageId
			FROM INSERTED I, DELETED D
			WHERE I.ID = D.ID
				AND I.PreviewImageId <> D.PreviewImageId
				AND D.PreviewImageId IS NOT NULL
		)

	END

	IF (UPDATE(DetailImageId))
	BEGIN

		DELETE FROM b_File 
		WHERE ID IN (
			SELECT D.DetailImageId
			FROM INSERTED I, DELETED D
			WHERE I.ID = D.ID
				AND I.DetailImageId <> D.DetailImageId
				AND D.DetailImageId IS NOT NULL
		)

	END
GO
/****** Object:  Trigger [b_IBlockElement_Delete]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlockElement_Delete]
ON [b_IBlockElement]
FOR DELETE
AS

	DELETE FROM b_File 
	WHERE ID IN (
		SELECT D.PreviewImageId
		FROM DELETED D
		WHERE D.PreviewImageId IS NOT NULL
	)

	DELETE FROM b_File 
	WHERE ID IN (
		SELECT D.DetailImageId
		FROM DELETED D
		WHERE D.DetailImageId IS NOT NULL
	)
GO
/****** Object:  StoredProcedure [dbo].[Users_DeleteUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_DeleteUser]
	@UserId int,
	@DeleteAllRelatedData bit = 1,
	@NumTablesDeletedFrom int OUTPUT
AS
BEGIN
	SELECT @NumTablesDeletedFrom = 0

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
	BEGIN
		SET @TranStarted = 0
	END

	DECLARE @ErrorCode int
	DECLARE @RowCount int

	SET @ErrorCode = 0
	SET @RowCount  = 0

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		SET @ErrorCode = 1
		GOTO Cleanup
	END

	IF (@UserId = 1)
	BEGIN
		SET @ErrorCode = 50
		GOTO Cleanup
	END

	IF (@DeleteAllRelatedData = 1)
	BEGIN
		-- Delete all related data here
		DELETE FROM dbo.b_UsersControlsOptions
		WHERE UserID = @UserId

		SELECT @ErrorCode = @@ERROR,
			@RowCount = @@ROWCOUNT

		IF (@ErrorCode <> 0)
			GOTO Cleanup

		IF (@RowCount <> 0)
			SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
	END

	DELETE FROM b_UsersInRoles WHERE UserID = @UserId

	SELECT @ErrorCode = @@ERROR,
		@RowCount = @@ROWCOUNT

	IF (@ErrorCode <> 0)
		GOTO Cleanup

	IF (@RowCount <> 0)
		SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1

	DECLARE @OldImageId table(ImageId int)
	DELETE FROM dbo.b_Users OUTPUT DELETED.ImageId INTO @OldImageId WHERE @UserId = ID

	SELECT @ErrorCode = @@ERROR,
			@RowCount = @@ROWCOUNT

	IF (@ErrorCode <> 0)
		GOTO Cleanup

	IF (@RowCount <> 0)
		SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    
    
    DECLARE @DeleteId int
    SET @DeleteId = (SELECT ImageId FROM @OldImageId)
    
    IF (@DeleteId IS NOT NULL) BEGIN
		DELETE FROM dbo.b_File WHERE ID = @DeleteId
	END


	IF (@@ERROR <> 0)
        GOTO Cleanup

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END

	RETURN 0

Cleanup:

	SET @NumTablesDeletedFrom = 0

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		ROLLBACK TRANSACTION
	END

	RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Users_UpdateUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_UpdateUser]
    @UserId int,
    @UserName nvarchar(256),
    @Email nvarchar(256),
    @Comment ntext,
    @IsApproved bit,
    @LastLoginDate datetime,
    @LastActivityDate datetime,
    @UniqueEmail int,
    @CurrentTimeUtc datetime,
    @ProviderName nvarchar(128) = NULL,
    @FirstName nvarchar(50) = NULL,
    @SecondName nvarchar(50) = NULL,
    @LastName nvarchar(50) = NULL,
    @SiteId varchar(50) = NULL,
    @BirthdayDate datetime = NULL,
    @DisplayName nvarchar(256) = NULL,
    @ImageId int = NULL,
    @Gender char(1) = NULL
AS
BEGIN

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	DECLARE @ID int

    SELECT @ID = u.ID
    FROM dbo.b_Users u
    WHERE u.LoweredUserName = LOWER(@UserName)
		AND u.LoweredProviderName = LOWER(@ProviderName)

    IF (@ID IS NULL OR @ID <> @UserId)
        RETURN(1)

    IF (@UniqueEmail = 1)
    BEGIN
        IF (EXISTS (SELECT *
                    FROM  dbo.b_Users WITH (UPDLOCK, HOLDLOCK)
                    WHERE @UserId <> ID
						AND LoweredEmail = LOWER(@Email)))
        BEGIN
            RETURN(7)
        END
    END

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
		SET @TranStarted = 0

	DECLARE @OldImageId table(ImageId int)
	
	UPDATE dbo.b_Users WITH (ROWLOCK) SET
		LastActivityDate = @LastActivityDate,
		Email = @Email,
		LoweredEmail = LOWER(@Email),
		Comment = @Comment,
		IsApproved = @IsApproved,
		LastLoginDate = @LastLoginDate,
		FirstName = @FirstName,
		SecondName = @SecondName,
		LastName = @LastName,
		SiteID = @SiteId,
		BirthdayDate = @BirthdayDate,
		DisplayName = @DisplayName,
		ImageId = @ImageId,
		Gender = @Gender
	OUTPUT DELETED.ImageId INTO @OldImageId
	WHERE @UserId = ID

    IF (@@ERROR <> 0)
        GOTO Cleanup
    
    DECLARE @DeleteId int
    SET @DeleteId = (SELECT ImageId FROM @OldImageId WHERE ImageId <> @ImageId)
    
    IF (@DeleteId IS NOT NULL) BEGIN
		DELETE FROM dbo.b_File WHERE ID = @DeleteId
	END
        
	IF (@@ERROR <> 0)
        GOTO Cleanup

    IF (@TranStarted = 1)
    BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN -1
END
GO
/****** Object:  StoredProcedure [dbo].[BlogUser_Synchronize]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [BlogUser_Synchronize]
	@UserId int,
	@BlogId int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @PostCount int;
	SELECT @PostCount = COUNT(p.ID) FROM [b_BlogPost] p WHERE p.AuthorId = @UserId;
	
	UPDATE  [b_BlogUser] SET PostCount = @PostCount WHERE ID = @UserId;
END
GO
/****** Object:  StoredProcedure [dbo].[Blog_SynchronizeBlog]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Blog_SynchronizeBlog] 
	@BlogId int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @DateLastPosted datetime, @Now datetime, @PostCount int, @CommentCount int;	
	SET @Now = GETDATE(); 
	
	IF (@BlogId IS NULL) RETURN;

	SELECT @PostCount = COUNT(ID) FROM b_BlogPost WHERE BlogId = @BlogId AND IsPublished = 1 AND DatePublished <= @Now;
	IF(@PostCount > 0)
	BEGIN
		SELECT TOP 1 @DateLastPosted = DatePublished FROM b_BlogPost WHERE BlogId = @BlogId AND IsPublished = 1 AND DatePublished <= @Now ORDER BY DatePublished DESC;
		SELECT @CommentCount = COUNT(ID) FROM b_BlogComment WHERE BlogId = @BlogId AND MarkedForDelete = 0;
		UPDATE b_Blog SET DateLastPosted = @DateLastPosted, PostCount = @PostCount, CommentCount = @CommentCount WHERE ID = @BlogId;
	END
	ELSE
	BEGIN
		UPDATE b_Blog SET DateLastPosted = DateCreated, PostCount = 0, CommentCount = 0 WHERE ID = @BlogId;
	END	
END
GO
/****** Object:  StoredProcedure [dbo].[BlogCategory_DeleteBlogInCategory]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [BlogCategory_DeleteBlogInCategory]
	@CategoryId int
AS
BEGIN
	DELETE FROM b_BlogInCategory WHERE CategoryId = @CategoryId;	
END
GO
/****** Object:  StoredProcedure [dbo].[BlogPost_SynchronizePost]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [BlogPost_SynchronizePost]
	@PostId int,
	@BlogId int = NULL	
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @CommentCount int;
	IF (@PostId IS NULL) RETURN;
	IF (@BlogId IS NULL) SELECT @BlogId = BlogId FROM b_BlogPost WHERE ID = @PostId;
	IF (@BlogId IS NULL) RETURN;
	SELECT @CommentCount = COUNT(ID) FROM b_BlogComment WHERE PostId = @PostId AND MarkedForDelete = 0;
	UPDATE b_BlogPost SET CommentCount = @CommentCount WHERE ID = @PostId AND BlogId = @BlogId;
END
GO
/****** Object:  StoredProcedure [dbo].[BlogComment_SynchronizeNestedSets]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [BlogComment_SynchronizeNestedSets]
	@Id int,
	@Mode int = 1
AS
BEGIN
SET NOCOUNT ON;
/*
@Mode = 1 - process addition;
@Mode = 2 - process deletion;
@Mode = 3 - process modification;
*/
declare @postId int, @currentLeft int, @currentRight int, @currentDepth int, @currentParentId int, @currentRootIndex int, @currentLiveRootIndex int, @currentMarkedForDelete bit, @currentLiveNestedCount int, @parentLeft int, @parentRight int, @parentDepth int, @parentRootIndex int, @parentLiveRootIndex int, @parentMarkedForDelete bit, @parentParentId int;


if @Mode < 1 OR @Mode > 3 return;
--set @currentLiveRootIndex = 0;
--set @currentLiveNestedCount = 0;
if @Mode = 1 --addition
begin
	select top(1) @postId = c.PostId, @currentMarkedForDelete = c.MarkedForDelete, @currentParentId = c.ParentId from [b_BlogComment] c where c.ID = @Id;

	if @currentParentId = 0
	begin
		set @currentDepth = 1;
		
		select top(1) @currentLeft = c.RightMargin + 1, @currentRootIndex = c.RootNodeIndex + 1 from [b_BlogComment] c where c.ID <> @Id and c.LeftMargin > 0 AND c.DepthLevel = 1 and c.PostId = @postId order by c.RightMargin desc;
				
		if @currentLeft is NULL
			set @currentLeft = 1;

		if @currentRootIndex is NULL
			set @currentRootIndex = 1;

		set @currentRight = @currentLeft + 1;
		
		--LiveRootNodeIndex
		if @currentMarkedForDelete = 0
			select top(1) @currentLiveRootIndex = c.LiveRootNodeIndex + 1 from [b_BlogComment] c where c.ID <> @Id and c.DepthLevel = 1 and c.PostId = @postId and c.MarkedForDelete = 0 order by c.RightMargin desc;		

		if(@currentLiveRootIndex is NULL)
			set @currentLiveRootIndex = 1;			
	end
	else
	begin
		select top(1) @parentLeft = c.LeftMargin, @parentRight = c.RightMargin, @parentDepth = c.DepthLevel, @parentRootIndex = c.RootNodeIndex, @parentLiveRootIndex = c.LiveRootNodeIndex from [b_BlogComment] c where c.ID = @currentParentId and c.PostId = @postId;	
		set @currentDepth = @parentDepth + 1;
		
		set @currentLeft = @parentRight;
		set @currentRight = @currentLeft + 1;
		set @currentRootIndex = @parentRootIndex;
		set @currentLiveRootIndex = @parentLiveRootIndex;
		
		
		update [b_BlogComment] set LeftMargin = LeftMargin + 2 where LeftMargin > @parentRight and PostId= @postId;
		update [b_BlogComment] set RightMargin = RightMargin + 2 where RightMargin >= @parentRight and PostId= @postId;	
	end

	update [b_BlogComment] set LeftMargin = @currentLeft, RightMargin = @currentRight, DepthLevel = @currentDepth, RootNodeIndex = @currentRootIndex, LiveRootNodeIndex = @currentLiveRootIndex where ID = @Id;
end
else if @Mode = 2 --deletion
begin
	if not exists (select c.ID from [b_BlogComment] c where c.ID = @Id)
		return;
		
	select top(1) @postId = c.PostId, @currentMarkedForDelete = c.MarkedForDelete, @currentLeft = c.LeftMargin, @currentRight = c.RightMargin, @currentDepth = c.DepthLevel, @currentRootIndex = c.RootNodeIndex, @currentLiveRootIndex = c.LiveRootNodeIndex, @currentParentId = c.ParentId  from [b_BlogComment] c where c.ID = @Id;	
	if @postId = 0 or @currentLeft = 0 or @currentRight = 0 or @currentDepth = 0 or @currentRootIndex = 0
		return;

	update [b_BlogComment] set LeftMargin = 0, RightMargin = 0, DepthLevel = 0, RootNodeIndex = 0 where ID = @Id;

	--RootNodeIndex
	--process inner sets (deletion nested sests)
	--update [b_BlogComment] set LeftMargin = 0, RightMargin = 0, DepthLevel = 0, RootNodeIndex = 0 where LeftMargin > @currentLeft and RightMargin < @currentRight and PostId = @postId;
	delete from [b_BlogComment] where LeftMargin > @currentLeft and RightMargin < @currentRight and PostId = @postId;
	--process outer sets
	declare @shift int;
	set @shift = @currentRight - @currentLeft + 1;
	update [b_BlogComment] set LeftMargin = LeftMargin - @shift, RightMargin = RightMargin - @shift where LeftMargin > @currentRight and RightMargin > @currentRight and PostId = @postId;
	update [b_BlogComment] set RightMargin = RightMargin - @shift where LeftMargin < @currentLeft and RightMargin > @currentRight and PostId = @postId;	
	--root node index shift
	if @currentDepth = 1
		update [b_BlogComment] set RootNodeIndex = RootNodeIndex - 1 where RootNodeIndex > @currentRootIndex and PostId = @postId;		
		
	--LiveRootNodeIndex
	if @currentLiveRootIndex > 0
	begin
		if @currentDepth = 1
			update [b_BlogComment] set LiveRootNodeIndex = LiveRootNodeIndex - 1 where LiveRootNodeIndex > @currentLiveRootIndex and PostId = @postId;
		else
		begin
			if @currentParentId is null 
				set @currentParentId = 0;
			
			while @currentParentId > 0
			begin
				set @parentParentId = null;
				select top(1) @parentParentId = c.ParentId from [b_BlogComment] c where c.ID = @currentParentId and c.PostId = @postId;			
				if @parentParentId is null
					set @currentParentId = 0;
				else
				begin
					set @Id = @currentParentId;
					set @currentParentId = @parentParentId;		
				end
			end
			
			select top(1) @currentLeft = c.LeftMargin, @currentRight = c.RightMargin, @currentLiveRootIndex = c.LiveRootNodeIndex from [b_BlogComment] c where c.ID = @Id;
			
			update [b_BlogComment] set LiveRootNodeIndex = 0 where ID = @Id;
			update [b_BlogComment] set LiveRootNodeIndex = 0 where LeftMargin > @currentLeft and RightMargin < @currentRight and PostId = @postId;
			update [b_BlogComment] set LiveRootNodeIndex = LiveRootNodeIndex - 1 where LiveRootNodeIndex > @currentLiveRootIndex and PostId = @postId;						
		end
	end			
end
else --modification
begin
	--print 'modification mode'
	select top(1) @postId = c.PostId, @currentParentId = c.ParentId from [b_BlogComment] c where c.ID = @Id;
	
	if @postId is null return;	
	if @currentParentId is null 
		set @currentParentId = 0;
	
	while @currentParentId > 0
	begin
		set @parentParentId = null;
		select top(1) @parentParentId = c.ParentId from [b_BlogComment] c where c.ID = @currentParentId and c.PostId = @postId;			
		if @parentParentId is null
			set @currentParentId = 0;
		else
		begin
			set @Id = @currentParentId;
			set @currentParentId = @parentParentId;		
		end
	end
	
	--print '@Id = ' + cast(@Id as varchar(20));				
	--print '@currentParentId = ' + cast(@currentParentId as varchar(20));				

	select top(1) @currentLeft = c.LeftMargin, @currentRight = c.RightMargin, @currentMarkedForDelete = c.MarkedForDelete, @currentLiveRootIndex = c.LiveRootNodeIndex from [b_BlogComment] c where c.ID = @Id;
	--print '@currentLiveRootIndex = ' + cast(@currentLiveRootIndex as varchar(20));

	--LiveRootNodeIndex
	if @currentMarkedForDelete = 1
	begin
		select @currentLiveNestedCount = count(c.ID) from [b_BlogComment] c where c.PostId = @postId and c.LeftMargin > @currentLeft and c.RightMargin < @currentRight and c.MarkedForDelete = 0;					
		--if(@currentLiveNestedCount is NULL)
		--	set @currentLiveNestedCount = 0;			
	end	
	
	if(@currentLiveNestedCount is NULL)
		set @currentLiveNestedCount = 0;
		
	--print '@currentMarkedForDelete = ' + cast(@currentMarkedForDelete as varchar(20));				
	--print '@currentLiveNestedCount = ' + cast(@currentLiveNestedCount as varchar(20));


	if @currentMarkedForDelete = 1 and (@currentLiveNestedCount is null or @currentLiveNestedCount = 0)
	begin
		if @currentLiveRootIndex > 0
		begin
			--print 'LiveRootIndex to 0';

			update [b_BlogComment] set LiveRootNodeIndex = 0 where ID = @Id;
			update [b_BlogComment] set LiveRootNodeIndex = 0 where LeftMargin > @currentLeft and RightMargin < @currentRight and PostId = @postId;
			update [b_BlogComment] set LiveRootNodeIndex = LiveRootNodeIndex - 1 where LiveRootNodeIndex > @currentLiveRootIndex and PostId = @postId;			
		end
	end
	else if @currentLiveRootIndex = 0
	begin
		with NewLiveRootIndexes as (select c.ID, c.Contents, c.RootNodeIndex, c.LiveRootNodeIndex, ROW_NUMBER() over(order by c.RootNodeIndex asc) NewLiveRootNodeIndex from b_BlogComment c where c.PostId = @postId and c.DepthLevel = 1 and (c.MarkedForDelete = 0 or exists(select ID from b_BlogComment where MarkedForDelete = 0 and LeftMargin > c.LeftMargin and RightMargin < c.RightMargin)))
			update b_BlogComment set LiveRootNodeIndex = NewLiveRootIndexes.NewLiveRootNodeIndex from NewLiveRootIndexes where NewLiveRootIndexes.ID = b_BlogComment.ID;
		with NewNestedLiveRootIndexes as (select c.ID, c.PostId, c.RootNodeIndex, c.LiveRootNodeIndex from b_BlogComment c where c.PostId = @postId and c.DepthLevel = 1 and (c.MarkedForDelete = 0 or exists(select ID from b_BlogComment where MarkedForDelete = 0 and LeftMargin > c.LeftMargin and RightMargin < c.RightMargin)))
			update b_BlogComment set b_BlogComment.LiveRootNodeIndex = NewNestedLiveRootIndexes.LiveRootNodeIndex from NewNestedLiveRootIndexes where b_BlogComment.DepthLevel > 1 and b_BlogComment.PostId = NewNestedLiveRootIndexes.PostId and b_BlogComment.RootNodeIndex = NewNestedLiveRootIndexes.RootNodeIndex;		
	end	
end
END
GO
/****** Object:  StoredProcedure [dbo].[Adv_GetBanners]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Adv_GetBanners]
	@UserId int,
	@SiteId varchar(50),
	@Url nvarchar(2048),
	@DisplayedItemsXml xml,
	@DateTime datetime,
	@HourOfWeek tinyint
AS
BEGIN
	SET NOCOUNT ON;
	SELECT 
		b.ID, 
		b.SpaceId,
		s.Code [SpaceCode],
		b.[Weight], 
		b.EnableUniformRotationVelocity, 
		b.DateOfRotationStart,
		b.DateOfRotationFinish,
		b.DateOfFirstDisplay,
		b.DisplayCount,
		b.MaxDisplayCount
		FROM [b_AdvSpace] s
		INNER JOIN [b_AdvBanner] b 
			ON b.SpaceId = s.ID 
				AND b.Active = 1
				AND(b.DateOfRotationStart IS NULL OR b.DateOfRotationStart <= @DateTime)
				AND(b.DateOfRotationFinish IS NULL OR b.DateOfRotationFinish > @DateTime)
				AND(
					b.EnableRedirectionCount = 0 
					OR b.MaxRedirectionCount = 0
					OR b.MaxRedirectionCount > b.RedirectionCount 
				)				
				AND(
					b.EnableFixedRotation = 0
					OR(
						(b.MaxDisplayCount = 0 OR b.MaxDisplayCount > b.DisplayCount)
						AND(b.MaxVisitorCount = 0 OR b.MaxVisitorCount > b.VisitorCount)
						AND( --MaxDisplayCountPerVisitor
							b.MaxDisplayCountPerVisitor = 0
							OR NOT EXISTS(
								SELECT TOP 1 N'x' 
									FROM @DisplayedItemsXml.nodes('/item') t(c) 
									WHERE t.c.value('@id', 'int') = b.ID
										AND t.c.value('@count', 'int') >= b.MaxDisplayCountPerVisitor
							)
						) 						
					)
				)				
		WHERE
			(
				NOT EXISTS(
					SELECT TOP 1 N'x'
						FROM [b_AdvBannerInSite]
						WHERE BannerId = b.ID
				)
				OR EXISTS(
					SELECT TOP 1 N'x'
						FROM [b_AdvBannerInSite]
						WHERE BannerId = b.ID AND SiteId = @SiteId					
				)
			)
			AND EXISTS(
				SELECT TOP 1 N'x' 
					FROM [b_AdvBannerWeekScheduleHourSpan] wsh 
					WHERE wsh.BannerId = b.ID
						AND wsh.FromHourOfWeek <= @HourOfWeek
						AND wsh.TillHourOfWeek > @HourOfWeek
			)
			AND(--UserRoles
					(
						b.EnableRotationForVisitorRoles = 1
						AND EXISTS(
							SELECT TOP 1 N'x' 
								FROM [b_AdvBannerInRole] b2r
								INNER JOIN [b_UsersInRoles] u2r 
									ON u2r.RoleID = b2r.RoleId
										AND u2r.UserID = @UserId
										AND (u2r.ActiveFrom IS NULL OR u2r.ActiveFrom <= @DateTime)
										AND (u2r.ActiveTo IS NULL OR u2r.ActiveTo > @DateTime)
								WHERE b2r.BannerId = b.ID						
						)
					)
					OR(
						b.EnableRotationForVisitorRoles = 0
						AND NOT EXISTS(
							SELECT TOP 1 N'x' 
								FROM [b_AdvBannerInRole] b2r
								INNER JOIN [b_UsersInRoles] u2r 
									ON u2r.RoleID = b2r.RoleId
										AND u2r.UserID = @UserId
										AND (u2r.ActiveFrom IS NULL OR u2r.ActiveFrom <= @DateTime)
										AND (u2r.ActiveTo IS NULL OR u2r.ActiveTo > @DateTime)
								WHERE b2r.BannerId = b.ID						
						)					
					)				
			)
			AND(--WhiteList&BlackList
				NOT EXISTS(--BlackList
					SELECT TOP 1 N'x' 
					FROM [b_AdvBannerUrlTemplate] ut
					WHERE ut.BannerId = b.ID 
						AND ut.IsPermitted = 0
						AND @Url LIKE ut.UrlTemplate + N'%'
				)
				AND(--WhiteList
					NOT EXISTS(
						SELECT TOP 1 N'x' 
						FROM [b_AdvBannerUrlTemplate] ut
						WHERE ut.BannerId = b.ID 
							AND ut.IsPermitted = 1			
					)
					OR EXISTS(
						SELECT TOP 1 N'x' 
						FROM [b_AdvBannerUrlTemplate] ut
						WHERE ut.BannerId = b.ID 
							AND ut.IsPermitted = 1
							AND @Url LIKE ut.UrlTemplate + N'%'					
					)
				)
			)
	ORDER BY b.SpaceId ASC, b.EnableUniformRotationVelocity DESC, b.[Weight] DESC	
END
GO
/****** Object:  StoredProcedure [dbo].[Users_ChangePasswordQuestionAndAnswer]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_ChangePasswordQuestionAndAnswer]
    @UserId int,
    @NewPasswordQuestion nvarchar(256),
    @NewPasswordAnswer nvarchar(128)
AS
BEGIN
    IF (@UserId IS NULL)
    BEGIN
        RETURN(1)
    END

    UPDATE dbo.b_Users SET
		PasswordQuestion = @NewPasswordQuestion,
		PasswordAnswer = @NewPasswordAnswer
    WHERE ID = @UserId

	IF (@@ROWCOUNT = 0)
    BEGIN
        RETURN(1)
    END

    RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Users_ChangeCheckWord]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_ChangeCheckWord]
	@UserId int,
	@NewCheckWord nvarchar(50),
	@CurrentTimeUtc datetime
AS
BEGIN
    
	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		RETURN(1)
	END

	UPDATE dbo.b_users
	SET CheckWord = @NewCheckWord, CheckWordWindowStart = @CurrentTimeUtc
	WHERE ID = @UserId

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Users_UnlockUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_UnlockUser]
    @UserId int
AS
BEGIN
    IF (@UserId IS NULL)
        RETURN 1

	UPDATE dbo.b_users SET
		IsLockedOut = 0,
		FailedPasswordAttemptCount = 0,
		FailedPasswordAttemptWindowStart = CONVERT(datetime, '17540101', 112),
		FailedPasswordAnswerAttemptCount = 0,
		FailedPasswordAnswerAttemptWindowStart = CONVERT(datetime, '17540101', 112),
		LastLockoutDate = CONVERT(datetime, '17540101', 112)
	WHERE @UserId = ID

	IF (@@ROWCOUNT = 0)
    BEGIN
        RETURN(1)
    END

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Users_GetPasswordWithFormat]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_GetPasswordWithFormat] 
	@UserId int = NULL,
    @UserName nvarchar(256) = NULL,
    @ProviderName nvarchar(128) = NULL,
    @UpdateLastLoginActivityDate bit,
    @CurrentTimeUtc datetime
AS
BEGIN
    DECLARE @IsLockedOut bit
    DECLARE @Password nvarchar(128)
    DECLARE @PasswordSalt nvarchar(128)
    DECLARE @ID int
    DECLARE @PasswordFormat int
    DECLARE @FailedPasswordAttemptCount int
    DECLARE @FailedPasswordAnswerAttemptCount int
    DECLARE @IsApproved bit
    DECLARE @LastActivityDate datetime
    DECLARE @LastLoginDate datetime

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		IF (@ProviderName IS NULL)
		BEGIN
			SELECT @ProviderName = 'self'
		END

		SELECT @ID = u.ID, @IsLockedOut = u.IsLockedOut, @Password = u.Password, @PasswordFormat = u.PasswordFormat,
			@PasswordSalt = u.PasswordSalt, @FailedPasswordAttemptCount = u.FailedPasswordAttemptCount,
			@FailedPasswordAnswerAttemptCount = u.FailedPasswordAnswerAttemptCount, @IsApproved = u.IsApproved,
			@LastActivityDate = u.LastActivityDate, @LastLoginDate = u.LastLoginDate
		FROM dbo.b_Users u
		WHERE LOWER(@UserName) = u.LoweredUserName
			AND LOWER(@ProviderName) = u.LoweredProviderName
	END
	ELSE
	BEGIN

		SELECT @ID = u.ID, @IsLockedOut = u.IsLockedOut, @Password = u.Password, @PasswordFormat = u.PasswordFormat,
			@PasswordSalt = u.PasswordSalt, @FailedPasswordAttemptCount = u.FailedPasswordAttemptCount,
			@FailedPasswordAnswerAttemptCount = u.FailedPasswordAnswerAttemptCount, @IsApproved = u.IsApproved,
			@LastActivityDate = u.LastActivityDate, @LastLoginDate = u.LastLoginDate
		FROM dbo.b_Users u
		WHERE @UserId = u.ID

	END

    IF (@ID IS NULL)
        RETURN 1

    IF (@IsLockedOut = 1)
        RETURN 99

	SELECT @Password, @PasswordFormat, @PasswordSalt, @FailedPasswordAttemptCount,
		@FailedPasswordAnswerAttemptCount, @IsApproved, @LastLoginDate, @LastActivityDate

	IF (@UpdateLastLoginActivityDate = 1 AND @IsApproved = 1)
	BEGIN
		UPDATE dbo.b_users SET
			LastLoginDate = @CurrentTimeUtc,
			LastActivityDate = @CurrentTimeUtc
		WHERE ID = @ID
    END

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Users_CreateUser]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_CreateUser]
    @UserName nvarchar(256),
    @Password nvarchar(128),
    @PasswordSalt nvarchar(128),
    @Email nvarchar(256),
    @PasswordQuestion nvarchar(256),
    @PasswordAnswer nvarchar(128),
    @CheckWord nvarchar(50),
    @IsApproved bit,
    @CurrentTimeUtc datetime,
    @UniqueEmail int = 0,
    @PasswordFormat int = 0,
    @ProviderName nvarchar(128) = NULL,
    @FirstName nvarchar(50) = NULL,
    @SecondName nvarchar(50) = NULL,
    @LastName nvarchar(50) = NULL,
    @SiteId varchar(50) = NULL,
    @BirthdayDate datetime = NULL,
    @Comment ntext = NULL,
    @DisplayName nvarchar(256) = NULL,
    @ImageId int = NULL,
    @Gender char(1) = NULL,
    @UserId int OUTPUT
AS
BEGIN
    SELECT @UserId = NULL

    DECLARE @IsLockedOut bit
    SET @IsLockedOut = 0

    DECLARE @LastLockoutDate datetime
    SET @LastLockoutDate = CONVERT(datetime, '17540101', 112)

    DECLARE @FailedPasswordAttemptCount int
    SET @FailedPasswordAttemptCount = 0

    DECLARE @FailedPasswordAttemptWindowStart datetime
    SET @FailedPasswordAttemptWindowStart = CONVERT(datetime, '17540101', 112)

    DECLARE @CheckWordAttemptWindowStart datetime
    SET @CheckWordAttemptWindowStart = CONVERT(datetime, '17540101', 112)

    DECLARE @FailedPasswordAnswerAttemptCount int
    SET @FailedPasswordAnswerAttemptCount = 0

    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime
    SET @FailedPasswordAnswerAttemptWindowStart = CONVERT(datetime, '17540101', 112)

    DECLARE @ReturnValue int
    SET @ReturnValue = 0

    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

    SELECT @UserId = ID
    FROM dbo.b_Users
    WHERE LOWER(@UserName) = LoweredUserName
		AND LOWER(@ProviderName) = LoweredProviderName

    IF (@UserId IS NOT NULL)
    BEGIN
        SET @ErrorCode = 6
        GOTO Cleanup
    END

	IF (@UniqueEmail = 1)
	BEGIN
		IF (EXISTS( SELECT *
			FROM  dbo.b_Users WITH (UPDLOCK, HOLDLOCK)
			WHERE LoweredEmail = LOWER(@Email) ))
		BEGIN
			SET @ErrorCode = 7
			GOTO Cleanup
		END
	END

	INSERT INTO dbo.b_Users(UserName, LoweredUserName, LastActivityDate, Password, PasswordSalt, ProviderName,
		LoweredProviderName, Email, LoweredEmail, PasswordQuestion, PasswordAnswer, PasswordFormat, CheckWord,
		CheckWordWindowStart, IsApproved, IsLockedOut, CreationDate, LastLoginDate, LastPasswordChangedDate,
		LastLockoutDate, FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart,
		FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart,
		FirstName, SecondName, LastName, SiteID, BirthdayDate, Comment, DisplayName, ImageId, Gender)
	VALUES (@UserName, LOWER(@UserName), @CurrentTimeUtc, @Password, @PasswordSalt, @ProviderName,
		LOWER(@ProviderName), @Email, LOWER(@Email), @PasswordQuestion, @PasswordAnswer, @PasswordFormat, 
		@CheckWord, @CheckWordAttemptWindowStart, @IsApproved, @IsLockedOut, @CurrentTimeUtc, @CurrentTimeUtc,
		@CurrentTimeUtc, @LastLockoutDate, @FailedPasswordAttemptCount, @FailedPasswordAttemptWindowStart,
		@FailedPasswordAnswerAttemptCount, @FailedPasswordAnswerAttemptWindowStart,
		@FirstName, @SecondName, @LastName, @SiteId, @BirthdayDate, @Comment, @DisplayName, @ImageId, @Gender)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	SELECT @UserId = @@IDENTITY;

    IF (@TranStarted = 1)
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Users_UpdateUserInfo]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_UpdateUserInfo]
	@UserId int = NULL,
    @UserName nvarchar(256) = NULL,
    @ProviderName nvarchar(128) = NULL,
    @IsPasswordCorrect bit,
    @UpdateLastLoginActivityDate bit,
    @MaxInvalidPasswordAttempts int,
    @PasswordAttemptWindow int,
    @CurrentTimeUtc datetime,
    @LastLoginDate datetime,
    @LastActivityDate datetime
AS
BEGIN
    DECLARE @IsApproved bit
    DECLARE @IsLockedOut bit
    DECLARE @LastLockoutDate datetime
    DECLARE @ID int
    DECLARE @FailedPasswordAttemptCount int
    DECLARE @FailedPasswordAttemptWindowStart datetime
    DECLARE @FailedPasswordAnswerAttemptCount int
    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime

    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

	IF (@UserId IS NULL OR @UserId = 0)
	BEGIN
		IF (@ProviderName IS NULL)
		BEGIN
			SELECT @ProviderName = 'self'
		END

		SELECT @ID = u.ID,
			   @IsApproved = u.IsApproved,
			   @IsLockedOut = u.IsLockedOut,
			   @LastLockoutDate = u.LastLockoutDate,
			   @FailedPasswordAttemptCount = u.FailedPasswordAttemptCount,
			   @FailedPasswordAttemptWindowStart = u.FailedPasswordAttemptWindowStart,
			   @FailedPasswordAnswerAttemptCount = u.FailedPasswordAnswerAttemptCount,
			   @FailedPasswordAnswerAttemptWindowStart = u.FailedPasswordAnswerAttemptWindowStart
		FROM dbo.b_Users u WITH (UPDLOCK)
		WHERE LOWER(@UserName) = u.LoweredUserName
			AND LOWER(@ProviderName) = u.LoweredProviderName
	END
	ELSE
	BEGIN
		SELECT @ID = u.ID,
			   @IsApproved = u.IsApproved,
			   @IsLockedOut = u.IsLockedOut,
			   @LastLockoutDate = u.LastLockoutDate,
			   @FailedPasswordAttemptCount = u.FailedPasswordAttemptCount,
			   @FailedPasswordAttemptWindowStart = u.FailedPasswordAttemptWindowStart,
			   @FailedPasswordAnswerAttemptCount = u.FailedPasswordAnswerAttemptCount,
			   @FailedPasswordAnswerAttemptWindowStart = u.FailedPasswordAnswerAttemptWindowStart
		FROM dbo.b_Users u WITH (UPDLOCK)
		WHERE @UserId = u.ID
	END

    IF (@@rowcount = 0)
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    IF (@IsLockedOut = 1)
    BEGIN
        GOTO Cleanup
    END

    IF (@IsPasswordCorrect = 0)
    BEGIN
        IF (@CurrentTimeUtc > DATEADD(minute, @PasswordAttemptWindow, @FailedPasswordAttemptWindowStart))
        BEGIN
            SET @FailedPasswordAttemptWindowStart = @CurrentTimeUtc
            SET @FailedPasswordAttemptCount = 1
        END
        ELSE
        BEGIN
            SET @FailedPasswordAttemptWindowStart = @CurrentTimeUtc
            SET @FailedPasswordAttemptCount = @FailedPasswordAttemptCount + 1
        END

        BEGIN
            IF (@FailedPasswordAttemptCount >= @MaxInvalidPasswordAttempts)
            BEGIN
                SET @IsLockedOut = 1
                SET @LastLockoutDate = @CurrentTimeUtc
            END
        END
    END
    ELSE
    BEGIN
        IF (@FailedPasswordAttemptCount > 0 OR @FailedPasswordAnswerAttemptCount > 0)
        BEGIN
            SET @FailedPasswordAttemptCount = 0
            SET @FailedPasswordAttemptWindowStart = CONVERT(datetime, '17540101', 112)
            SET @FailedPasswordAnswerAttemptCount = 0
            SET @FailedPasswordAnswerAttemptWindowStart = CONVERT(datetime, '17540101', 112)
            SET @LastLockoutDate = CONVERT(datetime, '17540101', 112)
        END
    END

    IF (@UpdateLastLoginActivityDate = 1)
    BEGIN
        UPDATE dbo.b_Users SET
			LastActivityDate = @LastActivityDate,
			LastLoginDate = @LastLoginDate
        WHERE @ID = ID

        IF (@@ERROR <> 0)
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END


    UPDATE dbo.b_Users SET
		IsLockedOut = @IsLockedOut, LastLockoutDate = @LastLockoutDate,
        FailedPasswordAttemptCount = @FailedPasswordAttemptCount,
        FailedPasswordAttemptWindowStart = @FailedPasswordAttemptWindowStart,
        FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount,
        FailedPasswordAnswerAttemptWindowStart = @FailedPasswordAnswerAttemptWindowStart
    WHERE @ID = ID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
    END

    RETURN @ErrorCode

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Users_SetPassword]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_SetPassword]
    @UserId int,
    @NewPassword nvarchar(128),
    @PasswordSalt nvarchar(128),
    @CurrentTimeUtc datetime,
    @PasswordFormat int = 0
AS
BEGIN
    IF (@UserId IS NULL)
        RETURN(1)

    UPDATE dbo.b_Users SET
		Password = @NewPassword,
		PasswordFormat = @PasswordFormat,
		PasswordSalt = @PasswordSalt,
        LastPasswordChangedDate = @CurrentTimeUtc
    WHERE @UserId = ID

	IF (@@ROWCOUNT = 0)
    BEGIN
        RETURN(1)
    END

    RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Users_GetUserByName]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_GetUserByName]
    @UserName nvarchar(256),
    @ProviderName nvarchar(128),
    @CurrentTimeUtc datetime,
    @UpdateLastActivity bit = 0
AS
BEGIN

	IF (@ProviderName IS NULL)
	BEGIN
		SELECT @ProviderName = 'self'
	END

	SELECT TOP 1 u.ID AS UserId, u.UserName, u.ProviderName, u.LastActivityDate, u.Email, u.PasswordQuestion, 
		u.IsApproved, u.IsLockedOut, u.CreationDate, u.LastLoginDate, u.LastPasswordChangedDate, 
		u.LastLockoutDate, u.Comment, u.FirstName, u.SecondName,
		u.LastName, u.SiteID AS SiteId, u.BirthdayDate, u.DisplayName, u.ImageId, u.Gender
	FROM dbo.b_Users u
	WHERE LOWER(@UserName) = u.LoweredUserName
		AND LOWER(@ProviderName) = u.LoweredProviderName

    IF (@@ROWCOUNT = 0)
        RETURN -1

    IF (@UpdateLastActivity = 1)
    BEGIN

        UPDATE dbo.b_users SET
			LastActivityDate = @CurrentTimeUtc
        WHERE LOWER(@UserName) = LoweredUserName
			AND LOWER(@ProviderName) = LoweredProviderName

    END

    RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Users_GetUserByID]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_GetUserByID]
	@UserId int,
	@CurrentTimeUtc datetime,
	@UpdateLastActivity bit = 0
AS
BEGIN
	IF (@UpdateLastActivity = 1)
	BEGIN
		UPDATE dbo.b_Users SET
			LastActivityDate = @CurrentTimeUtc
		WHERE ID = @UserId

		IF (@@ROWCOUNT = 0)
			RETURN -1
	END

	SELECT u.ID AS UserId, u.UserName, u.ProviderName, u.LastActivityDate, u.Email, u.PasswordQuestion, 
		u.IsApproved, u.IsLockedOut, u.CreationDate, u.LastLoginDate, u.LastPasswordChangedDate, 
		u.LastLockoutDate, u.Comment, u.FirstName, u.SecondName,
		u.LastName, u.SiteID AS SiteId, u.BirthdayDate, u.DisplayName, u.ImageId, u.Gender
	FROM dbo.b_Users u
	WHERE u.ID = @UserId

	IF (@@ROWCOUNT = 0)
		RETURN -1

	RETURN 0
END
GO
/****** Object:  StoredProcedure [dbo].[Users_ResetPassword]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Users_ResetPassword]
    @UserId int,
    @NewPassword nvarchar(128),
    @MaxInvalidPasswordAttempts int,
    @PasswordAttemptWindow int,
    @CheckWordAttemptWindow int,
    @PasswordSalt nvarchar(128),
    @CurrentTimeUtc datetime,
    @PasswordFormat int = 0,
    @PasswordAnswer nvarchar(128) = NULL,
    @CheckWord nvarchar(50) = NULL
AS
BEGIN
    DECLARE @IsLockedOut bit
    DECLARE @LastLockoutDate datetime
    DECLARE @FailedPasswordAttemptCount int
    DECLARE @FailedPasswordAttemptWindowStart datetime
    DECLARE @CheckWordAttemptWindowStart datetime
    DECLARE @FailedPasswordAnswerAttemptCount int
    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime

    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    IF (@UserId IS NULL)
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

	SELECT @IsLockedOut = IsLockedOut,
		@LastLockoutDate = LastLockoutDate,
		@FailedPasswordAttemptCount = FailedPasswordAttemptCount,
		@FailedPasswordAttemptWindowStart = FailedPasswordAttemptWindowStart,
		@CheckWordAttemptWindowStart = CheckWordWindowStart,
		@FailedPasswordAnswerAttemptCount = FailedPasswordAnswerAttemptCount,
		@FailedPasswordAnswerAttemptWindowStart = FailedPasswordAnswerAttemptWindowStart
    FROM dbo.b_Users WITH (UPDLOCK)
    WHERE @UserId = ID

	IF (@@ROWCOUNT = 0)
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    IF (@IsLockedOut = 1)
    BEGIN
        SET @ErrorCode = 99
        GOTO Cleanup
    END

	UPDATE dbo.b_Users SET
		Password = @NewPassword,
		LastPasswordChangedDate = @CurrentTimeUtc,
		PasswordFormat = @PasswordFormat,
		PasswordSalt = @PasswordSalt
	WHERE @UserId = ID
		AND ((@PasswordAnswer IS NULL) OR (LOWER(PasswordAnswer) = LOWER(@PasswordAnswer)))
		AND ((@CheckWord IS NULL) OR ((LOWER(CheckWord) = LOWER(@CheckWord)) AND (@CurrentTimeUtc <= DATEADD(minute, @CheckWordAttemptWindow, @CheckWordAttemptWindowStart))))

	IF (@@ROWCOUNT = 0)
	BEGIN
		IF (@CurrentTimeUtc > DATEADD(minute, @PasswordAttemptWindow, @FailedPasswordAnswerAttemptWindowStart))
		BEGIN
			SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
			SET @FailedPasswordAnswerAttemptCount = 1
		END
		ELSE
		BEGIN
			SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
			SET @FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount + 1
		END

		IF (@FailedPasswordAnswerAttemptCount >= @MaxInvalidPasswordAttempts)
		BEGIN
			SET @IsLockedOut = 1
			SET @LastLockoutDate = @CurrentTimeUtc
		END

		SET @ErrorCode = 3
	END
	ELSE
	BEGIN
		IF (@FailedPasswordAnswerAttemptCount > 0)
		BEGIN
			SET @FailedPasswordAnswerAttemptCount = 0
			SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, '17540101', 112 )
		END
	END

	IF (NOT(@PasswordAnswer IS NULL))
	BEGIN
		UPDATE dbo.b_Users SET
			IsLockedOut = @IsLockedOut,
			LastLockoutDate = @LastLockoutDate,
            FailedPasswordAttemptCount = @FailedPasswordAttemptCount,
            FailedPasswordAttemptWindowStart = @FailedPasswordAttemptWindowStart,
            FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount,
            FailedPasswordAnswerAttemptWindowStart = @FailedPasswordAnswerAttemptWindowStart
		WHERE @UserId = ID

        IF (@@ERROR <> 0)
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END

    IF (@TranStarted = 1)
    BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
    END

    RETURN @ErrorCode

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END
GO
/****** Object:  Trigger [b_Users_Detele]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_Users_Detele]
ON [b_Users] 
FOR DELETE
AS
	IF (SELECT COUNT(*) FROM deleted WHERE ID = 1) > 0
	BEGIN
		ROLLBACK
		RAISERROR('Can not delete the user #1', 16, 1)
	END
GO
/****** Object:  StoredProcedure [dbo].[Adv_ProcessClientRedirection]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Adv_ProcessClientRedirection]
	@BannerId int
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE [b_AdvBanner] 
	SET [RedirectionCount] = [RedirectionCount] + 1
	WHERE [ID] = @BannerId AND [Active] = 1 AND [EnableRedirectionCount] = 1;
	
	IF @@ROWCOUNT > 0
		SELECT [LinkUrl] FROM [b_AdvBanner]  WHERE [ID] = @BannerId AND [Active] = 1 AND [EnableRedirectionCount] = 1;
END
GO
/****** Object:  StoredProcedure [dbo].[Adv_ProcessDisplay]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Adv_ProcessDisplay] 
	@DisplayedItemsXml xml, 
	@Datetime datetime
AS
BEGIN
	SET NOCOUNT ON;
	WITH di AS
		(
			SELECT 
				t.c.value('@id', 'int') [ID], 
				t.c.value('@incrementedTotalCount', 'int') [IncrementedTotalCount], 
				t.c.value('if((@isNew cast as xs:byte?) = xs:byte(1)) then xs:integer(1) else xs:integer(0)', 'int') [InctementedVisitorCount]  
			FROM @DisplayedItemsXml.nodes('/item') t(c)	
		)
	UPDATE [b_AdvBanner] 
	SET 
		[DisplayCount] = [DisplayCount] + di.[IncrementedTotalCount], 
		[VisitorCount] = [VisitorCount] + di.[InctementedVisitorCount],
		[DateOfLastDisplay] = @Datetime,
		[DateOfFirstDisplay] = CASE WHEN [DateOfFirstDisplay] IS NULL THEN @Datetime ELSE [DateOfFirstDisplay] END
	FROM di INNER JOIN [b_AdvBanner] b ON di.ID = b.ID	
END
GO
/****** Object:  Trigger [b_IBlockSection_Insert]    Script Date: 10/01/2009 19:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [b_IBlockSection_Insert] 
ON [b_IBlockSection] 
FOR INSERT
AS
	DECLARE @IBlockId int

	UPDATE b_IBlock SET
		UpdateDate = UpdateDate
	WHERE ID IN (SELECT IBlockId FROM inserted)

	DECLARE C1 CURSOR LOCAL FOR
		SELECT DISTINCT IBlockId
		FROM INSERTED i

	OPEN C1
	FETCH NEXT FROM C1 INTO @IBlockId
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		EXEC IBlock_SortSections @IBlockId
		FETCH NEXT FROM C1 INTO @IBlockId
	END


--	DECLARE tempCursor CURSOR LOCAL FOR
--		SELECT i.ID, i.SectionId, i.IBlockId, i.Name, i.Sort
--		FROM INSERTED i 
--
--	OPEN tempCursor
--
--	FETCH NEXT FROM temp_cursor INTO @ID, @ParentSectionId, @IBlockId, @Name, @Sort
--	WHILE (@@FETCH_STATUS <> -1)
--	BEGIN
--		SET @insertPoint = NULL
--
--		SELECT @insertPoint = s.LeftMargin
--		FROM b_IBlockSection s 
--		WHERE s.ID IN (
--			SELECT TOP 1 st.ID 
--			FROM b_IBlockSection st
--			WHERE st.LeftMargin IS NOT NULL
--				AND (
--					(st.SectionId = @ParentSectionId AND st.ID <> @ID 
--						AND (@Sort < st.Sort OR (@Sort = st.Sort AND @Name < st.Name))
--					)
--					OR (st.SectionId IS NULL AND @ParentSectionId IS NULL AND st.ID <> @ID 
--						AND (@Sort < st.Sort OR (@Sort = st.Sort AND @Name < st.Name))
--					)
--				)
--			ORDER BY CASE WHEN (st.SectionId <> @ParentSectionId OR @ParentSectionId IS NULL) THEN 1 ELSE 0 END, st.Sort, st.Name
--		)
--
--		IF (@insertPoint IS NULL)
--		BEGIN
--			SELECT @insertPoint = RightMargin
--			FROM b_IBlockSection
--			WHERE IBlockId = @IBlockId
--				AND ID = @ParentSectionId
--
--			IF (@insertPoint IS NULL)
--			BEGIN
--				SELECT @insertPoint = COUNT('x') * 2 + 1
--				FROM b_IBlockSection
--				WHERE IBlockId = @IBlockId
--					AND LeftMargin IS NOT NULL
--			END
--		END
--
--		UPDATE b_IBlockSection SET
--			LeftMargin = CASE WHEN LeftMargin >= @insertPoint THEN LeftMargin + 2 ELSE LeftMargin END,
--			RightMargin = RightMargin + 2
--		WHERE IBlockId = @IBlockId
--			AND RightMargin >= @insertPoint
--
--		UPDATE b_IBlockSection SET
--			LeftMargin = @insertPoint,
--			RightMargin = @insertPoint + 1
--		WHERE ID = @ID
--
--		FETCH NEXT FROM temp_cursor INTO @ID, @ParentSectionId, @IBlockId, @Name, @Sort
--	END
GO
/****** Object:  StoredProcedure [dbo].[IBlockElement_IncViewsCount]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [IBlockElement_IncViewsCount](
	@elementId	INT,
	@inc		INT
	)
 AS
	SET NOCOUNT ON;
	
	UPDATE dbo.[b_IBlockElement] SET ViewsCount = ViewsCount + @inc WHERE ID = @elementId
GO
/****** Object:  StoredProcedure [dbo].[Search_SetTags]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Search_SetTags]
	@contentId int,
	@tags xml
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
		SET @TranStarted = 0
	
	DECLARE @tagsCache TABLE(name nvarchar(64))
	INSERT INTO @tagsCache
	SELECT 
		Tags.name.value('.', 'NVARCHAR(64)') AS tag
	FROM @tags.nodes('/tags/t') as Tags(name)
			
	DECLARE @tagsCount int
	SET @tagsCount = @@ROWCOUNT

	IF (@tagsCount > 0) BEGIN
		INSERT INTO b_Search_Tags(nameLower)
		SELECT name
		FROM @tagsCache
		WHERE NOT name IN (SELECT nameLower FROM b_Search_Tags)
	END

	DELETE FROM b_Search_ContentTags WHERE contentId = @contentId

	IF (@tagsCount > 0) BEGIN
		INSERT INTO b_Search_ContentTags(contentId, tagId) 
		SELECT @contentId, id
		FROM b_Search_Tags 
		WHERE nameLower IN (SELECT name FROM @tagsCache)
	END

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Search_CreateTag]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Search_CreateTag]
	@nameLower nvarchar(64),
	@status int = 0,
	@id int OUTPUT
AS
BEGIN
	SET NOCOUNT ON;

	SET @id = (SELECT id FROM b_Search_Tags WHERE nameLower = @nameLower)
	
	IF (@id IS NULL) BEGIN
		INSERT INTO b_Search_Tags (nameLower, [status]) VALUES (@nameLower, @status)
		SET @id = @@IDENTITY
	END ELSE
		UPDATE b_Search_Tags SET [status] = @status WHERE id = @id
END
GO
/****** Object:  StoredProcedure [dbo].[Search_GetInvalidTags]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Search_GetInvalidTags] 
	@tags xml,
	@minStatus int = 0
AS
BEGIN
	SET NOCOUNT ON;
	
	IF (@minStatus <= 0) BEGIN
		SELECT
			id AS Id, 
			nameLower AS Name, 
			status AS Status 
		FROM b_Search_Tags 
		WHERE 
			nameLower IN 
			(
				SELECT 
					Tags.name.value('.', 'NVARCHAR(64)')
				FROM @tags.nodes('/tags/t') AS Tags(name)
			)
			AND
			status < @minStatus	
	END ELSE BEGIN
		WITH tags AS
		(
			SELECT Tags.name.value('.', 'NVARCHAR(64)') AS name
			FROM @tags.nodes('/tags/t') AS Tags(name)
		)
		SELECT 
			id AS Id, 
			nameLower AS Name, 
			status AS Status
		FROM b_Search_Tags 
		WHERE 
			nameLower IN (SELECT name FROM tags)
			AND status < @minStatus	
		UNION
			SELECT 
				NULL AS Id, 
				name AS Name, 
				0 AS Status
			FROM tags
			WHERE NOT name IN (SELECT nameLower FROM b_Search_Tags)
	END
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_UpdateTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_UpdateTask]
	@TaskId int,
	@TaskName nvarchar(128),
	@TaskTitle nvarchar(255) = null,
	@Comment ntext = null
AS
BEGIN
	DECLARE @ErrorCode int
	SET @ErrorCode = 0

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
		SET @TranStarted = 0

	IF (NOT EXISTS( SELECT ID FROM dbo.b_RolesTasks WHERE ID = @TaskId ))
	BEGIN
		SET @ErrorCode = 9
		GOTO Cleanup
	END

	IF (EXISTS( SELECT ID FROM dbo.b_RolesTasks WHERE LOWER(@TaskName) = LoweredTaskName AND ID <> @TaskId ))
	BEGIN
		SET @ErrorCode = 8
		GOTO Cleanup
	END

	UPDATE dbo.b_RolesTasks SET
		TaskName = @TaskName,
		LoweredTaskName = LOWER(@TaskName),
		Title = @TaskTitle,
		Comment = @Comment
	WHERE ID = @TaskId
	
	IF (@@ERROR <> 0)
	BEGIN
		SET @ErrorCode = -1
		GOTO Cleanup
	END

	EXEC dbo.Roles_FillOperationsCache

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END

	RETURN(0)

Cleanup:

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		ROLLBACK TRANSACTION
	END

	RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveTaskFromTasks]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveTaskFromTasks]
	@TaskName nvarchar(128)
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TaskId int
    SET @TaskId = NULL

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	SELECT @TaskId = ID
	FROM dbo.b_RolesTasks
	WHERE LoweredTaskName = LOWER(@TaskName)

    IF (@TaskId IS NULL)
    BEGIN
        SELECT @ErrorCode = 9
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInTasks
    WHERE @TaskId = TaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_FillOperationsCache
	
    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveTaskFromOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveTaskFromOperations]
	@TaskName nvarchar(128)
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TaskId int
    SET @TaskId = NULL

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	SELECT @TaskId = ID
	FROM dbo.b_RolesTasks
	WHERE LoweredTaskName = LOWER(@TaskName)

    IF (@TaskId IS NULL)
    BEGIN
        SELECT @ErrorCode = 9
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInOperations
    WHERE @TaskId = TaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_FillOperationsCache
	
    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddRolesToTasks]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddRolesToTasks]
	@RoleNames nvarchar(4000),
	@TaskNames nvarchar(4000),
	@ModuleID varchar(50) = '',
	@ExternalID varchar(50) = ''
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@ModuleID IS NULL)
		SELECT @ModuleID = ''
	IF (@ExternalID IS NULL)
		SELECT @ExternalID = ''

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles table(RoleId int NOT NULL PRIMARY KEY)
	DECLARE @tbTasks table(TaskId int NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	SELECT r.ID
	FROM [dbo].[b_Roles] r, @tbNames t
	WHERE LOWER(t.Name) = r.LoweredRoleName

	IF (@@ROWCOUNT <> @Num)
	BEGIN

		SELECT TOP 1 Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT r.LoweredRoleName 
			FROM [dbo].[b_Roles] r, @tbRoles tr 
			WHERE tr.RoleId = r.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(2)
	END

	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1

	WHILE (@Pos <= LEN(@TaskNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @TaskNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@TaskNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@TaskNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbTasks
	SELECT u.ID
	FROM dbo.b_RolesTasks u, @tbNames t
	WHERE LOWER(t.Name) = u.LoweredTaskName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT u.LoweredTaskName
			FROM dbo.b_RolesTasks u, @tbTasks tu 
			WHERE tu.TaskId = u.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(12)
	END

	IF (EXISTS(
		SELECT *
		FROM dbo.b_RolesInTasks ur, @tbRoles tu, @tbTasks tr
		WHERE tu.RoleId = ur.RoleID
			AND tr.TaskId = ur.TaskID
			AND ur.ModuleID = @ModuleID
			AND ur.ExternalID = @ExternalID
	))
	BEGIN

		SELECT TOP 1 RoleName, TaskName
		FROM dbo.b_RolesInTasks ur, @tbRoles tu, @tbTasks tr, [dbo].[b_Roles] u, dbo.b_RolesTasks r
		WHERE u.ID = tu.RoleId 
			AND r.ID = tr.TaskId
			AND tu.RoleId = ur.RoleID
			AND tr.TaskId = ur.TaskID
			AND ur.ModuleID = @ModuleID
			AND ur.ExternalID = @ExternalID

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(14)
	END

	INSERT INTO dbo.b_RolesInTasks (RoleID, TaskID, ModuleID, ExternalID)
	SELECT RoleId, TaskId, @ModuleID, @ExternalID
	FROM @tbRoles, @tbTasks

	EXEC dbo.Roles_FillOperationsCache

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddTasksToOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddTasksToOperations]
	@TaskNames		nvarchar(4000),
	@OperationNames	nvarchar(4000),
	@CurrentTimeUtc	datetime
AS
BEGIN
	DECLARE @TranStarted   bit
	SET @TranStarted = 0

	IF( @@TRANCOUNT = 0 )
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames		table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbTasks		table(TaskId int NOT NULL PRIMARY KEY)
	DECLARE @tbOperations	table(OperationId int NOT NULL PRIMARY KEY)
	DECLARE @Num			int
	DECLARE @Pos			int
	DECLARE @NextPos		int
	DECLARE @Name			nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE(@Pos <= LEN(@TaskNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @TaskNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@TaskNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@TaskNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbTasks
	  SELECT r.ID
	  FROM   dbo.b_RolesTasks r, @tbNames t
	  WHERE  LOWER(t.Name) = r.LoweredTaskName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (
				SELECT r.LoweredTaskName 
				FROM dbo.b_RolesTasks r, @tbTasks tr 
				WHERE tr.TaskId = r.ID)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(9)
	END

	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1

	WHILE (@Pos <= LEN(@OperationNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @OperationNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@OperationNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@OperationNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbOperations
	  SELECT u.ID
	  FROM   dbo.b_RolesOperations u, @tbNames t
	  WHERE  LOWER(t.Name) = u.LoweredOperationName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (
				SELECT u.LoweredOperationName
				FROM dbo.b_RolesOperations u, @tbOperations tu 
				WHERE tu.OperationId = u.ID)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(12)
	END

	IF (EXISTS( SELECT * FROM dbo.b_RolesTasksInOperations ur, @tbTasks tu, @tbOperations tr WHERE tu.TaskId = ur.TaskID AND tr.OperationId = ur.OperationID ))
	BEGIN
		SELECT TOP 1 TaskName, OperationName
		FROM dbo.b_RolesTasksInOperations ur, @tbTasks tu, @tbOperations tr, dbo.b_RolesTasks u, dbo.b_RolesOperations r
		WHERE u.ID = tu.TaskId 
			AND r.ID = tr.OperationId
			AND tu.TaskId = ur.TaskID
			AND tr.OperationId = ur.OperationID

		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(13)
	END

	INSERT INTO dbo.b_RolesTasksInOperations (TaskID, OperationID)
	SELECT TaskId, OperationId
	FROM @tbTasks, @tbOperations

	EXEC dbo.Roles_FillOperationsCache

	IF( @TranStarted = 1 )
		COMMIT TRANSACTION
	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddTasksToTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddTasksToTask]
	@TaskName		nvarchar(128),
	@SubTaskNames	nvarchar(4000),
	@CurrentTimeUtc	datetime
AS
BEGIN
	DECLARE @TranStarted   bit
	SET @TranStarted = 0

	IF( @@TRANCOUNT = 0 )
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @TaskId		int
	SET @TaskId = NULL

	SELECT @TaskId = ID
	FROM dbo.b_RolesTasks
	WHERE LOWER(@TaskName) = LoweredTaskName

	IF (@TaskId IS NULL)
	BEGIN
		ROLLBACK TRANSACTION
		RETURN(9)
	END

	DECLARE @tbNames	table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbTasks	table(TaskId int NOT NULL PRIMARY KEY)

	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE(@Pos <= LEN(@SubTaskNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @SubTaskNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@SubTaskNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@SubTaskNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbTasks
	  SELECT r.ID
	  FROM   dbo.b_RolesTasks r, @tbNames t
	  WHERE  LOWER(t.Name) = r.LoweredTaskName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (
				SELECT r.LoweredTaskName 
				FROM dbo.b_RolesTasks r, @tbTasks tr 
				WHERE tr.TaskId = r.ID)

		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(9)
	END

	IF (EXISTS( SELECT * FROM dbo.b_RolesTasksInTasks rir, @tbTasks tr WHERE rir.TaskID = @TaskId AND rir.SubTaskID = tr.TaskId ))
	BEGIN
		SELECT TOP 1 r.TaskName
		FROM dbo.b_RolesTasksInTasks rir, @tbTasks tr, dbo.b_RolesTasks r
		WHERE rir.TaskID = @TaskId 
			AND rir.SubTaskID = tr.TaskId
			AND r.ID = tr.TaskId

		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(10)
	END

	INSERT INTO dbo.b_RolesTasksInTasks (TaskID, SubTaskID)
	SELECT @TaskId, TaskId
	FROM @tbTasks

	EXEC dbo.Roles_FillOperationsCache

	IF( @TranStarted = 1 )
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_DeleteTask]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_DeleteTask]
	@TaskId int = NULL,
    @TaskName nvarchar(256) = NULL
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

	IF ((@TaskId IS NULL OR @TaskId = 0) AND @TaskName IS NOT NULL)
	BEGIN
		SELECT @TaskId = ID
		FROM dbo.b_RolesTasks
		WHERE LoweredTaskName = LOWER(@TaskName)
	END

    IF (@TaskId IS NULL OR @TaskId = 0)
    BEGIN
        SELECT @ErrorCode = 9
        GOTO Cleanup
    END


	INSERT INTO dbo.b_RolesTasksInTasks(TaskID, SubTaskID)
    SELECT rir1.TaskID, rir2.SubTaskID
    FROM dbo.b_RolesTasksInTasks rir1, dbo.b_RolesTasksInTasks rir2
    WHERE rir1.SubTaskID = @TaskId
		AND @TaskId = rir2.TaskID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesTasksInTasks rir3 WHERE rir3.TaskID = rir1.TaskID AND rir3.SubTaskID = rir2.SubTaskID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	INSERT INTO dbo.b_RolesTasksInOperations(TaskID, OperationID)
	SELECT rir.TaskID, rio.OperationID
	FROM b_RolesTasksInTasks rir, b_RolesTasksInOperations rio
	WHERE rir.SubTaskID = @TaskId
		AND @TaskId = rio.TaskID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesTasksInOperations rio1 WHERE rio1.TaskID = rir.TaskID AND rio1.OperationID = rio.OperationID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	INSERT INTO dbo.b_RolesInTasks(RoleID, TaskID, ModuleID, ExternalID)
	SELECT rit.RoleID, rir.SubTaskID, rit.ModuleID, rit.ExternalID
	FROM b_RolesTasksInTasks rir, b_RolesInTasks rit
	WHERE rir.TaskID = @TaskId
		AND @TaskId = rit.TaskID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesInTasks rit1 WHERE rit1.RoleID = rit.RoleID AND rit1.TaskID = rir.TaskID AND rit1.ModuleID = rit.ModuleID AND rit1.ExternalID = rit.ExternalID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END


    DELETE FROM dbo.b_RolesInTasks
    WHERE @TaskId = TaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInTasks
    WHERE @TaskId = TaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInTasks
    WHERE @TaskId = SubTaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInOperations
    WHERE @TaskId = TaskID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasks
    WHERE @TaskId = ID

	EXEC dbo.Roles_FillOperationsCache

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_DeleteOperation]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_DeleteOperation]
	@OperationId int = NULL,
    @OperationName nvarchar(128) = NULL
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

	IF ((@OperationId IS NULL OR @OperationId = 0) AND @OperationName IS NOT NULL)
	BEGIN
		SELECT @OperationId = ID
		FROM dbo.b_RolesOperations
		WHERE LoweredOperationName = LOWER(@OperationName)
	END

    IF (@OperationId IS NULL OR @OperationId = 0)
    BEGIN
        SELECT @ErrorCode = 9
        GOTO Cleanup
    END


    DELETE FROM dbo.b_RolesInOperations
    WHERE @OperationId = OperationID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesTasksInOperations
    WHERE @OperationId = OperationID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesOperations
    WHERE @OperationId = ID

	EXEC dbo.Roles_FillOperationsCache

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddRolesToOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddRolesToOperations]
	@RoleNames nvarchar(4000),
	@OperationNames nvarchar(4000),
	@ModuleID varchar(50) = '',
	@ExternalID varchar(50) = ''
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@ModuleID IS NULL)
		SELECT @ModuleID = ''
	IF (@ExternalID IS NULL)
		SELECT @ExternalID = ''

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles table(RoleId int NOT NULL PRIMARY KEY)
	DECLARE @tbOperations table(OperationId int NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	SELECT r.ID
	FROM [dbo].[b_Roles] r, @tbNames t
	WHERE LOWER(t.Name) = r.LoweredRoleName

	IF (@@ROWCOUNT <> @Num)
	BEGIN

		SELECT TOP 1 Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT r.LoweredRoleName 
			FROM [dbo].[b_Roles] r, @tbRoles tr 
			WHERE tr.RoleId = r.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(2)
	END

	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1

	WHILE (@Pos <= LEN(@OperationNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @OperationNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@OperationNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@OperationNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbOperations
	SELECT u.ID
	FROM dbo.b_RolesOperations u, @tbNames t
	WHERE LOWER(t.Name) = u.LoweredOperationName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT u.LoweredOperationName
			FROM dbo.b_RolesOperations u, @tbOperations tu 
			WHERE tu.OperationId = u.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(12)
	END

	IF (EXISTS(
		SELECT *
		FROM dbo.b_RolesInOperations ur, @tbRoles tu, @tbOperations tr
		WHERE tu.RoleId = ur.RoleID
			AND tr.OperationId = ur.OperationID
			AND ur.ModuleID = @ModuleID
			AND ur.ExternalID = @ExternalID
	))
	BEGIN

		SELECT TOP 1 RoleName, OperationName
		FROM dbo.b_RolesInOperations ur, @tbRoles tu, @tbOperations tr, [dbo].[b_Roles] u, dbo.b_RolesOperations r
		WHERE u.ID = tu.RoleId 
			AND r.ID = tr.OperationId
			AND tu.RoleId = ur.RoleID
			AND tr.OperationId = ur.OperationID
			AND ur.ModuleID = @ModuleID
			AND ur.ExternalID = @ExternalID

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(14)
	END

	INSERT INTO dbo.b_RolesInOperations (RoleID, OperationID, ModuleID, ExternalID)
	SELECT RoleId, OperationId, @ModuleID, @ExternalID
	FROM @tbRoles, @tbOperations

	EXEC dbo.Roles_FillOperationsCache

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_UpdateOperation]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_UpdateOperation]
    @OperationId int,
	@OperationName nvarchar(128),
	@OperationType nvarchar(128),
	@ModuleId varchar(50),
    @Comment ntext = null
AS
BEGIN
	DECLARE @ErrorCode int
	SET @ErrorCode = 0

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
		SET @TranStarted = 0

	IF (NOT EXISTS( SELECT ID FROM dbo.b_RolesOperations WHERE ID = @OperationId ))
	BEGIN
		SET @ErrorCode = 12
		GOTO Cleanup
	END

	IF (EXISTS( SELECT ID FROM dbo.b_RolesOperations WHERE LOWER(@OperationName) = LoweredOperationName AND ID <> @OperationId ))
	BEGIN
		SET @ErrorCode = 11
		GOTO Cleanup
	END

	UPDATE dbo.b_RolesOperations SET
		OperationName = @OperationName,
		LoweredOperationName = LOWER(@OperationName),
		OperationType = @OperationType,
		ModuleID = @ModuleId,
		Comment = @Comment
	WHERE ID = @OperationId
	
	IF (@@ERROR <> 0)
	BEGIN
		SET @ErrorCode = -1
		GOTO Cleanup
	END

	EXEC dbo.Roles_FillOperationsCache

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END

	RETURN(0)

Cleanup:

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		ROLLBACK TRANSACTION
	END

	RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveRolesFromRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveRolesFromRole]
	@RoleName nvarchar(128)
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @RoleId int
    SET @RoleId = NULL

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LoweredRoleName = LOWER(@RoleName)

    IF (@RoleId IS NULL)
    BEGIN
        SELECT @ErrorCode = 2
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesInRoles
    WHERE @RoleId = RoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_DropEffectivePolicy @RoleId
	EXEC dbo.Roles_FillEffectivePolicy

	EXEC dbo.Roles_FillOperationsCache
	
    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_UpdateRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_UpdateRole] 
	@RoleId int,
	@RoleName nvarchar(128),
	@RoleTitle nvarchar(255) = null,
	@Active bit = 1,
	@Comment ntext = null,
	@Policy nvarchar(4000) = null
AS
BEGIN
	DECLARE @ErrorCode int
	SET @ErrorCode = 0

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
		SET @TranStarted = 0

	IF (NOT EXISTS( SELECT ID FROM dbo.b_roles WHERE ID = @RoleId ))
	BEGIN
		SET @ErrorCode = 2
		GOTO Cleanup
	END

	IF (EXISTS( SELECT ID FROM dbo.b_roles WHERE LOWER(@RoleName) = LoweredRoleName AND ID <> @RoleId ))
	BEGIN
		SET @ErrorCode = 4
		GOTO Cleanup
	END

	IF (@Policy IS NULL OR @Policy = '')
	BEGIN
		SET @Policy = '<Policy/>'
	END

	IF (@RoleId = 1 OR @RoleId = 2 OR @RoleId = 3)
	BEGIN
		UPDATE dbo.b_roles SET
			Active = @Active,
			Title = @RoleTitle,
			Comment = @Comment,
			Policy = @Policy,
			EffectivePolicy = NULL
		WHERE ID = @RoleId
	END
	ELSE
	BEGIN
		UPDATE dbo.b_roles SET
			RoleName = @RoleName,
			Title = @RoleTitle,
			LoweredRoleName = LOWER(@RoleName),
			Active = @Active,
			Comment = @Comment,
			Policy = @Policy,
			EffectivePolicy = NULL
		WHERE ID = @RoleId
	END
	
	IF (@@ERROR <> 0)
	BEGIN
		SET @ErrorCode = -1
		GOTO Cleanup
	END

	EXEC dbo.Roles_DropEffectivePolicy @RoleId
	EXEC dbo.Roles_FillEffectivePolicy
	EXEC dbo.Roles_FillOperationsCache
	EXEC dbo.Roles_FillRolesCache

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END

	RETURN(0)

Cleanup:

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		ROLLBACK TRANSACTION
	END

	RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_AddRolesToRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_AddRolesToRole]
	@RoleName nvarchar(128),
	@SubRoleNames nvarchar(4000)
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @RoleId int
	SET @RoleId = NULL

	SELECT @RoleId = ID
	FROM [dbo].[b_Roles]
	WHERE LOWER(@RoleName) = LoweredRoleName

	IF (@RoleId IS NULL)
	BEGIN
		ROLLBACK TRANSACTION
		RETURN(2)
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles table(RoleId int NOT NULL PRIMARY KEY)

	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@SubRoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @SubRoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@SubRoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@SubRoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	SELECT r.ID
	FROM [dbo].[b_Roles] r, @tbNames t
	WHERE LOWER(t.Name) = r.LoweredRoleName

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT r.LoweredRoleName 
			FROM [dbo].[b_Roles] r, @tbRoles tr 
			WHERE tr.RoleId = r.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(2)
	END

	IF (EXISTS(
		SELECT *
		FROM dbo.b_RolesInRoles rir, @tbRoles tr
		WHERE rir.RoleID = @RoleId
			AND rir.SubRoleID = tr.RoleId
	))
	BEGIN
		SELECT TOP 1 r.RoleName
		FROM dbo.b_RolesInRoles rir, @tbRoles tr, [dbo].[b_Roles] r
		WHERE rir.RoleID = @RoleId 
			AND rir.SubRoleID = tr.RoleId
			AND r.ID = tr.RoleId

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(7)
	END

	INSERT INTO dbo.b_RolesInRoles (RoleID, SubRoleID)
	SELECT @RoleId, RoleId
	FROM @tbRoles



	EXEC dbo.Roles_DropEffectivePolicy @RoleId
	EXEC dbo.Roles_FillEffectivePolicy

	EXEC dbo.Roles_FillOperationsCache
	EXEC dbo.Roles_FillRolesCache

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_CreateRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_CreateRole]
    @RoleName nvarchar(128),
    @RoleTitle nvarchar(255) = null,
    @Active bit = 1,
    @Comment ntext = null,
    @Policy nvarchar(4000) = null,
    @RoleId int OUTPUT
AS
BEGIN
	SELECT @RoleId = NULL

	DECLARE @ErrorCode int
	SET @ErrorCode = 0

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END
	ELSE
		SET @TranStarted = 0

	IF (EXISTS( SELECT ID FROM dbo.b_roles WHERE LoweredRoleName = LOWER(@RoleName) ))
	BEGIN
		SET @ErrorCode = 4
		GOTO Cleanup
	END

	IF (@Policy IS NULL OR @Policy = '')
	BEGIN
		SET @Policy = '<Policy/>'
	END

	INSERT INTO b_Roles(RoleName, LoweredRoleName, Active, Comment, Policy, EffectivePolicy, Title)
	VALUES (@RoleName, LOWER(@RoleName), @Active, @Comment, @Policy, NULL, @RoleTitle)

	IF (@@ERROR <> 0)
	BEGIN
		SET @ErrorCode = -1
		GOTO Cleanup
	END

	SELECT @RoleId = @@IDENTITY

	EXEC dbo.Roles_FillEffectivePolicy

	EXEC dbo.Roles_FillRolesCache

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		COMMIT TRANSACTION
	END

	RETURN(0)

Cleanup:

	IF (@TranStarted = 1)
	BEGIN
		SET @TranStarted = 0
		ROLLBACK TRANSACTION
	END

	RETURN @ErrorCode

END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveRoleFromOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveRoleFromOperations]
	@RoleName nvarchar(128) = NULL,
	@ModuleId varchar(128) = NULL,
	@ExternalId varchar(128) = NULL
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @RoleId int
    SET @RoleId = NULL

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	IF (@RoleName IS NOT NULL)
	BEGIN
		SELECT @RoleId = ID
		FROM [dbo].[b_Roles]
		WHERE LoweredRoleName = LOWER(@RoleName)

		IF (@RoleId IS NULL)
		BEGIN
			SELECT @ErrorCode = 2
			GOTO Cleanup
		END
	END

    DELETE FROM dbo.b_RolesInOperations
    WHERE (@RoleId IS NULL OR @RoleId IS NOT NULL AND @RoleId = RoleID)
		AND (@ModuleId IS NULL AND (ModuleID IS NULL OR ModuleID = '')
			OR @ModuleId IS NOT NULL AND ModuleID = @ModuleId AND ExternalID = @ExternalId)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_FillOperationsCache
	
    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveRoleFromTasks]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveRoleFromTasks]
	@RoleName nvarchar(128) = NULL,
	@ModuleId varchar(128) = NULL,
	@ExternalId varchar(128) = NULL
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @RoleId int
    SET @RoleId = NULL

	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	IF (@RoleName IS NOT NULL)
	BEGIN
		SELECT @RoleId = ID
		FROM [dbo].[b_Roles]
		WHERE LoweredRoleName = LOWER(@RoleName)

		IF (@RoleId IS NULL)
		BEGIN
			SELECT @ErrorCode = 2
			GOTO Cleanup
		END
	END

    DELETE FROM dbo.b_RolesInTasks
    WHERE (@RoleId IS NULL OR @RoleId IS NOT NULL AND @RoleId = RoleID)
		AND (@ModuleId IS NULL AND (ModuleID IS NULL OR ModuleID = '')
			OR @ModuleId IS NOT NULL AND ModuleID = @ModuleId AND ExternalID = @ExternalId)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_FillOperationsCache
	
    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_DeleteRole]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_DeleteRole]
	@RoleId int = NULL,
    @RoleName nvarchar(256) = NULL,
    @DeleteOnlyIfRoleIsEmpty bit = 1
AS
BEGIN
    DECLARE @ErrorCode int
    SET @ErrorCode = 0

    DECLARE @TranStarted bit
    SET @TranStarted = 0

    IF (@@TRANCOUNT = 0)
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

	IF ((@RoleId IS NULL OR @RoleId = 0) AND @RoleName IS NOT NULL)
	BEGIN
		SELECT @RoleId = ID
		FROM [dbo].[b_Roles]
		WHERE LoweredRoleName = LOWER(@RoleName)
	END

    IF (@RoleId IS NULL OR @RoleId = 0)
    BEGIN
        SELECT @ErrorCode = 2
        GOTO Cleanup
    END

	IF (@RoleId = 1 OR @RoleId = 2 OR @RoleId = 3)
	BEGIN
		SET @ErrorCode = 50
		GOTO Cleanup
	END

    IF (@DeleteOnlyIfRoleIsEmpty <> 0)
    BEGIN
        IF (EXISTS(SELECT RoleID FROM dbo.b_UsersInRoles WHERE @RoleId = RoleID))
        BEGIN
            SELECT @ErrorCode = 5
            GOTO Cleanup
        END
    END

    DELETE FROM dbo.b_UsersInRoles
    WHERE @RoleId = RoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END


	INSERT INTO dbo.b_RolesInRoles(RoleID, SubRoleID)
    SELECT rir1.RoleID, rir2.SubRoleID
    FROM dbo.b_RolesInRoles rir1, dbo.b_RolesInRoles rir2
    WHERE rir1.SubRoleID = @RoleId
		AND @RoleId = rir2.RoleID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesInRoles rir3 WHERE rir3.RoleID = rir1.RoleID AND rir3.SubRoleID = rir2.SubRoleID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	INSERT INTO dbo.b_RolesInTasks(RoleID, TaskID, ModuleID, ExternalID)
	SELECT rir.RoleID, rit.TaskID, rit.ModuleID, rit.ExternalID
	FROM b_RolesInRoles rir, b_RolesInTasks rit
	WHERE rir.SubRoleID = @RoleId
		AND @RoleId = rit.RoleID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesInTasks rit1 WHERE rit1.RoleID = rir.RoleID AND rit1.TaskID = rit.TaskID AND rit1.ModuleID = rit.ModuleID AND rit1.ExternalID = rit.ExternalID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	INSERT INTO dbo.b_RolesInOperations(RoleID, OperationID, ModuleID, ExternalID)
	SELECT rir.RoleID, rio.OperationID, rio.ModuleID, rio.ExternalID
	FROM b_RolesInRoles rir, b_RolesInOperations rio
	WHERE rir.SubRoleID = @RoleId
		AND @RoleId = rio.RoleID
		AND NOT EXISTS(SELECT 'x' FROM dbo.b_RolesInOperations rio1 WHERE rio1.RoleID = rir.RoleID AND rio1.OperationID = rio.OperationID AND rio1.ModuleID = rio.ModuleID AND rio1.ExternalID = rio.ExternalID)

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

	EXEC dbo.Roles_DropEffectivePolicy @RoleId

    DELETE FROM dbo.b_RolesInRoles
    WHERE @RoleId = RoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesInRoles
    WHERE @RoleId = SubRoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesInTasks
    WHERE @RoleId = RoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.b_RolesInOperations
    WHERE @RoleId = RoleID

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM [dbo].[b_Roles]
    WHERE @RoleId = ID

	EXEC dbo.Roles_FillEffectivePolicy

	EXEC dbo.Roles_FillOperationsCache
	EXEC dbo.Roles_FillRolesCache

    IF (@@ERROR <> 0)
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF (@TranStarted = 1)
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END
GO
/****** Object:  StoredProcedure [dbo].[Roles_RemoveRolesFromOperations]    Script Date: 10/01/2009 19:30:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Roles_RemoveRolesFromOperations]
	@RoleNames nvarchar(4000),
	@OperationNames nvarchar(4000),
	@ModuleID varchar(50) = '',
	@ExternalID int = 0
AS
BEGIN
	DECLARE @TranStarted bit
	SET @TranStarted = 0

	IF (@@TRANCOUNT = 0)
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles table(RoleId int NOT NULL PRIMARY KEY)
	DECLARE @tbOperations table(OperationId int NOT NULL PRIMARY KEY)
	DECLARE @Num int
	DECLARE @Pos int
	DECLARE @NextPos int
	DECLARE @Name nvarchar(256)
	DECLARE @CountAll int
	DECLARE @CountU int
	DECLARE @CountR int


	SET @Num = 0
	SET @Pos = 1
	WHILE (@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	SELECT ID
	FROM [dbo].[b_Roles] ar, @tbNames t
	WHERE LOWER(t.Name) = ar.LoweredRoleName

	SELECT @CountR = @@ROWCOUNT

	IF (@CountR <> @Num)
	BEGIN
		SELECT TOP 1 N'', Name
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT ar.LoweredRoleName
			FROM [dbo].[b_Roles] ar, @tbRoles r
			WHERE r.RoleId = ar.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(2)
	END


	DELETE FROM @tbNames
	WHERE 1 = 1

	SET @Num = 0
	SET @Pos = 1


	WHILE (@Pos <= LEN(@OperationNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N',', @OperationNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@OperationNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@OperationNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos + 1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbOperations
	SELECT ID
	FROM dbo.b_Operations ar, @tbNames t
	WHERE LOWER(t.Name) = ar.LoweredOperationName

	SELECT @CountU = @@ROWCOUNT

	IF (@CountU <> @Num)
	BEGIN
		SELECT TOP 1 Name, N''
		FROM @tbNames
		WHERE LOWER(Name) NOT IN (
			SELECT au.LoweredOperationName
			FROM dbo.b_Operations au, @tbOperations u
			WHERE u.OperationId = au.ID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(1)
	END

	SELECT @CountAll = COUNT(*)
	FROM dbo.b_RolesInOperations ur, @tbOperations u, @tbRoles r
	WHERE ur.OperationID = u.OperationId
		AND ur.RoleID = r.RoleId
		AND ur.ModuleID = @ModuleID
		AND ur.ExternalID = @ExternalID

	IF (@CountAll <> @CountU * @CountR)
	BEGIN
		SELECT TOP 1 OperationName, RoleName
		FROM @tbOperations tu, @tbRoles tr, dbo.b_Operations u, [dbo].[b_Roles] r
		WHERE u.ID = tu.OperationId
			AND r.ID = tr.RoleId
			AND tu.OperationId NOT IN (
				SELECT ur.OperationID
				FROM dbo.b_RolesInOperations ur
				WHERE ur.RoleID = tr.RoleId
					AND ur.ModuleID = @ModuleID
					AND ur.ExternalID = @ExternalID)
			AND tr.RoleId NOT IN (
				SELECT ur.RoleID 
				FROM dbo.b_UsersInRoles ur 
				WHERE ur.UserID = tu.UserId
					AND ur.ModuleID = @ModuleID
					AND ur.ExternalID = @ExternalID)

		IF (@TranStarted = 1)
			ROLLBACK TRANSACTION

		RETURN(6)
	END

	DELETE FROM dbo.b_RolesInOperations
	WHERE OperationID IN (SELECT OperationId FROM @tbOperations)
		AND RoleID IN (SELECT RoleId FROM @tbRoles)
		AND ModuleID = @ModuleID
		AND ExternalID = @ExternalID

	EXEC dbo.Roles_FillOperationsCache

	IF (@TranStarted = 1)
		COMMIT TRANSACTION

	RETURN(0)
END
GO
/****** Object:  Default [DF_b_File_UpdateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_File] ADD  CONSTRAINT [DF_b_File_UpdateDate]  DEFAULT (getdate()) FOR [UpdateDate]
GO
/****** Object:  Default [DF_b_File_ContentType]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_File] ADD  CONSTRAINT [DF_b_File_ContentType]  DEFAULT ('IMAGE') FOR [ContentType]
GO
/****** Object:  Default [DF_b_FileAction_Action]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_FileAction] ADD  CONSTRAINT [DF_b_FileAction_Action]  DEFAULT ('D') FOR [Action]
GO
/****** Object:  Default [DF_b_FileAction_CreateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_FileAction] ADD  CONSTRAINT [DF_b_FileAction_CreateDate]  DEFAULT (getdate()) FOR [CreateDate]
GO
/****** Object:  Default [DF_b_Forum_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_Active]  DEFAULT ((1)) FOR [Active]
GO
/****** Object:  Default [DF_b_Forum_DateCreate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_DateCreate]  DEFAULT (getdate()) FOR [DateCreate]
GO
/****** Object:  Default [DF_b_Forum_CategoryId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_CategoryId]  DEFAULT ((0)) FOR [CategoryId]
GO
/****** Object:  Default [DF_b_Forum_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_Sort]  DEFAULT ((10)) FOR [Sort]
GO
/****** Object:  Default [DF_b_Forum_Topics]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_Topics]  DEFAULT ((0)) FOR [Topics]
GO
/****** Object:  Default [DF_b_Forum_QueuedTopics]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_QueuedTopics]  DEFAULT ((0)) FOR [QueuedTopics]
GO
/****** Object:  Default [DF_b_Forum_Posts]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_Posts]  DEFAULT ((0)) FOR [Replies]
GO
/****** Object:  Default [DF_b_Forum_QueuedPosts]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_QueuedPosts]  DEFAULT ((0)) FOR [QueuedReplies]
GO
/****** Object:  Default [DF_b_Forum_AllowBBCode]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_AllowBBCode]  DEFAULT ((1)) FOR [AllowBBCode]
GO
/****** Object:  Default [DF_b_Forum_AllowSmiles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_AllowSmiles]  DEFAULT ((1)) FOR [AllowSmiles]
GO
/****** Object:  Default [DF_b_Forum_LastPostId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_LastPostId]  DEFAULT ((0)) FOR [LastPostId]
GO
/****** Object:  Default [DF_b_Forum_LastPosterId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_LastPosterId]  DEFAULT ((0)) FOR [LastPosterId]
GO
/****** Object:  Default [DF_b_Forum_IndexContent]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Forum] ADD  CONSTRAINT [DF_b_Forum_IndexContent]  DEFAULT ((1)) FOR [IndexContent]
GO
/****** Object:  Default [DF_b_ForumCategory_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumCategory] ADD  CONSTRAINT [DF_b_ForumCategory_Sort]  DEFAULT ((10)) FOR [Sort]
GO
/****** Object:  Default [DF_b_ForumPost_AuthorId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost] ADD  CONSTRAINT [DF_b_ForumPost_AuthorId]  DEFAULT ((0)) FOR [AuthorId]
GO
/****** Object:  Default [DF_b_ForumPost_ParentPostId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost] ADD  CONSTRAINT [DF_b_ForumPost_ParentPostId]  DEFAULT ((0)) FOR [ParentPostId]
GO
/****** Object:  Default [DF_b_ForumPost_Approved]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost] ADD  CONSTRAINT [DF_b_ForumPost_Approved]  DEFAULT ((1)) FOR [Approved]
GO
/****** Object:  Default [DF_b_ForumPost_DateCreate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost] ADD  CONSTRAINT [DF_b_ForumPost_DateCreate]  DEFAULT (getdate()) FOR [DateCreate]
GO
/****** Object:  Default [DF_b_ForumPost_AllowSmiles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost] ADD  CONSTRAINT [DF_b_ForumPost_AllowSmiles]  DEFAULT ((1)) FOR [AllowSmiles]
GO
/****** Object:  Default [DF_b_ForumTopic_DateCreate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_DateCreate]  DEFAULT (getdate()) FOR [DateCreate]
GO
/****** Object:  Default [DF_b_ForumTopic_StarterId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_StarterId]  DEFAULT ((0)) FOR [AuthorId]
GO
/****** Object:  Default [DF_b_ForumTopic_Open]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_Open]  DEFAULT ((0)) FOR [Closed]
GO
/****** Object:  Default [DF_b_ForumTopic_Approved]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_Approved]  DEFAULT ((1)) FOR [Approved]
GO
/****** Object:  Default [DF_b_ForumTopic_StickyIndex]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_StickyIndex]  DEFAULT ((0)) FOR [StickyIndex]
GO
/****** Object:  Default [DF_b_ForumTopic_Posts]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_Posts]  DEFAULT ((0)) FOR [Replies]
GO
/****** Object:  Default [DF_b_ForumTopic_QueuedPosts]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_QueuedPosts]  DEFAULT ((0)) FOR [QueuedReplies]
GO
/****** Object:  Default [DF_b_ForumTopic_Views]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_Views]  DEFAULT ((0)) FOR [Views]
GO
/****** Object:  Default [DF_b_ForumTopic_MovedTo]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_MovedTo]  DEFAULT ((0)) FOR [MovedTo]
GO
/****** Object:  Default [DF_b_ForumTopic_FirstPostId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_FirstPostId]  DEFAULT ((0)) FOR [FirstPostId]
GO
/****** Object:  Default [DF_b_ForumTopic_LastPostId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_LastPostId]  DEFAULT ((0)) FOR [LastPostId]
GO
/****** Object:  Default [DF_b_ForumTopic_LastPosterId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic] ADD  CONSTRAINT [DF_b_ForumTopic_LastPosterId]  DEFAULT ((0)) FOR [LastPosterId]
GO
/****** Object:  Default [DF_b_ForumUser_Posts]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumUser] ADD  CONSTRAINT [DF_b_ForumUser_Posts]  DEFAULT ((0)) FOR [Posts]
GO
/****** Object:  Default [DF_b_IBlock_UpdateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_UpdateDate]  DEFAULT (getdate()) FOR [UpdateDate]
GO
/****** Object:  Default [DF_b_IBlock_CreateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_CreateDate]  DEFAULT (getdate()) FOR [CreateDate]
GO
/****** Object:  Default [DF_b_IBlock_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_Active]  DEFAULT ('Y') FOR [Active]
GO
/****** Object:  Default [DF_b_IBlock_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_Sort]  DEFAULT ((50)) FOR [Sort]
GO
/****** Object:  Default [DF_b_IBlock_DescriptionType]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_DescriptionType]  DEFAULT ('T') FOR [DescriptionType]
GO
/****** Object:  Default [DF_b_IBlock_IndexContent]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock] ADD  CONSTRAINT [DF_b_IBlock_IndexContent]  DEFAULT ('Y') FOR [IndexContent]
GO
/****** Object:  Default [DF_b_IBlockElement_UpdateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_UpdateDate]  DEFAULT (getdate()) FOR [UpdateDate]
GO
/****** Object:  Default [DF_b_IBlockElement_CreateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_CreateDate]  DEFAULT (getdate()) FOR [CreateDate]
GO
/****** Object:  Default [DF_b_IBlockElement_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_Active]  DEFAULT ('Y') FOR [Active]
GO
/****** Object:  Default [DF_b_IBlockElement_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_Sort]  DEFAULT ((50)) FOR [Sort]
GO
/****** Object:  Default [DF_b_IBlockElement_PreviewTextType]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_PreviewTextType]  DEFAULT ('T') FOR [PreviewTextType]
GO
/****** Object:  Default [DF_b_IBlockElement_DetailTextType]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  CONSTRAINT [DF_b_IBlockElement_DetailTextType]  DEFAULT ('T') FOR [DetailTextType]
GO
/****** Object:  Default [DF__b_IBlockE__Views__63D8CE75]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement] ADD  DEFAULT ((0)) FOR [ViewsCount]
GO
/****** Object:  Default [DF_b_IBlockSection_UpdateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_UpdateDate]  DEFAULT (getdate()) FOR [UpdateDate]
GO
/****** Object:  Default [DF_b_IBlockSection_CreateDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_CreateDate]  DEFAULT (getdate()) FOR [CreateDate]
GO
/****** Object:  Default [DF_b_IBlockSection_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_Active]  DEFAULT ('Y') FOR [Active]
GO
/****** Object:  Default [DF_b_IBlockSection_ActiveGlobal]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_ActiveGlobal]  DEFAULT ('Y') FOR [ActiveGlobal]
GO
/****** Object:  Default [DF_b_IBlockSection_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_Sort]  DEFAULT ((50)) FOR [Sort]
GO
/****** Object:  Default [DF_b_IBlockSection_DescriptionType]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection] ADD  CONSTRAINT [DF_b_IBlockSection_DescriptionType]  DEFAULT ('T') FOR [DescriptionType]
GO
/****** Object:  Default [DF_b_IBlock_Type_HaveSections]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockType] ADD  CONSTRAINT [DF_b_IBlock_Type_HaveSections]  DEFAULT ('Y') FOR [HaveSections]
GO
/****** Object:  Default [DF_b_IBlock_Type_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockType] ADD  CONSTRAINT [DF_b_IBlock_Type_Sort]  DEFAULT ((50)) FOR [Sort]
GO
/****** Object:  Default [DF_b_Language_Sort]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Language] ADD  CONSTRAINT [DF_b_Language_Sort]  DEFAULT ((100)) FOR [Sort]
GO
/****** Object:  Default [DF_b_Language_Default]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Language] ADD  CONSTRAINT [DF_b_Language_Default]  DEFAULT ((0)) FOR [Default]
GO
/****** Object:  Default [DF_b_Language_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Language] ADD  CONSTRAINT [DF_b_Language_Active]  DEFAULT ((1)) FOR [Active]
GO
/****** Object:  Default [DF_b_Language_Culture]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Language] ADD  CONSTRAINT [DF_b_Language_Culture]  DEFAULT ('en-US') FOR [Culture]
GO
/****** Object:  Default [DF_b_Log_type]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_type]  DEFAULT ((0)) FOR [type]
GO
/****** Object:  Default [DF_b_Log_code]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_code]  DEFAULT ((0)) FOR [code]
GO
/****** Object:  Default [DF_b_Log_source_1]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_source_1]  DEFAULT ('') FOR [source]
GO
/****** Object:  Default [DF_b_Log_source]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_source]  DEFAULT ('Unknown') FOR [title]
GO
/****** Object:  Default [DF_b_Log_description]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_description]  DEFAULT ('') FOR [message]
GO
/****** Object:  Default [DF_b_Log_occured]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_occured]  DEFAULT (getdate()) FOR [occured]
GO
/****** Object:  Default [DF_b_Log_body_type]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Log] ADD  CONSTRAINT [DF_b_Log_body_type]  DEFAULT ('text') FOR [text_type]
GO
/****** Object:  Default [DF_b_MailerEvents_duplicates]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerEvents] ADD  CONSTRAINT [DF_b_MailerEvents_duplicates]  DEFAULT ('Y') FOR [duplicate]
GO
/****** Object:  Default [DF_b_MailerEvents_status]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerEvents] ADD  CONSTRAINT [DF_b_MailerEvents_status]  DEFAULT ('N') FOR [status]
GO
/****** Object:  Default [DF_b_MailerEvents_last_updated]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerEvents] ADD  CONSTRAINT [DF_b_MailerEvents_last_updated]  DEFAULT (getdate()) FOR [last_updated]
GO
/****** Object:  Default [DF_b_MailerEvents_template_id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerEvents] ADD  CONSTRAINT [DF_b_MailerEvents_template_id]  DEFAULT ((0)) FOR [template_id]
GO
/****** Object:  Default [DF_b_MailerTemplates_lastupdated]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_lastupdated]  DEFAULT (getdate()) FOR [last_updated]
GO
/****** Object:  Default [DF_b_MailerTemplates_active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_active]  DEFAULT ((1)) FOR [active]
GO
/****** Object:  Default [DF_b_MailerTemplates_email_from]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_email_from]  DEFAULT ('') FOR [email_from]
GO
/****** Object:  Default [DF_b_MailerTemplates_email_to]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_email_to]  DEFAULT ('') FOR [email_to]
GO
/****** Object:  Default [DF_b_MailerTemplates_subject]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_subject]  DEFAULT ('') FOR [subject]
GO
/****** Object:  Default [DF_b_MailerTemplates_message]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_message]  DEFAULT ('') FOR [message]
GO
/****** Object:  Default [DF_b_MailerTemplates_body_type]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_body_type]  DEFAULT ('text') FOR [body_type]
GO
/****** Object:  Default [DF_b_MailerTemplates_bcc]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates] ADD  CONSTRAINT [DF_b_MailerTemplates_bcc]  DEFAULT ('') FOR [bcc]
GO
/****** Object:  Default [DF_b_MailerTemplates_Sites_siteId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_MailerTemplates_Sites] ADD  CONSTRAINT [DF_b_MailerTemplates_Sites_siteId]  DEFAULT ('') FOR [siteId]
GO
/****** Object:  Default [DF_b_Options_SiteId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Options] ADD  CONSTRAINT [DF_b_Options_SiteId]  DEFAULT (NULL) FOR [SiteId]
GO
/****** Object:  Default [DF_b_roles_Active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Roles] ADD  CONSTRAINT [DF_b_roles_Active]  DEFAULT ((1)) FOR [Active]
GO
/****** Object:  Default [DF_b_RolesInOperations_ModuleID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInOperations] ADD  CONSTRAINT [DF_b_RolesInOperations_ModuleID]  DEFAULT ('') FOR [ModuleID]
GO
/****** Object:  Default [DF_b_RolesInOperations_ExternalID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInOperations] ADD  CONSTRAINT [DF_b_RolesInOperations_ExternalID]  DEFAULT ((0)) FOR [ExternalID]
GO
/****** Object:  Default [DF_b_RolesInTasks_ModuleID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInTasks] ADD  CONSTRAINT [DF_b_RolesInTasks_ModuleID]  DEFAULT ('') FOR [ModuleID]
GO
/****** Object:  Default [DF_b_RolesInTasks_ExternalID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInTasks] ADD  CONSTRAINT [DF_b_RolesInTasks_ExternalID]  DEFAULT ((0)) FOR [ExternalID]
GO
/****** Object:  Default [DF_b_RolesOperations_ModuleID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesOperations] ADD  CONSTRAINT [DF_b_RolesOperations_ModuleID]  DEFAULT ('') FOR [ModuleID]
GO
/****** Object:  Default [DF_b_RolesOperationsCache_ModuleID]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesOperationsCache] ADD  CONSTRAINT [DF_b_RolesOperationsCache_ModuleID]  DEFAULT ('') FOR [ModuleID]
GO
/****** Object:  Default [DF__b_Scheduler__name]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__name]  DEFAULT ('') FOR [name]
GO
/****** Object:  Default [DF__b_Scheduler__classname]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__classname]  DEFAULT ('') FOR [classname]
GO
/****** Object:  Default [DF__b_Scheduler__assembly]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__assembly]  DEFAULT ('') FOR [assembly]
GO
/****** Object:  Default [DF_b_Scheduler_parameters]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF_b_Scheduler_parameters]  DEFAULT ('') FOR [parameters]
GO
/****** Object:  Default [DF__b_Scheduler__starttime]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__starttime]  DEFAULT (dateadd(minute,(15),getdate())) FOR [starttime]
GO
/****** Object:  Default [DF__b_Scheduler__periodic]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__periodic]  DEFAULT ((0)) FOR [periodic]
GO
/****** Object:  Default [DF__b_Scheduler__period]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__period]  DEFAULT ((0)) FOR [period]
GO
/****** Object:  Default [DF__b_Scheduler__active]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF__b_Scheduler__active]  DEFAULT ((0)) FOR [active]
GO
/****** Object:  Default [DF_b_Scheduler_last_updated]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Scheduler] ADD  CONSTRAINT [DF_b_Scheduler_last_updated]  DEFAULT (getdate()) FOR [last_updated]
GO
/****** Object:  Default [DF_b_search_content_moduleId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_search_content_moduleId]  DEFAULT ('') FOR [moduleId]
GO
/****** Object:  Default [DF_b_search_content_itemGroup]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_search_content_itemGroup]  DEFAULT ('') FOR [itemGroup]
GO
/****** Object:  Default [DF_b_search_content_itemId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_search_content_itemId]  DEFAULT ('') FOR [itemId]
GO
/****** Object:  Default [DF_b_Search_Content_contentDate]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_Search_Content_contentDate]  DEFAULT (getdate()) FOR [contentDate]
GO
/****** Object:  Default [DF_b_Search_Content_operationModuleId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_Search_Content_operationModuleId]  DEFAULT ('') FOR [operationModuleId]
GO
/****** Object:  Default [DF_b_Search_Content_operationExternalId]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Content] ADD  CONSTRAINT [DF_b_Search_Content_operationExternalId]  DEFAULT ('') FOR [operationExternalId]
GO
/****** Object:  Default [DF_b_Search_Tags_approved]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Search_Tags] ADD  CONSTRAINT [DF_b_Search_Tags_approved]  DEFAULT ((0)) FOR [status]
GO
/****** Object:  Default [DF_b_Site_Culture]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Site] ADD  CONSTRAINT [DF_b_Site_Culture]  DEFAULT ('en-US') FOR [Culture]
GO
/****** Object:  Default [DF_b_users_PASSWORD_FORMAT]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Users] ADD  CONSTRAINT [DF_b_users_PASSWORD_FORMAT]  DEFAULT ((0)) FOR [PasswordFormat]
GO
/****** Object:  Default [DF_b_Users_DisplayName]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Users] ADD  CONSTRAINT [DF_b_Users_DisplayName]  DEFAULT ('') FOR [DisplayName]
GO
/****** Object:  Default [DF_b_UsersOptions_Common]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_UsersOptions] ADD  CONSTRAINT [DF_b_UsersOptions_Common]  DEFAULT ('N') FOR [Common]
GO
/****** Object:  ForeignKey [FK_b_AdvBanner_b_AdvSpace]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBanner]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBanner_b_AdvSpace] FOREIGN KEY([SpaceId])
REFERENCES [b_AdvSpace] ([ID])
GO
ALTER TABLE [b_AdvBanner] CHECK CONSTRAINT [FK_b_AdvBanner_b_AdvSpace]
GO
/****** Object:  ForeignKey [FK_b_AdvBanner_b_Author]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBanner]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBanner_b_Author] FOREIGN KEY([AuthorId])
REFERENCES [b_Users] ([ID])
GO
ALTER TABLE [b_AdvBanner] CHECK CONSTRAINT [FK_b_AdvBanner_b_Author]
GO
/****** Object:  ForeignKey [FK_b_AdvBanner_b_File]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBanner]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBanner_b_File] FOREIGN KEY([ContentFileId])
REFERENCES [b_File] ([ID])
GO
ALTER TABLE [b_AdvBanner] CHECK CONSTRAINT [FK_b_AdvBanner_b_File]
GO
/****** Object:  ForeignKey [FK_b_AdvBanner_b_LMAuthor]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBanner]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBanner_b_LMAuthor] FOREIGN KEY([LastModificationAuthorId])
REFERENCES [b_Users] ([ID])
GO
ALTER TABLE [b_AdvBanner] CHECK CONSTRAINT [FK_b_AdvBanner_b_LMAuthor]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerInRole_b_AdvBanner]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerInRole]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerInRole_b_AdvBanner] FOREIGN KEY([BannerId])
REFERENCES [b_AdvBanner] ([ID])
GO
ALTER TABLE [b_AdvBannerInRole] CHECK CONSTRAINT [FK_b_AdvBannerInRole_b_AdvBanner]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerInRole_b_Roles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerInRole]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerInRole_b_Roles] FOREIGN KEY([RoleId])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_AdvBannerInRole] CHECK CONSTRAINT [FK_b_AdvBannerInRole_b_Roles]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerInSite_b_AdvBanner]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerInSite_b_AdvBanner] FOREIGN KEY([BannerId])
REFERENCES [b_AdvBanner] ([ID])
GO
ALTER TABLE [b_AdvBannerInSite] CHECK CONSTRAINT [FK_b_AdvBannerInSite_b_AdvBanner]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerInSite_b_Site]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerInSite_b_Site] FOREIGN KEY([SiteId])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_AdvBannerInSite] CHECK CONSTRAINT [FK_b_AdvBannerInSite_b_Site]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerUrlTemplate_b_AdvBanner]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerUrlTemplate]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerUrlTemplate_b_AdvBanner] FOREIGN KEY([BannerId])
REFERENCES [b_AdvBanner] ([ID])
GO
ALTER TABLE [b_AdvBannerUrlTemplate] CHECK CONSTRAINT [FK_b_AdvBannerUrlTemplate_b_AdvBanner]
GO
/****** Object:  ForeignKey [FK_b_AdvBannerWeekScheduleHourSpan_b_AdvBanner]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_AdvBannerWeekScheduleHourSpan]  WITH CHECK ADD  CONSTRAINT [FK_b_AdvBannerWeekScheduleHourSpan_b_AdvBanner] FOREIGN KEY([BannerId])
REFERENCES [b_AdvBanner] ([ID])
GO
ALTER TABLE [b_AdvBannerWeekScheduleHourSpan] CHECK CONSTRAINT [FK_b_AdvBannerWeekScheduleHourSpan_b_AdvBanner]
GO
/****** Object:  ForeignKey [FK_b_Blog_b_BlogUser]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Blog]  WITH CHECK ADD  CONSTRAINT [FK_b_Blog_b_BlogUser] FOREIGN KEY([OwnerId])
REFERENCES [b_BlogUser] ([ID])
GO
ALTER TABLE [b_Blog] CHECK CONSTRAINT [FK_b_Blog_b_BlogUser]
GO
/****** Object:  ForeignKey [FK_b_BlogCategoryInSite_b_BlogCategory]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogCategoryInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogCategoryInSite_b_BlogCategory] FOREIGN KEY([CategoryId])
REFERENCES [b_BlogCategory] ([ID])
GO
ALTER TABLE [b_BlogCategoryInSite] CHECK CONSTRAINT [FK_b_BlogCategoryInSite_b_BlogCategory]
GO
/****** Object:  ForeignKey [FK_b_BlogCategoryInSite_b_Site]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogCategoryInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogCategoryInSite_b_Site] FOREIGN KEY([SiteId])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_BlogCategoryInSite] CHECK CONSTRAINT [FK_b_BlogCategoryInSite_b_Site]
GO
/****** Object:  ForeignKey [FK_b_BlogComment_b_Blog]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogComment]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogComment_b_Blog] FOREIGN KEY([BlogId])
REFERENCES [b_Blog] ([ID])
GO
ALTER TABLE [b_BlogComment] CHECK CONSTRAINT [FK_b_BlogComment_b_Blog]
GO
/****** Object:  ForeignKey [FK_b_BlogComment_b_BlogPost]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogComment]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogComment_b_BlogPost] FOREIGN KEY([PostId])
REFERENCES [b_BlogPost] ([ID])
GO
ALTER TABLE [b_BlogComment] CHECK CONSTRAINT [FK_b_BlogComment_b_BlogPost]
GO
/****** Object:  ForeignKey [FK_b_BlogInCategory_b_Blog]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogInCategory]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogInCategory_b_Blog] FOREIGN KEY([BlogId])
REFERENCES [b_Blog] ([ID])
GO
ALTER TABLE [b_BlogInCategory] CHECK CONSTRAINT [FK_b_BlogInCategory_b_Blog]
GO
/****** Object:  ForeignKey [FK_b_BlogInCategory_b_BlogCategory]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogInCategory]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogInCategory_b_BlogCategory] FOREIGN KEY([CategoryId])
REFERENCES [b_BlogCategory] ([ID])
GO
ALTER TABLE [b_BlogInCategory] CHECK CONSTRAINT [FK_b_BlogInCategory_b_BlogCategory]
GO
/****** Object:  ForeignKey [FK_b_BlogPost_b_Blog]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogPost]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogPost_b_Blog] FOREIGN KEY([BlogId])
REFERENCES [b_Blog] ([ID])
GO
ALTER TABLE [b_BlogPost] CHECK CONSTRAINT [FK_b_BlogPost_b_Blog]
GO
/****** Object:  ForeignKey [FK_b_Post_b_BlogUser]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogPost]  WITH CHECK ADD  CONSTRAINT [FK_b_Post_b_BlogUser] FOREIGN KEY([AuthorId])
REFERENCES [b_BlogUser] ([ID])
GO
ALTER TABLE [b_BlogPost] CHECK CONSTRAINT [FK_b_Post_b_BlogUser]
GO
/****** Object:  ForeignKey [FK_b_BlogUser_b_Users]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_BlogUser]  WITH CHECK ADD  CONSTRAINT [FK_b_BlogUser_b_Users] FOREIGN KEY([ID])
REFERENCES [b_Users] ([ID])
GO
ALTER TABLE [b_BlogUser] CHECK CONSTRAINT [FK_b_BlogUser_b_Users]
GO
/****** Object:  ForeignKey [FK_b_Custom_Field_Enum_b_Custom_Field]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Custom_Field_Enum]  WITH CHECK ADD  CONSTRAINT [FK_b_Custom_Field_Enum_b_Custom_Field] FOREIGN KEY([FieldID])
REFERENCES [b_Custom_Field] ([ID])
GO
ALTER TABLE [b_Custom_Field_Enum] CHECK CONSTRAINT [FK_b_Custom_Field_Enum_b_Custom_Field]
GO
/****** Object:  ForeignKey [FK_b_Custom_Field_Localization_b_Custom_Field]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Custom_Field_Localization]  WITH CHECK ADD  CONSTRAINT [FK_b_Custom_Field_Localization_b_Custom_Field] FOREIGN KEY([FieldID])
REFERENCES [b_Custom_Field] ([ID])
GO
ALTER TABLE [b_Custom_Field_Localization] CHECK CONSTRAINT [FK_b_Custom_Field_Localization_b_Custom_Field]
GO
/****** Object:  ForeignKey [FK_ForumInSite_ForumId_Forum_Id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumInSite]  WITH CHECK ADD  CONSTRAINT [FK_ForumInSite_ForumId_Forum_Id] FOREIGN KEY([ForumId])
REFERENCES [b_Forum] ([ID])
GO
ALTER TABLE [b_ForumInSite] CHECK CONSTRAINT [FK_ForumInSite_ForumId_Forum_Id]
GO
/****** Object:  ForeignKey [FK_ForumInSite_SiteId_Site_Id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumInSite]  WITH CHECK ADD  CONSTRAINT [FK_ForumInSite_SiteId_Site_Id] FOREIGN KEY([SiteId])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_ForumInSite] CHECK CONSTRAINT [FK_ForumInSite_SiteId_Site_Id]
GO
/****** Object:  ForeignKey [FK_ForumPost_ForumId_Forum_Id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost]  WITH CHECK ADD  CONSTRAINT [FK_ForumPost_ForumId_Forum_Id] FOREIGN KEY([ForumId])
REFERENCES [b_Forum] ([ID])
GO
ALTER TABLE [b_ForumPost] CHECK CONSTRAINT [FK_ForumPost_ForumId_Forum_Id]
GO
/****** Object:  ForeignKey [FK_ForumPost_TopicId_ForumTopic_Id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumPost]  WITH CHECK ADD  CONSTRAINT [FK_ForumPost_TopicId_ForumTopic_Id] FOREIGN KEY([TopicId])
REFERENCES [b_ForumTopic] ([ID])
GO
ALTER TABLE [b_ForumPost] CHECK CONSTRAINT [FK_ForumPost_TopicId_ForumTopic_Id]
GO
/****** Object:  ForeignKey [FK_ForumTopic_ForumId_Forum_Id]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_ForumTopic]  WITH CHECK ADD  CONSTRAINT [FK_ForumTopic_ForumId_Forum_Id] FOREIGN KEY([ForumId])
REFERENCES [b_Forum] ([ID])
GO
ALTER TABLE [b_ForumTopic] CHECK CONSTRAINT [FK_ForumTopic_ForumId_Forum_Id]
GO
/****** Object:  ForeignKey [FK_b_IBlock_b_IBlock_Type]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlock]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlock_b_IBlock_Type] FOREIGN KEY([TypeId])
REFERENCES [b_IBlockType] ([ID])
GO
ALTER TABLE [b_IBlock] CHECK CONSTRAINT [FK_b_IBlock_b_IBlock_Type]
GO
/****** Object:  ForeignKey [FK_b_IBlockElement_b_IBlock]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElement]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlockElement_b_IBlock] FOREIGN KEY([IBlockID])
REFERENCES [b_IBlock] ([ID])
GO
ALTER TABLE [b_IBlockElement] CHECK CONSTRAINT [FK_b_IBlockElement_b_IBlock]
GO
/****** Object:  ForeignKey [FK_b_IBlockElementInSection_b_IBlockElement]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElementInSection]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlockElementInSection_b_IBlockElement] FOREIGN KEY([ElementId])
REFERENCES [b_IBlockElement] ([ID])
GO
ALTER TABLE [b_IBlockElementInSection] CHECK CONSTRAINT [FK_b_IBlockElementInSection_b_IBlockElement]
GO
/****** Object:  ForeignKey [FK_b_IBlockElementInSection_b_IBlockSection]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockElementInSection]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlockElementInSection_b_IBlockSection] FOREIGN KEY([SectionId])
REFERENCES [b_IBlockSection] ([ID])
GO
ALTER TABLE [b_IBlockElementInSection] CHECK CONSTRAINT [FK_b_IBlockElementInSection_b_IBlockSection]
GO
/****** Object:  ForeignKey [FK_b_IBlock_Site_b_IBlock]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlock_Site_b_IBlock] FOREIGN KEY([IBlockId])
REFERENCES [b_IBlock] ([ID])
GO
ALTER TABLE [b_IBlockInSite] CHECK CONSTRAINT [FK_b_IBlock_Site_b_IBlock]
GO
/****** Object:  ForeignKey [FK_b_IBlock_Site_b_Site]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockInSite]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlock_Site_b_Site] FOREIGN KEY([SiteId])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_IBlockInSite] CHECK CONSTRAINT [FK_b_IBlock_Site_b_Site]
GO
/****** Object:  ForeignKey [FK_b_IBlockSection_b_IBlock]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlockSection_b_IBlock] FOREIGN KEY([IBlockId])
REFERENCES [b_IBlock] ([ID])
GO
ALTER TABLE [b_IBlockSection] CHECK CONSTRAINT [FK_b_IBlockSection_b_IBlock]
GO
/****** Object:  ForeignKey [FK_b_IBlockSection_b_IBlockSection]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockSection]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlockSection_b_IBlockSection] FOREIGN KEY([SectionId])
REFERENCES [b_IBlockSection] ([ID])
GO
ALTER TABLE [b_IBlockSection] CHECK CONSTRAINT [FK_b_IBlockSection_b_IBlockSection]
GO
/****** Object:  ForeignKey [FK_b_IBlock_TypeLang_b_Language]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_IBlockTypeLang]  WITH CHECK ADD  CONSTRAINT [FK_b_IBlock_TypeLang_b_Language] FOREIGN KEY([LanguageId])
REFERENCES [b_Language] ([ID])
GO
ALTER TABLE [b_IBlockTypeLang] CHECK CONSTRAINT [FK_b_IBlock_TypeLang_b_Language]
GO
/****** Object:  ForeignKey [FK_b_Options_b_Site]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Options]  WITH CHECK ADD  CONSTRAINT [FK_b_Options_b_Site] FOREIGN KEY([SiteId])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_Options] CHECK CONSTRAINT [FK_b_Options_b_Site]
GO
/****** Object:  ForeignKey [FK_b_RolesInOperations_b_roles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInOperations]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInOperations_b_roles] FOREIGN KEY([RoleID])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_RolesInOperations] CHECK CONSTRAINT [FK_b_RolesInOperations_b_roles]
GO
/****** Object:  ForeignKey [FK_b_RolesInOperations_b_RolesOperations]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInOperations]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInOperations_b_RolesOperations] FOREIGN KEY([OperationID])
REFERENCES [b_RolesOperations] ([ID])
GO
ALTER TABLE [b_RolesInOperations] CHECK CONSTRAINT [FK_b_RolesInOperations_b_RolesOperations]
GO
/****** Object:  ForeignKey [FK_b_RolesInRoles_b_roles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInRoles]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInRoles_b_roles] FOREIGN KEY([RoleID])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_RolesInRoles] CHECK CONSTRAINT [FK_b_RolesInRoles_b_roles]
GO
/****** Object:  ForeignKey [FK_b_RolesInRoles_b_roles1]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInRoles]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInRoles_b_roles1] FOREIGN KEY([SubRoleID])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_RolesInRoles] CHECK CONSTRAINT [FK_b_RolesInRoles_b_roles1]
GO
/****** Object:  ForeignKey [FK_b_RolesInTasks_b_roles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInTasks]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInTasks_b_roles] FOREIGN KEY([RoleID])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_RolesInTasks] CHECK CONSTRAINT [FK_b_RolesInTasks_b_roles]
GO
/****** Object:  ForeignKey [FK_b_RolesInTasks_b_RolesTasks]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesInTasks]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesInTasks_b_RolesTasks] FOREIGN KEY([TaskID])
REFERENCES [b_RolesTasks] ([ID])
GO
ALTER TABLE [b_RolesInTasks] CHECK CONSTRAINT [FK_b_RolesInTasks_b_RolesTasks]
GO
/****** Object:  ForeignKey [FK_b_RolesTasksInOperations_b_RolesOperations]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesTasksInOperations]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesTasksInOperations_b_RolesOperations] FOREIGN KEY([OperationID])
REFERENCES [b_RolesOperations] ([ID])
GO
ALTER TABLE [b_RolesTasksInOperations] CHECK CONSTRAINT [FK_b_RolesTasksInOperations_b_RolesOperations]
GO
/****** Object:  ForeignKey [FK_b_RolesTasksInOperations_b_RolesTasks]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesTasksInOperations]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesTasksInOperations_b_RolesTasks] FOREIGN KEY([TaskID])
REFERENCES [b_RolesTasks] ([ID])
GO
ALTER TABLE [b_RolesTasksInOperations] CHECK CONSTRAINT [FK_b_RolesTasksInOperations_b_RolesTasks]
GO
/****** Object:  ForeignKey [FK_b_RolesTasksInTasks_b_RolesTasks]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesTasksInTasks]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesTasksInTasks_b_RolesTasks] FOREIGN KEY([SubTaskID])
REFERENCES [b_RolesTasks] ([ID])
GO
ALTER TABLE [b_RolesTasksInTasks] CHECK CONSTRAINT [FK_b_RolesTasksInTasks_b_RolesTasks]
GO
/****** Object:  ForeignKey [FK_b_RolesTasksInTasks_b_RolesTasksInTasks]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_RolesTasksInTasks]  WITH CHECK ADD  CONSTRAINT [FK_b_RolesTasksInTasks_b_RolesTasksInTasks] FOREIGN KEY([TaskID])
REFERENCES [b_RolesTasks] ([ID])
GO
ALTER TABLE [b_RolesTasksInTasks] CHECK CONSTRAINT [FK_b_RolesTasksInTasks_b_RolesTasksInTasks]
GO
/****** Object:  ForeignKey [FK_b_Site_b_Language]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Site]  WITH CHECK ADD  CONSTRAINT [FK_b_Site_b_Language] FOREIGN KEY([LanguageId])
REFERENCES [b_Language] ([ID])
GO
ALTER TABLE [b_Site] CHECK CONSTRAINT [FK_b_Site_b_Language]
GO
/****** Object:  ForeignKey [FK_b_Users_b_Site]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_Users]  WITH CHECK ADD  CONSTRAINT [FK_b_Users_b_Site] FOREIGN KEY([SiteID])
REFERENCES [b_Site] ([ID])
GO
ALTER TABLE [b_Users] CHECK CONSTRAINT [FK_b_Users_b_Site]
GO
/****** Object:  ForeignKey [UserUpLink]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_UsersControlsOptions]  WITH CHECK ADD  CONSTRAINT [UserUpLink] FOREIGN KEY([UserID])
REFERENCES [b_Users] ([ID])
GO
ALTER TABLE [b_UsersControlsOptions] CHECK CONSTRAINT [UserUpLink]
GO
/****** Object:  ForeignKey [FK_b_UsersInRoles_b_roles]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [FK_b_UsersInRoles_b_roles] FOREIGN KEY([RoleID])
REFERENCES [b_Roles] ([ID])
GO
ALTER TABLE [b_UsersInRoles] CHECK CONSTRAINT [FK_b_UsersInRoles_b_roles]
GO
/****** Object:  ForeignKey [FK_b_UsersInRoles_b_users]    Script Date: 10/01/2009 19:30:25 ******/
ALTER TABLE [b_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [FK_b_UsersInRoles_b_users] FOREIGN KEY([UserID])
REFERENCES [b_Users] ([ID])
GO
ALTER TABLE [b_UsersInRoles] CHECK CONSTRAINT [FK_b_UsersInRoles_b_users]
