Data Model

__RefactorLog Table

Table ID: 561437074; Created: November 16, 2021, 18:20:38
Name Type NULL Comment
OperationKey uniqueidentifier

_Test Table

Table ID: 773577794; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TestId int
Descrip nvarchar (2000)
DecimalField decimal (38, 14)
IntegerField int
ImageField varchar (max)
FileField varchar (max)
BitField bit
DateField date
SmalldateTimeField smalldatetime
DbComboField nvarchar (50)
ComboField nvarchar (50)
WhiteBoardField nvarchar (max)
ColorField nvarchar (50)
CoordinateField nvarchar (100)
CronField nvarchar (250)
CssField nvarchar (1000)
CustomField nvarchar (100)
EmailField nvarchar (100)
CheckMultiField nvarchar (1000)
FilePathField nvarchar (250)
HtmlCodeField nvarchar (1000)
HtmlEditField nvarchar (1000)
ImageFileField nvarchar (250)
JavaCodeField nvarchar (1000)
MultiComboField nvarchar (1000)
MultiLineField nvarchar (250)
NullCheckField bit
PasswordField nvarchar (50)
PhoneField nvarchar (50)
RadioField nvarchar (50)
SqlCodeField nvarchar (1000)
SwitchField bit
TagListField nvarchar (1000)
TimeField nvarchar (50)
UploadB64Field nvarchar (max)
UploadFile nvarchar (250)
UrlField nvarchar (100)
WeekField nvarchar (100)
IdentField nvarchar (250)
IdDoc int IDENTITY
InsertUpdate bit DEFAULT ((0))
Usuario nvarchar (50)
FechaInsertUpdate datetime DEFAULT (getdate())

_Test_Conf Table

Table ID: 805577908; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TestId int dbo._Test.TestId
Config nvarchar (50)

ActionsLog Table

Table ID: 837578022; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id int IDENTITY
UserId nvarchar (128)
TypeId int dbo.ActionsLog_Types.TypeId
ProcessName nvarchar (255)
ActionMessage nvarchar (1000)
ObjectName nvarchar (50)
ObjectKey nvarchar (255)
TimeStamp datetime
UserName nvarchar (128)
EndTimeStamp datetime
Milliseconds int COMPUTED

ActionsLog_Details Table

Table ID: 869578136; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id int IDENTITY
LogId int dbo.ActionsLog.Id
PropertyName nvarchar (50)
OldValue nvarchar (max)
NewValue nvarchar (max)

ActionsLog_Settings Table

Table ID: 901578250; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
SettingsId int
Descrip nvarchar (50)

ActionsLog_Types Table

Table ID: 933578364; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId int
Descrip nvarchar (50)
Action nvarchar (50)

AspNetFaculties Table

Table ID: 965578478; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
FacultyId nvarchar (128)
Name nvarchar (256)
Descrip nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetProfiles Table

Table ID: 997578592; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProfileName nvarchar (100)
Descrip nvarchar (100)
CultureId nvarchar (8) dbo.Cultures.CultureId
WebInterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
MobileInterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
StartupPageName nvarchar (100) dbo.Pages.PageName
MailAccountId nvarchar (100) dbo.Mail_Accounts.MailAccountId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetRoles Table

Table ID: 1029578706; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id nvarchar (128)
Name nvarchar (256)
IsDesigner bit DEFAULT ((0))
IsAdmin bit DEFAULT ((0))
Hidden bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetUserClaims Table

Table ID: 1061578820; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id int IDENTITY
UserId nvarchar (128) dbo.AspNetUsers.Id
ClaimType nvarchar (max)
ClaimValue nvarchar (max)

AspNetUserLogins Table

Table ID: 1093578934; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
LoginProvider nvarchar (128)
ProviderKey nvarchar (128)
UserId nvarchar (128) dbo.AspNetUsers.Id

AspNetUserRoles Table

Table ID: 1109578991; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
RoleId nvarchar (128) dbo.AspNetRoles.Id

AspNetUsers Table

Table ID: 1141579105; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id nvarchar (128)
RoleId nvarchar (128) dbo.AspNetRoles.Id
ProfileName nvarchar (100) DEFAULT (N'default')dbo.AspNetProfiles.ProfileName
Email nvarchar (256)
EmailConfirmed bit
PasswordHash nvarchar (max)
SecurityStamp nvarchar (max)
PhoneNumber nvarchar (50)
PhoneNumberConfirmed bit
TwoFactorEnabled bit
LockoutEndDateUtc datetime
LockoutEnabled bit DEFAULT ((1))
AccessFailedCount int
UserName nvarchar (256)
IPGroup nvarchar (50) dbo.AspNetUsers_IPGroups.IPGroup
Reference nvarchar (50)
SubReference nvarchar (50)
Avatar nvarchar (max) DEFAULT ('~/img/Avatars/avatar_blank.png')
Name nvarchar (100)
SurName nvarchar (100)
NickName nvarchar (100)
CultureId nvarchar (8) dbo.Cultures.CultureId
MailAccountId nvarchar (100) dbo.Mail_Accounts.MailAccountId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetUsers_Devices Table

Table ID: 1173579219; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
DeviceToken nvarchar (250)
Platform nvarchar (50)
RegisterDate smalldatetime DEFAULT (getdate())
LastRegisterDate smalldatetime DEFAULT (getdate())

AspNetUsers_Devices_Platforms Table

Table ID: 1205579333; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Platform nvarchar (50)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName

AspNetUsers_Faculties Table

Table ID: 1237579447; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetUsers_Integrations Table

Table ID: 1269579561; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id nvarchar (128) dbo.AspNetUsers.Id
TokenType nvarchar (64) dbo.AspNetUsers_TokenTypes.TokenType
Active bit DEFAULT ((0))

AspNetUsers_IPGroups Table

Table ID: 1301579675; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
IPGroup nvarchar (50)

AspNetUsers_IPGroups_Detail Table

Table ID: 1333579789; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
IPGroup nvarchar (50) dbo.AspNetUsers_IPGroups.IPGroup
IP nvarchar (50)

AspNetUsers_Log Table

Table ID: 1365579903; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:32
Name Type NULL Comment
LogId int IDENTITY
Date smalldatetime
UserId nvarchar (128)
IP nvarchar (50)
Browser nvarchar (256)
Culture nvarchar (100)
Time nvarchar (5) DEFAULT (left(CONVERT([varchar],getdate(),(108)),(5)))
Success bit DEFAULT ((1))

AspNetUsers_Settings Table

Table ID: 1397580017; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
SkinId int
MobileSkinId varchar (50)
DefaultPageSize int
DefaultDropDownRows int
MailAccount nvarchar (50)
MailUser nvarchar (100)
MailVisibleName nvarchar (100)
POP3Host nvarchar (100)
SMTPHost nvarchar (100)
MaillPassowrd varchar (50)
DeleteMailsOnServer bit
SMTPPort int DEFAULT ((25))
POPPort int DEFAULT ((110))
UseSSL bit
MailSignature nvarchar (1000)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

AspNetUsers_Tokens Table

Table ID: 1429580131; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TokenId nvarchar (100) DEFAULT (newid())
Id nvarchar (128) dbo.AspNetUsers.Id
TokenType nvarchar (64) dbo.AspNetUsers_TokenTypes.TokenType
AccessToken nvarchar (max)
RefreshToken nvarchar (max)
RefreshData nvarchar (max)
Scope nvarchar (max)
ExpiryDate smalldatetime
InsertedDate smalldatetime
AppName nvarchar (256)
CalendarId nvarchar (255)

AspNetUsers_TokenTypes Table

Table ID: 1461580245; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TokenType nvarchar (64)
Descrip nvarchar (max)
IconName nvarchar (100) DEFAULT (N'noicon')
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

BlackList Table

Table ID: 1493580359; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
Id nvarchar (100) DEFAULT (newid())
Method nvarchar (255)
Param nvarchar (255)
ExcludeList nvarchar (max)
ExcludeRegex nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Charts_Animations Table

Table ID: 1525580473; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Animation nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Charts_Settings Table

Table ID: 1557580587; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ChartSettingName nvarchar (100)
Descrip nvarchar (255)
ShowLabels bit DEFAULT ((1))
Colors nvarchar (500)
BorderColors nvarchar (500)
ShowLegend bit DEFAULT ((1))
LegendPos nvarchar (20)
ToolTipBackgroundColor nvarchar (10)
ShowTitle bit DEFAULT ((1))
TitleFontStyle nvarchar (150)
TitleFontSize int
TitlePosition nvarchar (20)
TitleFontColor nvarchar (20)
Responsive bit DEFAULT ((1))
MinXAxes int DEFAULT ((0))
MinYAxes int DEFAULT ((0))
AnimationDuration int DEFAULT ((2000))
AnimationStyle nvarchar (100) dbo.Charts_Animations.Animation
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Chatters Table

Table ID: 1589580701; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
MessageId uniqueidentifier DEFAULT (newid())
UserOwner nvarchar (128) dbo.AspNetUsers.Id
Content nvarchar (max)
InsertionDate datetime DEFAULT (getdate())
DestinationObjectName nvarchar (50) dbo.Objects.ObjectName
DestinationObjectId nvarchar (250)
DestinationParentMessage uniqueidentifier dbo.Chatters.MessageId
DestinationUser nvarchar (128) dbo.AspNetUsers.Id
DestinationChatterGroup uniqueidentifier dbo.Chatters_Groups.ChatterGroupId
LoginOwner nvarchar (128)

Chatters_Config Table

Table ID: 1621580815; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ObjectName nvarchar (50)
ObjectPK nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Chatters_Groups Table

Table ID: 1653580929; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ChatterGroupId uniqueidentifier DEFAULT (newid())
Name nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Chatters_Groups_Users Table

Table ID: 1685581043; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ChatterGroupId uniqueidentifier dbo.Chatters_Groups.ChatterGroupId
UserId nvarchar (128) dbo.AspNetUsers.Id
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Configuration_Actions_Types Table

Table ID: 1717581157; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ActionId smallint
Description nvarchar (255)

Configuration_Default_Actions Table

Table ID: 1749581271; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
DefaultActionId int
TableName nvarchar (256)
FieldName nvarchar (256)
RowOriginId int dbo.Origins.OriginId
ActionId smallint dbo.Configuration_Actions_Types.ActionId

Configuration_Scripts Table

Table ID: 1781581385; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ScriptId nvarchar (256)
ScriptText nvarchar (max)

Configuration_Tables Table

Table ID: 1813581499; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TableName nvarchar (256)
CompareMode smallint dbo.Configuration_Tables_CompareModes.Mode
CompareFilter nvarchar (max)
Autoscripting bit DEFAULT ((1))

Configuration_Tables_CompareModes Table

Table ID: 1845581613; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Mode smallint
Description nvarchar (255)

ContextVars Table

Table ID: 1877581727; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
VarName nvarchar (50)
VarSQL nvarchar (max)
Order int DEFAULT ((0))
ConnStringId nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Countries Table

Table ID: 1909581841; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
IsoCode nvarchar (2)
Iso3 nvarchar (3)
Name nvarchar (50)
IsoName nvarchar (50)
Flag nvarchar (1009)
Active bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Cultures Table

Table ID: 1941581955; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
CultureId nvarchar (8)
CountryISO nvarchar (2) dbo.Countries.IsoCode
Name nvarchar (100)
Flag nvarchar (100)
Active bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

DbConnectionStrings Table

Table ID: 1973582069; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ConnStringId nvarchar (50)
Descrip nvarchar (100)
UpdateDataModel bit DEFAULT ((0))
DacpacName nvarchar (150)
Active bit DEFAULT ((1))
Reserved bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

DbConnectionStrings_LinkedServers Table

Table ID: 2005582183; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
ConnStringId nvarchar (50)
ChildConnStringId nvarchar (50)
ServerName nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

DbUpdateTypes Table

Table ID: 2037582297; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UpdateTypeId nvarchar (10)
Descrip nvarchar (50)

Documents Table

Table ID: 2069582411; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
DocGuid uniqueidentifier DEFAULT (newid())
Name nvarchar (100)
Description nvarchar (250)
CategoryId nvarchar (50) DEFAULT (N'sysdoc-generic')dbo.Documents_Category.CategoryId
CreationDate smalldatetime DEFAULT (getdate())

Documents_Category Table

Table ID: 2101582525; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
CategoryId nvarchar (50)
Category nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Documents_Drive_Config Table

Table ID: 2133582639; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Account nvarchar (250)
Code nvarchar (1000)
RefreshToken nvarchar (1000)
AccessToken nvarchar (1000)
TokenType nvarchar (250)
ExpiryDate datetime
Active bit
Default bit
LastUse datetime

Documents_Extensions Table

Table ID: 18099105; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Origin nvarchar (50)
Description nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
Extension nvarchar (255)

Documents_Objects Table

Table ID: 50099219; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
DocGuid uniqueidentifier dbo.Documents.DocGuid
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectId nvarchar (250)

Documents_Objects_Config Table

Table ID: 82099333; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectPK nvarchar (50)
ERPObjectName nvarchar (250)
TypeId nvarchar (50) DEFAULT ('flexygo')dbo.Documents_Objects_Config_Types.TypeId
Path nvarchar (500)
DefaultCategoryId nvarchar (50)
CategoryFilter nvarchar (max)
DropboxFolderCreate bit DEFAULT ((0))
DropboxFolderLink bit DEFAULT ((0))
DropboxFileCreate bit DEFAULT ((0))
DropboxFileLink bit DEFAULT ((0))
DriveFolderCreate bit DEFAULT ((0))
DriveFolderLink bit DEFAULT ((0))
DriveFileCreate bit DEFAULT ((0))
DriveFileLink bit DEFAULT ((0))
DiskFolderCreate bit DEFAULT ((0))
DiskFolderLink bit DEFAULT ((0))
DiskFileCreate bit DEFAULT ((0))
DiskFileLink bit DEFAULT ((0))
ExtensionId nvarchar (100) DEFAULT (N'sysAll')dbo.Extensions.ExtensionId
OfflineFilter nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Documents_Objects_Config_Types Table

Table ID: 114099447; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (250)
Active bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Documents_Versions Table

Table ID: 146099561; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
DocGuid uniqueidentifier dbo.Documents.DocGuid
Revision int
FilePath nvarchar (255)
DownloadLink nvarchar (255)
CloudID nvarchar (250)
DocumentTypeName nvarchar (50) dbo.Documents_Versions_Types.Type
InProgress bit DEFAULT ((0))
Origin nvarchar (50) dbo.Documents_Extensions.Origin

Documents_Versions_Types Table

Table ID: 178099675; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Type nvarchar (50)
Description nvarchar (250)

Error_Levels Table

Table ID: 210099789; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Level int
Descrip nvarchar (100)

Error_Log Table

Table ID: 242099903; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Id int IDENTITY
UserId nvarchar (128)
ErrorLevel int dbo.Error_Levels.Level
ErrorMessage nvarchar (max)
ErrorStack nvarchar (max)
ErrorCode nvarchar (50)
ErrorSeverity int dbo.Error_Severity.Severity
ObjectName nvarchar (50)
ObjectKey nvarchar (500)
ActionType int dbo.ActionsLog_Types.TypeId
ProcessName nvarchar (255)
ProcessParams nvarchar (max)
MoreInfo nvarchar (max)
ConnectionStringId nvarchar (50)
UserName nvarchar (128)
Browser nvarchar (50)
BrowserVersion nvarchar (50)
TimeStamp datetime
Version nvarchar (50)
Guid nvarchar (100) DEFAULT (newid())
IP nvarchar (50)

Error_Severity Table

Table ID: 274100017; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Severity int
Descrip nchar (10)

Events_Actions Table

Table ID: 306100131; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
EventAction nvarchar (50)
Description nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Events_Classes Table

Table ID: 338100245; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
EventClass nvarchar (50)
Description nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Events_Classes_Types Table

Table ID: 370100359; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
EventClass nvarchar (50) dbo.Events_Classes.EventClass
EventType nvarchar (50) dbo.Events_Types.EventType
Description nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Events_Types Table

Table ID: 402100473; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
EventType nvarchar (50)
Description nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Exceptions Table

Table ID: 434100587; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
Id nvarchar (100) DEFAULT (newid())
Msg nvarchar (900)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Export_Formats Table

Table ID: 482100758; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
Format nvarchar (50)
Description nvarchar (100)
IconName nvarchar (100)
MaxNumber int DEFAULT ((50000))
Active bit DEFAULT ((1))
Order int DEFAULT ((20))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Extensions Table

Table ID: 514100872; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ExtensionId nvarchar (100)
Descrip nvarchar (500)
Extensions nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Flexygo_Connectors Table

Table ID: 546100986; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (255)
ExternalUrl nvarchar (255)

Follow_Object_Users Table

Table ID: 578101100; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Object nvarchar (50) dbo.Follow_Objects_Config.Object
UserId nvarchar (128) dbo.AspNetUsers.Id

Follow_Objects_Child_Config Table

Table ID: 610101214; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Object nvarchar (50) dbo.Follow_Objects_Config.Object
ChildObject nvarchar (50) dbo.Objects.ObjectName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Follow_Objects_Child_Users Table

Table ID: 642101328; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Object nvarchar (50)
ChildObject nvarchar (50)
UserId nvarchar (128) dbo.AspNetUsers.Id

Follow_Objects_Config Table

Table ID: 674101442; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Object nvarchar (50) dbo.Objects.ObjectName
Disable bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

GreyList Table

Table ID: 706101556; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
Id nvarchar (100) DEFAULT (newid())
Method nvarchar (255)
Param nvarchar (255)
ExcludeList nvarchar (max)
ExcludeRegex nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Help Table

Table ID: 738101670; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
HelpId nvarchar (50) DEFAULT (newid())
Title nvarchar (150)
HTMLText nvarchar (max)
TargetId nvarchar (50) DEFAULT (N'current')dbo.Targets.TargetId
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
ExternalUrl nvarchar (255)
Order int DEFAULT ((0))
Category nvarchar (50)
Tag nvarchar (200)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Help_Categories Table

Table ID: 770101784; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Category nvarchar (50)
Descrip nvarchar (250)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Help_Cultures Table

Table ID: 802101898; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
HelpId nvarchar (50) dbo.Help.HelpId
CultureId nvarchar (8) dbo.Cultures.CultureId
HTMLText nvarchar (max)

Help_SamplesJS Table

Table ID: 834102012; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
HelpJSId nvarchar (50) DEFAULT (newid())
Title nvarchar (150)
HTMLCode nvarchar (max)
JSCode nvarchar (max)
CSSCode nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Icons Table

Table ID: 866102126; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
IconName nvarchar (100)
Classification nvarchar (50)
CSSClass nvarchar (100)
ImagePath nvarchar (255)
Category nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Image_Compression_Types Table

Table ID: 898102240; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId smallint
Descrip nvarchar (50)

Interfaces Table

Table ID: 930102354; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
InterfaceName nvarchar (100)
TypeId int dbo.Interfaces_Types.TypeId
Descrip nvarchar (100)
IsDefault bit DEFAULT ((0))
Logo nvarchar (255)
SkinId nvarchar (50) dbo.Skins.SkinId
Script nvarchar (max)
Style nvarchar (1000)
MainNavigateId uniqueidentifier dbo.Navigation_Nodes.NodeId
NavigateId uniqueidentifier dbo.Navigation_Nodes.NodeId
StartupPageName nvarchar (250)
DefaultPageSize int DEFAULT ((50))
DefaultDropDownRows int DEFAULT ((20))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Interfaces_Types Table

Table ID: 962102468; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId int
Descrip nvarchar (100)

Interfaces_Types_JS Table

Table ID: 994102582; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
InterfaceTypeId uniqueidentifier DEFAULT (newid())
TypeId int dbo.Interfaces_Types.TypeId
FilePath nvarchar (255)
Description nvarchar (255)
Order int DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Jobs Table

Table ID: 1026102696; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
JobName nvarchar (50)
JobGroup nvarchar (50)
Enabled bit DEFAULT ((0))
Descrip nvarchar (250)
FirstExecutionDate datetime
LastExecutionDate datetime
TriggerExpression nvarchar (50) dbo.Jobs_Triggers.TriggerExpression
ExecuteInmediatlyAfterMisfire bit DEFAULT ((0))
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectWhere nvarchar (max)
UserName nvarchar (256)
ProcessName nvarchar (255) dbo.Processes.ProcessName
Params nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Jobs_Log Table

Table ID: 1058102810; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ExecutionId nvarchar (50) DEFAULT (newid())
JobName nvarchar (50) dbo.Jobs.JobName
JobStart datetime DEFAULT (getdate())
JobEnd datetime
HasError bit DEFAULT ((0))
NotifiedError bit DEFAULT ((0))
Descrip nvarchar (max)

Jobs_Qrtz_Blob_Triggers Table

Table ID: 1090102924; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Trigger_Name nvarchar (150)
Trigger_Group nvarchar (150)
Blob_Data image

Jobs_Qrtz_Calendars Table

Table ID: 1122103038; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Calendar_Name nvarchar (200)
Calendar image

Jobs_Qrtz_Cron_Triggers Table

Table ID: 1154103152; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Sched_Name nvarchar (120) dbo.Jobs_Qrtz_Triggers.Sched_Name
Trigger_Name nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Name
Trigger_Group nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Group
Cron_Expression nvarchar (120)
Time_Zone_Id nvarchar (80)

Jobs_Qrtz_Fired_Triggers Table

Table ID: 1186103266; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Entry_Id nvarchar (140)
Trigger_Name nvarchar (150)
Trigger_Group nvarchar (150)
Instance_Name nvarchar (200)
Fired_Time bigint
Sched_Time bigint
Priority int
State nvarchar (16)
Job_Name nvarchar (150)
Job_Group nvarchar (150)
Is_Nonconcurrent bit
Requests_Recovery bit

Jobs_Qrtz_Job_Details Table

Table ID: 1218103380; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Sched_Name nvarchar (120)
Job_Name nvarchar (150)
Job_Group nvarchar (150)
Description nvarchar (250)
Job_Class_Name nvarchar (250)
Is_Durable bit
Is_Nonconcurrent bit
Is_Update_Data bit
Requests_Recovery bit
Job_Data image

Jobs_Qrtz_Locks Table

Table ID: 1250103494; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Lock_Name nvarchar (40)

Jobs_Qrtz_Paused_Trigger_Grps Table

Table ID: 1282103608; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Trigger_Group nvarchar (150)

Jobs_Qrtz_Scheduler_State Table

Table ID: 1314103722; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Sched_Name nvarchar (120)
Instance_Name nvarchar (200)
Last_Checkin_Time bigint
Checkin_Interval bigint

Jobs_Qrtz_Simple_Triggers Table

Table ID: 1346103836; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Sched_Name nvarchar (120) dbo.Jobs_Qrtz_Triggers.Sched_Name
Trigger_Name nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Name
Trigger_Group nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Group
Repeat_Count int
Repeat_Interval bigint
Times_Triggered int

Jobs_Qrtz_Simprop_Triggers Table

Table ID: 1378103950; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Sched_Name nvarchar (120) dbo.Jobs_Qrtz_Triggers.Sched_Name
Trigger_Name nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Name
Trigger_Group nvarchar (150) dbo.Jobs_Qrtz_Triggers.Trigger_Group
Str_Prop_1 nvarchar (512)
Str_Prop_2 nvarchar (512)
Str_Prop_3 nvarchar (512)
Int_Prop_1 int
Int_Prop_2 int
Long_Prop_1 bigint
Long_Prop_2 bigint
Dec_Prop_1 numeric (13, 4)
Dec_Prop_2 numeric (13, 4)
Bool_Prop_1 bit
Bool_Prop_2 bit
Time_Zone_Id nvarchar (80)

Jobs_Qrtz_Triggers Table

Table ID: 1410104064; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Sched_Name nvarchar (120) dbo.Jobs_Qrtz_Job_Details.Sched_Name
Trigger_Name nvarchar (150)
Trigger_Group nvarchar (150)
Job_Name nvarchar (150) dbo.Jobs_Qrtz_Job_Details.Job_Name
Job_Group nvarchar (150) dbo.Jobs_Qrtz_Job_Details.Job_Group
Description nvarchar (250)
Next_Fire_Time bigint
Prev_Fire_Time bigint
Priority int
Trigger_State nvarchar (16)
Trigger_Type nvarchar (8)
Start_Time bigint
End_Time bigint
Calendar_Name nvarchar (200)
Misfire_Instr int
Job_Data image

Jobs_Triggers Table

Table ID: 1442104178; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TriggerExpression nvarchar (50)
Descrip nvarchar (250)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Boards Table

Table ID: 1474104292; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
BoardName nvarchar (50) DEFAULT (newid())
BoardGroup nvarchar (50)
Title nvarchar (100)
Descrip nvarchar (250)
OwnerId nvarchar (128)
BoardTypeName nvarchar (50) dbo.Kanban_Boards_Types.BoardTypeName
ObjectName nvarchar (50)
ObjectKey nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Boards_Columns Table

Table ID: 1506104406; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
BoardName nvarchar (50) dbo.Kanban_Boards.BoardName
ColumnName nvarchar (50) DEFAULT (newid())
Descrip nvarchar (50)
CssClass nvarchar (50)
IconId nvarchar (100)
Order int DEFAULT ((0))
Hidden bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Boards_Types Table

Table ID: 1538104520; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
BoardTypeName nvarchar (50)
Descrip nvarchar (250)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Boards_Types_Columns Table

Table ID: 1570104634; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
BoardTypeName nvarchar (50) dbo.Kanban_Boards_Types.BoardTypeName
ColumnName nvarchar (50)
Descrip nvarchar (50)
CssClass nvarchar (50)
IconId nvarchar (100)
Order int DEFAULT ((0))
Hidden bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Cards Table

Table ID: 1602104748; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
CardId nvarchar (100) DEFAULT (newid())
BoardName nvarchar (50) dbo.Kanban_Boards_Columns.BoardName
ColumnName nvarchar (50) dbo.Kanban_Boards_Columns.ColumnName
Descrip nvarchar (max)
OwnerId nvarchar (128)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Kanban_Order Table

Table ID: 1634104862; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
KanbanSettingsName nvarchar (50) dbo.Kanban_Settings.KanbanSettingsName
BoardId nvarchar (250)
JsonData nvarchar (max)

Kanban_Settings Table

Table ID: 1666104976; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
KanbanSettingsName nvarchar (50) DEFAULT (newid())
BoardTitleTemplate nvarchar (max)
BoardDescripTemplate nvarchar (max)
BoardObjectName nvarchar (50)
ColumnViewName nvarchar (255)
ColumnDescripField nvarchar (100)
ColumnIdField nvarchar (100)
ColumnCssClassField nvarchar (100)
ColumnIconIdField nvarchar (100)
CardObjectName nvarchar (50)
CardViewName nvarchar (255)
CardIdField nvarchar (100)
CardColumnIdField nvarchar (100)
CardDescripField nvarchar (100)
CardContentTemplate nvarchar (max)
onChangeColumnProcess nvarchar (255)
onCardClick nvarchar (50) DEFAULT ('edit')
EndBoxLastState nvarchar (100)
EndBoxProcess nvarchar (255)
EndBoxText nvarchar (255)
EndBoxIconName nvarchar (100)
EndBoxCssClass nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Layouts Table

Table ID: 1698105090; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
LayoutName nvarchar (100)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
LayoutDescrip nvarchar (255)
LayoutTemplate nvarchar (max)
ImagePath nvarchar (255)
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

License Table

Table ID: 1730105204; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
RequestId nvarchar (50)
LicenseId nvarchar (50)
RequestData nvarchar (max)
LicenseData nvarchar (max)
LicenseCode nvarchar (50)

LocalStorage Table

Table ID: 1762105318; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
InterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
Key nvarchar (100)
Value nvarchar (max)

Mail_Accounts Table

Table ID: 1794105432; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
MailAccountId nvarchar (100) DEFAULT (newid())
Account nvarchar (50)
UserName nvarchar (100)
VisibleName nvarchar (100)
PopImapHost nvarchar (100)
SMTPHost nvarchar (100)
MailPassword varchar (50)
SMTPPort int
PopImapPort int
UseSSL bit DEFAULT ((1))
UseTLS bit DEFAULT ((0))

MailChimp_Campaigns Table

Table ID: 1826105546; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id nvarchar (55)
WebId int
Type int
CreateTime datetime
Status nvarchar (255)
EmailsSent int
SendTime datetime
ContentType nvarchar (255)
SubjectLine nvarchar (255)
PreviewText nvarchar (255)
Title nvarchar (255)
FromName nvarchar (255)
ReplyTo nvarchar (255)
FolderId nvarchar (255)
TemplateId int
PlainText nvarchar (max)
Html nvarchar (max)
ListId nvarchar (55)
Segmented bit DEFAULT ((0))
Synchronized bit DEFAULT ((0))

MailChimp_Campaigns_Contacts Table

Table ID: 1858105660; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
CampaignId nvarchar (55) dbo.MailChimp_Campaigns.Id
EmailAddress nvarchar (255)

MailChimp_CampaignsInfo Table

Table ID: 1890105774; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
Id nvarchar (55)
EmailsSent int
AbuseReports int
Unsubscribed int
OpensTotal int
UniqueOpens int
OpenRate decimal (5, 4)
LastOpen datetime
ClicksTotal int
UniqueClicks int
ClickRate decimal (5, 4)
LastClick datetime
RecipientLikes int
UniqueLikes int
FacebookLikes int

MailChimp_CampaignsInfo_Clicks Table

Table ID: 1922105888; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
CampaignId nvarchar (55) dbo.MailChimp_Campaigns.Id
UrlId nvarchar (55)
Url nvarchar (550)
EmailAddress nvarchar (255)
Clicks int

MailChimp_CampaignsInfo_Opens Table

Table ID: 1954106002; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
CampaignId nvarchar (55) dbo.MailChimp_Campaigns.Id
EmailAddress nvarchar (255)
OpensCount int
FirstOpen datetime
LastOpen datetime

MailChimp_Contacts Table

Table ID: 1986106116; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
EmailAddress nvarchar (255)
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectId nvarchar (255)
Fname nvarchar (255)
LName nvarchar (255)
Addr1 nvarchar (255)
Addr2 nvarchar (255)
City nvarchar (255)
State nvarchar (255)
Zip nvarchar (50)
Country nvarchar (255)
Status nvarchar (50)
Language nvarchar (50)
Vip bit
IsUpload bit DEFAULT ((0))

MailChimp_Lists Table

Table ID: 2018106230; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id nvarchar (55)
WebId int
Name nvarchar (255)
Company nvarchar (255)
Address1 nvarchar (255)
Address2 nvarchar (255)
City nvarchar (255)
State nvarchar (255)
Zip nvarchar (50)
Country nvarchar (255)
Phone nvarchar (255)
PermissionReminder nvarchar (max)
DefaultCampaignFromName nvarchar (255)
DefaultCampaignFromEmail nvarchar (255)
DefaultCampaignSubject nvarchar (255)
DefaultCampaignLanguage nvarchar (255)
EmailTypeOption bit
Visibility nvarchar (50)
DateCreated datetime
MemberCount int
CampaignCount int
Synchronized bit DEFAULT ((0))

MailChimp_Lists_Contacts Table

Table ID: 2050106344; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ListId nvarchar (55) dbo.MailChimp_Lists.Id
EmailAddress nvarchar (255)

MailChimp_Objects_Contacts Table

Table ID: 2082106458; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
RegId uniqueidentifier DEFAULT (newid())
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectId nvarchar (255)
ViewName nvarchar (255)
EmailAddress nvarchar (255)
Fname nvarchar (255)
LName nvarchar (255)
Addr1 nvarchar (255)
Addr2 nvarchar (250)
City nvarchar (255)
State nvarchar (255)
Zip nvarchar (50)
Country nvarchar (255)
Status nvarchar (50)
Language nvarchar (50)
Vip bit

MailChimp_Settings Table

Table ID: 2114106572; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
SettingName nvarchar (255)
Descrip nvarchar (255)
Value nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

MailChimp_Templates Table

Table ID: 2146106686; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:32
Name Type NULL Comment
Id int
Type nvarchar (255)
Name nvarchar (255)
Html nvarchar (max)
DragAndDrop bit
Responsive bit
Category nvarchar (255)
DateCreated datetime
CreatedBy nvarchar (255)
Active bit
FolderId nvarchar (255)
Thumbnail nvarchar (255)
ShareUrl nvarchar (255)
Synchronized bit DEFAULT ((0))

Mails Table

Table ID: 30623152; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
MessageId nvarchar (250)
HeaderMessageId nvarchar (250)
Uid bigint DEFAULT ((0))
MailDate smalldatetime
Subject nvarchar (max)
BodyHtml nvarchar (max)
BodyText nvarchar (max)
BodyRtf nvarchar (max)
InReplyTo nvarchar (250)
PartialId nvarchar (250)
Importance nvarchar (150)
MimeVersion nvarchar (150)
RcptTo nvarchar (150)
ReturnPath nvarchar (150)
MailAccountId nvarchar (100) dbo.Mail_Accounts.MailAccountId
FolderId nvarchar (50) dbo.Mails_Folders.FolderId
IsForward bit DEFAULT ((0))
IsReply bit DEFAULT ((0))
IsPartial bit DEFAULT ((0))
IsEncrypted bit DEFAULT ((0))
IsSigned bit DEFAULT ((0))
IsLinked bit DEFAULT ((0))
HasAttachments bit DEFAULT ((0))
FromAddress nvarchar (500)
FromName nvarchar (500)
MailTo nvarchar (max)
MailCC nvarchar (max)
Seen bit DEFAULT ((0))
Sincronizado bit DEFAULT ((0))
Deleted bit DEFAULT ((0))

Mails_Attachments Table

Table ID: 62623266; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
MessageId nvarchar (250) dbo.Mails.MessageId
AttachmentId nvarchar (200)
FileName nvarchar (250)
ContentType nvarchar (50)
FilePath nvarchar (250)
Size int
IsEmbebed bit

Mails_Contacts Table

Table ID: 94623380; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
MessageId nvarchar (250) dbo.Mails.MessageId
TypeId nvarchar (50) dbo.Mails_Contacts_Types.TypeId
MailAddress nvarchar (500)
Name nvarchar (500)

Mails_Contacts_Types Table

Table ID: 126623494; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (500)

Mails_Folders Table

Table ID: 158623608; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
FolderId nvarchar (50)
Descrip nvarchar (500)
IconName nvarchar (100) dbo.Icons.IconName
Generic bit DEFAULT ((0))
IsInbox bit DEFAULT ((0))
IsSent bit DEFAULT ((0))
IsOutbox bit DEFAULT ((0))
CanSelect bit DEFAULT ((0))
Parent nvarchar (50) dbo.Mails_Folders.FolderId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Mails_Folders_Accounts Table

Table ID: 190623722; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
MailAccountId nvarchar (100) dbo.Mail_Accounts.MailAccountId
FolderId nvarchar (50) dbo.Mails_Folders.FolderId
Sync bit DEFAULT ((0))
SyncError nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Mails_Objects Table

Table ID: 222623836; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
MessageId nvarchar (250) dbo.Mails.MessageId
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectId nvarchar (250)
FolderId nvarchar (50) DEFAULT ('inbox')dbo.Mails_Folders.FolderId

Mails_Objects_Config Table

Table ID: 254623950; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
KeyProperty nvarchar (150)
EmailField nvarchar (1000)
DomainFilter bit DEFAULT ((0))
Path nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Mails_Outbox Table

Table ID: 286624064; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Id nvarchar (100) DEFAULT (newid())
FromName nvarchar (100)
FromEmail nvarchar (250)
To nvarchar (max)
CC nvarchar (max)
Subject nvarchar (500)
Body nvarchar (max)
UserId nvarchar (128)
SentDate smalldatetime
SendDate smalldatetime
Status int DEFAULT ((0))dbo.Mails_Status.Status
ErrorMsg nvarchar (max)
NotifiedError bit DEFAULT ((0))
ReplyTo nvarchar (max)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
LinkToId nvarchar (100)

Mails_Outbox_Attachments Table

Table ID: 318624178; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AttId nvarchar (100) DEFAULT (newid())
MailId nvarchar (100) dbo.Mails_Outbox.Id
Path nvarchar (500)
FileName nvarchar (500)

Mails_Status Table

Table ID: 350624292; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
Status int
Descrip nvarchar (50)

Mails_Templates Table

Table ID: 382624406; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
Name nvarchar (100)
Body nvarchar (max)
Subject nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Master_Tables Table

Table ID: 414624520; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TableName nvarchar (250)
Descrip nvarchar (255)
GroupName nvarchar (100) DEFAULT ('sys-generic')dbo.Master_Tables_Groups.GroupName
CollectionName nvarchar (50) dbo.Objects.ObjectName
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
Order int DEFAULT ((0))
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Master_Tables_Groups Table

Table ID: 446624634; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
GroupName nvarchar (100)
Descrip nvarchar (200)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
Order int
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Master_Tables_Properties Table

Table ID: 478624748; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
TableName nvarchar (250) dbo.Master_Tables.TableName
FieldName nvarchar (100)
SqlSentence nvarchar (max)
ConnStringId nvarchar (50) DEFAULT ((0))dbo.DbConnectionStrings.ConnStringId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Menus Table

Table ID: 510624862; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
MenuId nvarchar (50) DEFAULT (newid())
Descrip nvarchar (50)
ParentId nvarchar (50) dbo.Menus.MenuId
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules Table

Table ID: 542624976; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ModuleName nvarchar (100)
TypeId nvarchar (50) dbo.Modules_Types.TypeId
ClassId nvarchar (50) dbo.Modules_Classification.ClassId
ObjectName nvarchar (50)
ObjectFilter nvarchar (1000)
Descrip nvarchar (250)
Title nvarchar (250)
ContainerId nvarchar (50) dbo.Modules_Containers.ContainerId
CollapsibleButton bit DEFAULT ((1))
FullscreenButton bit DEFAULT ((1))
RefreshButton bit DEFAULT ((1))
SearchButton bit DEFAULT ((0))
SQlSentence nvarchar (max)
Header nvarchar (max)
HTMLText nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
CssText nvarchar (max)
ScriptText nvarchar (max)
ChartTypeId nvarchar (50) dbo.Modules_ChartsGauges_Types.ChartTypeId
ChartSettingName nvarchar (100) dbo.Charts_Settings.ChartSettingName
Series nvarchar (500)
Labels nvarchar (500)
Value nvarchar (500)
Params nvarchar (255)
JsonOptions nvarchar (500)
Path nvarchar (255)
TransFormFilePath nvarchar (255)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
PagerId nvarchar (50) dbo.Modules_Pager_Types.PagerId
PageSize int
ConnStringID nvarchar (50) dbo.DbConnectionStrings.ConnStringId
ToolbarName nvarchar (50) dbo.ToolBars.ToolbarName
GridbarName nvarchar (50) dbo.ToolBars.ToolbarName
TemplateId nvarchar (50) dbo.Objects_Templates.TemplateId
HeaderClass nvarchar (50)
ModuleClass nvarchar (50)
JSAfterLoad nvarchar (500)
Searcher bit DEFAULT ((0))
ShowWhenNew bit DEFAULT ((0))
ManualInit bit DEFAULT ((0))
SchedulerName nvarchar (20)
TimelineSettingName nvarchar (50) dbo.Timelines_Settings.TimelineSettingName
KanbanSettingsName nvarchar (50) dbo.Kanban_Settings.KanbanSettingsName
ChartBackground nvarchar (255)
ChartBorder nvarchar (255)
Reserved bit DEFAULT ((0))
Cache int DEFAULT ((0))
Offline bit DEFAULT ((0))
PresetName nvarchar (50)
MixedChartTypes nvarchar (255)
MixedChartLabels nvarchar (255)
ChartLineBorderDash bit DEFAULT ((0))
ChartLineFill bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_ChartsGauges_Types Table

Table ID: 574625090; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ChartTypeId nvarchar (50)
Descrip nvarchar (100)
ImageUrl nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_Classification Table

Table ID: 606625204; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ClassId nvarchar (50)
Descrip nvarchar (255)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_Containers Table

Table ID: 638625318; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ContainerId nvarchar (50)
Descrip nvarchar (255)
TemplateHtml varchar (max)
CssClass nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_Events Table

Table ID: 670625432; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ModuleEventId nvarchar (50) DEFAULT (newid())
ModuleName nvarchar (100) dbo.Modules.ModuleName
ModuleName nvarchar (100) dbo.Modules.ModuleName
EventClass nvarchar (50) dbo.Events_Classes_Types.EventClass
EventType nvarchar (50) dbo.Events_Classes_Types.EventType
EventAction nvarchar (50) dbo.Events_Actions.EventAction
ProcessName nvarchar (255) dbo.Processes.ProcessName
ObjectFilter nvarchar (50) dbo.Objects.ObjectName
ObjectFilter nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyFilter nvarchar (50) dbo.Objects_Properties.PropertyName
ProcessFilter nvarchar (255)
ModuleFilter nvarchar (100)
PageFilter nvarchar (100) dbo.Pages.PageName
MethodFilter nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_Pager_Types Table

Table ID: 702625546; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
PagerId nvarchar (50)
Descrip nvarchar (100)
NumButtons int
Template nvarchar (1000)
Position nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Modules_Types Table

Table ID: 734625660; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (255)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
SettingsTable nvarchar (255)
WebComponent nvarchar (50)
UseCollection bit
Reserved bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Navigation_Nodes Table

Table ID: 766625774; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NodeId uniqueidentifier DEFAULT (newid())
ParentNodeId uniqueidentifier dbo.Navigation_Nodes.NodeId
Order int DEFAULT ((0))
Title nvarchar (255)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
Descrip nvarchar (100)
TypeId nvarchar (50) dbo.Navigation_Nodes_Types.TypeId
Params nvarchar (255)
Url nvarchar (255)
TargetId nvarchar (50) DEFAULT (N'current')dbo.Targets.TargetId
ProcessName nvarchar (255) dbo.Processes.ProcessName
PageTypeId nvarchar (50) dbo.Pages_Types.TypeId
PageName nvarchar (100) dbo.Pages.PageName
ReportName nvarchar (100) dbo.Reports.ReportName
HelpId nvarchar (50) dbo.Help.HelpId
ReportWhere nvarchar (1000)
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectWhere nvarchar (1000)
Defaults varchar (2000)
SQLSentence nvarchar (max)
SQLConStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
WebComponent nvarchar (1000)
TableName nvarchar (250)
BadgeClass nvarchar (100)
BadgeSQL nvarchar (max)
BadgeConStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
BadgeRefresh int DEFAULT ((0))
Enabled bit DEFAULT ((1))
cssClass nvarchar (250)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Navigation_Nodes_Types Table

Table ID: 798625888; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

News Table

Table ID: 830626002; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NewsId uniqueidentifier DEFAULT (newid())
Title nvarchar (255)
TypeId nvarchar (100) dbo.News_Types.NewsTypeId
ImagePath nvarchar (255)
Descrip nvarchar (max)
UrlLink nvarchar (255)
PublicationDate smalldatetime
EndDate smalldatetime
UserId nvarchar (128)
PublicArticle bit
Publish bit
Alert bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

News_ReadBy Table

Table ID: 862626116; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NewsId uniqueidentifier dbo.News.NewsId
UserId nvarchar (128)

News_Types Table

Table ID: 894626230; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NewsTypeId nvarchar (100)
Descrip nvarchar (255)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Notices Table

Table ID: 926626344; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NoticeId nvarchar (100) DEFAULT (newid())
Title nvarchar (500)
Message nvarchar (1000)
AfterClickEvent nvarchar (max)
ReminderTime smalldatetime
ExpiryTime smalldatetime
MethodName nvarchar (15) dbo.Notices_Methods.MethodName
CausesSync bit DEFAULT ((0))
AllUsers bit DEFAULT ((0))
AllUsersIsSent bit DEFAULT ((0))
Error bit DEFAULT ((0))
ErrorMsg varchar (max)
CSSClass nvarchar (125)
InsertDate datetime
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())
TypeId nvarchar (50) DEFAULT (N'text')
Params nvarchar (255)
Url nvarchar (255)
TargetId nvarchar (50) DEFAULT (N'current')
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ReportName nvarchar (100)
HelpId nvarchar (50)
ReportWhere nvarchar (1000)
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectWhere nvarchar (1000)
SQLSentence nvarchar (max)
SQLConStringId nvarchar (50)
WebComponent nvarchar (1000)
TableName nvarchar (250)

Notices_Methods Table

Table ID: 958626458; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
MethodName nvarchar (15)
Descrip nvarchar (15)
IconName nvarchar (100) dbo.Icons.IconName

Notices_Sentences Table

Table ID: 990626572; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
SentenceId nvarchar (100) DEFAULT (newid())
Decrip nvarchar (250)
MailSentence nvarchar (max)
NoticeSentence nvarchar (max)
NoticeAllUsers bit DEFAULT ((0))
NoticeUsersSentence nvarchar (max)
UpdateNoticeSentence nvarchar (max)
UpdateMailSentence nvarchar (max)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
JobName nvarchar (50) dbo.Jobs.JobName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Notices_Users Table

Table ID: 1022626686; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id nvarchar (100) DEFAULT (newid())
NoticeId nvarchar (100) dbo.Notices.NoticeId
UserId nvarchar (128) dbo.AspNetUsers.Id
CurrentReference nvarchar (50)
IsSent bit DEFAULT ((0))
IsRead bit DEFAULT ((0))
Error bit DEFAULT ((0))
ErrorMsg varchar (max)

Objects Table

Table ID: 1054626800; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50) dbo.Objects.ObjectName
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100) dbo.Icons.IconName
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit DEFAULT ((0))
DefaultPageSize int DEFAULT ((200))
ParsedDescrip nvarchar (255)
Auditable int DEFAULT ((0))
Active bit
CanInsert bit DEFAULT ((1))
CanUpdate bit DEFAULT ((1))
CanDelete bit DEFAULT ((1))
CanView bit DEFAULT ((1))
CanPrint bit DEFAULT ((1))
InsertType nvarchar (10) DEFAULT ('standard')dbo.DbUpdateTypes.UpdateTypeId
UpdateType nvarchar (10) DEFAULT ('standard')
DeleteType nvarchar (10) DEFAULT ('standard')dbo.DbUpdateTypes.UpdateTypeId
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit DEFAULT ((0))
UpdateTriggerEvent bit DEFAULT ((0))
DeleteTriggerEvent bit DEFAULT ((0))
HelpId nvarchar (50) dbo.Help.HelpId
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier dbo.Navigation_Nodes.NodeId
Clonable bit DEFAULT ((1))
ViewKeys nvarchar (100)
IgnoreDBRequired bit DEFAULT ((0))
ConnStringID nvarchar (50) dbo.DbConnectionStrings.ConnStringId
TransactionOn bit DEFAULT ((1))
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit DEFAULT ((0))
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Additional_Tables Table

Table ID: 1086626914; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
TableName nvarchar (255)
KeyMap nvarchar (255)
Descrip nvarchar (255)
InsertType nvarchar (10) DEFAULT ('nothing')dbo.DbUpdateTypes.UpdateTypeId
UpdateType nvarchar (10) DEFAULT ('nothing')dbo.DbUpdateTypes.UpdateTypeId
DeleteType nvarchar (10) DEFAULT ('nothing')dbo.DbUpdateTypes.UpdateTypeId
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Images Table

Table ID: 1118627028; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ImageId uniqueidentifier DEFAULT (newid())
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectId nvarchar (170)
Name nvarchar (255)
Descrip nvarchar (255)
ImageClassId nvarchar (50) DEFAULT (N'sysimg-generic')dbo.Objects_Images_Classification.ImageClassId
MainImage bit DEFAULT ((0))
OrderNumber int DEFAULT ((0))
Path nvarchar (300)
CreationDate smalldatetime DEFAULT (getdate())

Objects_Images_Classification Table

Table ID: 1150627142; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ImageClassId nvarchar (50)
Descrip nvarchar (150)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Images_Recognition Table

Table ID: 1182627256; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:32
Name Type NULL Comment
ImageId uniqueidentifier DEFAULT (newid())
ObjectName nvarchar (50)
ObjectId nvarchar (170)
Name nvarchar (255)
OrderNumber int DEFAULT ((0))
Path nvarchar (300)
FaceEncodings nvarchar (max)
LastError nvarchar (max)

Objects_Images_Recognition_Settings Table

Table ID: 1214627370; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50)
KeyProperty nvarchar (150)
RootPath nvarchar (250)
Models nvarchar (250)
ExtensionId nvarchar (100) DEFAULT (N'sysImages')dbo.Extensions.ExtensionId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Images_Settings Table

Table ID: 1246627484; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
KeyProperty nvarchar (150)
RootPath nvarchar (250)
TypeId nvarchar (50) DEFAULT ('flexygo')dbo.Documents_Objects_Config_Types.TypeId
ERPObjectName nvarchar (250)
DefaultCategoryId nvarchar (50)
ExtensionId nvarchar (100) DEFAULT (N'sysImages')dbo.Extensions.ExtensionId
OfflineFilter nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Interfaces Table

Table ID: 1278627598; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
InterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Objects Table

Table ID: 1310627712; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ChildCollection nvarchar (50) dbo.Objects.ObjectName
ObjectRelation nvarchar (255)
ObjectDefaults nvarchar (255)
ShowInMenu bit DEFAULT ((1))
ShowInAnalysis bit DEFAULT ((1))
OneToOneRelation bit DEFAULT ((0))
Order int DEFAULT ((0))
RemoveOnDelete bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Presets Table

Table ID: 1342627826; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
PresetName nvarchar (50)
ObjectName nvarchar (50) dbo.Objects.ObjectName
Title nvarchar (250)
Filter nvarchar (max)
IconName nvarchar (100) dbo.Icons.IconName
IconClass nvarchar (100)
TitleClass nvarchar (100)
Order int DEFAULT ((0))
Offline bit DEFAULT ((0))
Originid int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Processes Table

Table ID: 1374627940; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ProcessName nvarchar (255) dbo.Processes.ProcessName
MenuId nvarchar (50) dbo.Menus.MenuId
Order int DEFAULT ((0))
Active bit DEFAULT ((1))
SQLEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (255)
EnabledProperty nvarchar (50)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
BagOnly bit DEFAULT ((0))
ClearSelectionBag bit DEFAULT ((1))
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Processes_Interfaces Table

Table ID: 1406628054; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ProcessName nvarchar (255) dbo.Processes.ProcessName
InterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Properties Table

Table ID: 1438628168; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
PropertyName nvarchar (50)
Label varchar (250)
PositionY smallint DEFAULT ((0))
PositionX smallint DEFAULT ((0))
Width smallint DEFAULT ((1))
Height smallint DEFAULT ((1))
Hide bit DEFAULT ((0))
ClientReadOnly bit DEFAULT ((0))
FormDisplay bit DEFAULT ((1))
TypeId nvarchar (50) dbo.Objects_Properties_Types.TypeId
Locked bit DEFAULT ((0))
CustomPropName nvarchar (50) dbo.Objects_Properties_Templates.CustomPropName
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLEditSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DefaultValue nvarchar (250)
PersistDefaultValue bit DEFAULT ((0))
IgnoreDBDefaultValue bit DEFAULT ((0))
DetachedFromDB bit DEFAULT ((0))
SearchFunction nvarchar (250)
SearchCollection nvarchar (50) dbo.Objects.ObjectName
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50) dbo.Objects.ObjectName
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50) DEFAULT ('popup')
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (max)
Tag varchar (500)
HelpId nvarchar (50) dbo.Help.HelpId
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
IsRequired bit DEFAULT ((0))
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
ToolbarName nvarchar (50) dbo.ToolBars.ToolbarName
Separator nvarchar (1) DEFAULT (N'|')
AutoIncrement bit DEFAULT ((0))
AutoIncrementFunction nvarchar (1000)
CascadeDependencies bit DEFAULT ((0))
RootPathType nvarchar (25) DEFAULT (N'RelativePath')dbo.Root_Path_Types.TypeId
PageSize int
ImageCompressionType smallint dbo.Image_Compression_Types.TypeId
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit DEFAULT ((0))
ExtensionId nvarchar (100) DEFAULT (N'sysAll')dbo.Extensions.ExtensionId
Autoselect bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Properties_Dependencies Table

Table ID: 1470628282; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
DependingPropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
Order int DEFAULT ((0))
Active bit DEFAULT ((1))
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (255)
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Properties_Templates Table

Table ID: 1502628396; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
CustomPropName nvarchar (50)
Descrip nvarchar (100)
TypeId nvarchar (50) DEFAULT ('dbcombo')dbo.Objects_Properties_Types.TypeId
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLEditSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
Label varchar (250)
Width smallint DEFAULT ((1))
Height smallint DEFAULT ((1))
DefaultValue nvarchar (250)
PersistDefaultValue bit DEFAULT ((0))
IgnoreDBDefaultValue bit DEFAULT ((0))
DetachedFromDB bit DEFAULT ((0))
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50)
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50) DEFAULT ('popup')
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (max)
Tag varchar (50)
HelpId nvarchar (50) dbo.Help.HelpId
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
IsRequired bit DEFAULT ((0))
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100)
Separator nvarchar (1) DEFAULT (N'|')
PageSize int
ImageCompressionType smallint dbo.Image_Compression_Types.TypeId
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit DEFAULT ((0))
ExtensionId nvarchar (100) DEFAULT (N'sysAll')dbo.Extensions.ExtensionId
Autoselect bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Properties_Types Table

Table ID: 1534628510; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (255)
WebComponent nvarchar (50)
OfflineWebComponent nvarchar (50)
DefaultSize int
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())
SearchTypes nvarchar (500) DEFAULT (N'text')
DefaultSearchType nvarchar (50) DEFAULT (N'text')
ShowInObjects bit DEFAULT ((1))
ShowInProcesses bit DEFAULT ((1))
ShowInReports bit DEFAULT ((1))

Objects_Reports Table

Table ID: 1566628624; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports.ReportName
ObjectName nvarchar (50) dbo.Objects.ObjectName
SQLEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (255)
EnabledProperty nvarchar (50)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
Active bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Search Table

Table ID: 1598628738; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
SearchId uniqueidentifier DEFAULT (newid())
ObjectName nvarchar (50) dbo.Objects.ObjectName
Name nvarchar (100)
Generic bit DEFAULT ((0))
IsDefault bit DEFAULT ((0))
Type nvarchar (20) dbo.Objects_Search_Types.Type
Order int DEFAULT ((0))
UserId nvarchar (128) dbo.AspNetUsers.Id
SQLSentence nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Search_Properties Table

Table ID: 1630628852; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
SearchId uniqueidentifier dbo.Objects_Search.SearchId
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
ObjectPath nvarchar (500)
Size int DEFAULT ((2))
Order int DEFAULT ((0))
Label nvarchar (250)
PropertySearchType nvarchar (20) dbo.Objects_Search_Properties_Types.PropertySearchType
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Search_Properties_Types Table

Table ID: 1662628966; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
PropertySearchType nvarchar (20)
Descrip nvarchar (255)
WebComponent nvarchar (50)
DefaultSize int
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Search_Types Table

Table ID: 1694629080; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Type nvarchar (20)

Objects_Search_Users_Settings Table

Table ID: 1726629194; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
SearchId uniqueidentifier dbo.Objects_Search.SearchId
UserId nvarchar (128) dbo.AspNetUsers.Id
Enabled bit
Order int DEFAULT ((0))

Objects_Search_Users_Values Table

Table ID: 1758629308; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id int
SearchId uniqueidentifier dbo.Objects_Search.SearchId
Name nvarchar (250)
UserId nvarchar (128)
Values nvarchar (max)
Generic bit DEFAULT ((0))

Objects_Selection Table

Table ID: 1790629422; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id int IDENTITY
ObjectName nvarchar (50) dbo.Objects.ObjectName
Descrip nvarchar (255)
UniquePropertyName nvarchar (50)
Active bit
UserId nvarchar (128)

Objects_Selection_Items Table

Table ID: 1822629536; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
Id int dbo.Objects_Selection.Id
ItemId nvarchar (255)

Objects_Templates Table

Table ID: 1854629650; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TemplateId nvarchar (50)
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
TypeId nvarchar (50) dbo.Objects_Templates_Types.TypeId
Descrip nvarchar (500)
Body nvarchar (max)
ViewName nvarchar (255) dbo.Objects_Views.ViewName
WhereSentence nvarchar (1000)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
ModuleClass nvarchar (100)
IsDefault bit DEFAULT ((0))
Offline bit DEFAULT ((0))
UserDefinedGroups bit DEFAULT ((0))
Active bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Templates_Groups Table

Table ID: 1886629764; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TemplateId nvarchar (50) dbo.Objects_Templates.TemplateId
GroupField nvarchar (50)
Order int DEFAULT ((0))
OrderType nvarchar (4) DEFAULT ('ASC')
Header nvarchar (max)
Footer nvarchar (max)
Offline bit DEFAULT ((0))
Label varchar (250)
UserDefault bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Templates_Samples Table

Table ID: 1918629878; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
SampleId nvarchar (150)
TypeId nvarchar (50) dbo.Objects_Templates_Types.TypeId
Descrip nvarchar (500)
Body nvarchar (max)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
Img nvarchar (250)
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Templates_Types Table

Table ID: 1950629992; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
Body nvarchar (max)
Header varchar (max)
Footer varchar (max)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Views Table

Table ID: 1982630106; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ViewName nvarchar (255)
Descrip nvarchar (255)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
SQLSentence nvarchar (max)
NoFilter bit DEFAULT ((0))
ShowAsGrid bit DEFAULT ((0))
Active bit DEFAULT ((1))
System bit DEFAULT ((0))
IsDefault bit DEFAULT ((0))
OrderBy nvarchar (max)
Offline bit DEFAULT ((0))
PrimaryKeys nvarchar (max)
IndexFields nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Views_Properties Table

Table ID: 2014630220; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
ViewName nvarchar (255) dbo.Objects_Views.ViewName
ObjectPropertyName nvarchar (50)
PropertyName nvarchar (50)
ObjectPath nvarchar (500)
Order int DEFAULT ((0))
Label nvarchar (250)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Objects_Workflows_Areas Table

Table ID: 2046630334; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
WorkflowAreaId nvarchar (50) dbo.Workflows_Areas.WorkflowAreaId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Apps Table

Table ID: 2078630448; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
AppName nvarchar (50)
Title nvarchar (50)
Descrip nvarchar (max)
IconName nvarchar (100) dbo.Icons.IconName
APKUrl nvarchar (600)
APKWebService nvarchar (600)
SyncDataProcessName nvarchar (255)
Active bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Files Table

Table ID: 2110630562; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
FileName nvarchar (150)
AppName nvarchar (50) dbo.Offline_Apps.AppName
FilePath nvarchar (500)
FileDate smalldatetime
Enabled bit DEFAULT ((1))
OriginID int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Menus Table

Table ID: 2142630676; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
MenuId uniqueidentifier DEFAULT (newid())
AppName nvarchar (50) dbo.Offline_Apps.AppName
ParentMenuId uniqueidentifier
Order int
Title nvarchar (255)
IconName nvarchar (100)
Descrip nvarchar (255)
TypeId nvarchar (50)
Url nvarchar (255)
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
Enabled bit DEFAULT ((1))
cssClass nvarchar (255)
OriginID int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Menus_Types Table

Table ID: 27147142; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Objects Table

Table ID: 59147256; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (50) dbo.Offline_Apps.AppName
ObjectName nvarchar (50) dbo.Objects.ObjectName
BufferSize int DEFAULT ((500))
UpdateRelatedPrimaryKeys bit DEFAULT ((1))
SyncImmediately bit DEFAULT ((0))
SendData bit DEFAULT ((1))
GetData bit DEFAULT ((1))
TableName nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Pages Table

Table ID: 91147370; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (50) dbo.Offline_Apps.AppName
PageName nvarchar (50)
ObjectName nvarchar (50) dbo.Objects.ObjectName
TypeId nvarchar (50)
Title nvarchar (150)
Body nvarchar (max)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
SQLSentence nvarchar (max)
SQLAdditionalWhere nvarchar (max)
SQLOrderBy nvarchar (max)
SQLSearchFilter nvarchar (max)
IsDefault bit DEFAULT ((0))
ShowSearchBar bit DEFAULT ((0))
JSAfterLoad nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Pages_Groups Table

Table ID: 123147484; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (50) dbo.Offline_Pages.AppName
PageName nvarchar (50) dbo.Offline_Pages.PageName
GroupField nvarchar (50)
Order int DEFAULT ((0))
OrderType nvarchar (4) DEFAULT ('ASC')
Header nvarchar (max)
Footer nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Scripts Table

Table ID: 155147598; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (50) dbo.Offline_Apps.AppName
Name nvarchar (50)
JSScript nvarchar (max)
Enabled bit DEFAULT ((1))
Order int DEFAULT ((0))
LastChange datetime DEFAULT (getdate())
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Styles Table

Table ID: 187147712; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
AppName nvarchar (50) dbo.Offline_Apps.AppName
Name nvarchar (50)
CSSCode nvarchar (max)
Enabled bit DEFAULT ((1))
Order int DEFAULT ((0))
LastChange datetime DEFAULT (getdate())
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Offline_Sync Table

Table ID: 219147826; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
SyncId nvarchar (100) DEFAULT (newid())
AppName nvarchar (50) dbo.Offline_Apps.AppName
SyncDate smalldatetime DEFAULT (getdate())
Username nvarchar (150)
Finished bit DEFAULT ((0))
FinishDate smalldatetime
Error bit DEFAULT ((0))
ErrorDesc nvarchar (max)

Offline_Sync_Tables Table

Table ID: 251147940; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
SyncId nvarchar (100) DEFAULT (newid())dbo.Offline_Sync.SyncId
TableName nvarchar (250)
PageNumber int
JsonValue nvarchar (max)

Origins Table

Table ID: 283148054; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
OriginId int
Descrip nvarchar (50)
Active bit

Pages Table

Table ID: 315148168; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
PageName nvarchar (100) DEFAULT (newid())
TypeId nvarchar (50) dbo.Pages_Types.TypeId
ObjectName nvarchar (50) dbo.Objects.ObjectName
InterfaceName nvarchar (100) dbo.Interfaces.InterfaceName
LayoutName nvarchar (100) DEFAULT (N'default')dbo.Layouts.LayoutName
Name nvarchar (255)
IconName nvarchar (100) DEFAULT (N'noicon')dbo.Icons.IconName
Descrip nvarchar (100)
UrlRewrite nvarchar (255)
Script nvarchar (max)
ScriptActive bit DEFAULT ((0))
Style nvarchar (1000)
RefreshInterval int DEFAULT ((0))
Sytem bit DEFAULT ((0))
Generic bit DEFAULT ((0))
BodyCssClass nvarchar (200)
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Pages_Modules Table

Table ID: 347148282; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
ModuleName nvarchar (100) dbo.Modules.ModuleName
LayoutPositionId nvarchar (50)
RelationWhere nvarchar (1000)
Order int DEFAULT ((0))
SQlEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (250)
Title nvarchar (250)
IconName nvarchar (100) dbo.Icons.IconName
HeaderClass nvarchar (50)
ModuleClass nvarchar (50)
ConnStringID nvarchar (50) dbo.DbConnectionStrings.ConnStringId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Pages_Modules_Tabs Table

Table ID: 379148396; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
TabModuleName nvarchar (100) dbo.Modules.ModuleName
ModuleName nvarchar (100) dbo.Modules.ModuleName
Order int DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Pages_Types Table

Table ID: 411148510; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Plugins Table

Table ID: 443148624; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PluginId uniqueidentifier DEFAULT (newid())
Path nvarchar (500)
Descrip nvarchar (100)
Order int DEFAULT ((100))
typeId int DEFAULT ((0))dbo.Plugins_Types.TypeId
Bundle bit DEFAULT ((1))
Enabled bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Plugins_Types Table

Table ID: 475148738; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
TypeId int
Descrip nvarchar (100)

Processes Table

Table ID: 507148852; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ProcessName nvarchar (255)
TypeId int dbo.Processes_Types.TypeId
ClassId nvarchar (50) dbo.Processes_Classification.ClassId
ConfirmText varchar (200)
ProcessDescrip nvarchar (500)
ParamsDescrip nvarchar (500)
ReturnDescrip nvarchar (500)
JSforParams varchar (500)
File varchar (255)
Class varchar (255)
Method varchar (50)
StoredName varchar (255)
Code varchar (max)
ExternalUrl varchar (255)
PageTypeId nvarchar (50) dbo.Pages_Types.TypeId
PageName nvarchar (100) dbo.Pages.PageName
ReportName nvarchar (100) dbo.Reports.ReportName
HelpId uniqueidentifier
ReportWhere nvarchar (1000)
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectWhere nvarchar (1000)
Defaults varchar (2000)
TimeOut int DEFAULT ((0))
ConnStringId nvarchar (255)
TargetId nvarchar (50) DEFAULT (N'current')dbo.Targets.TargetId
ProcessFlowText nvarchar (500)
Auditable bit DEFAULT ((1))
Refresh bit DEFAULT ((1))
IsTransacted bit DEFAULT ((0))
AdminOnly bit DEFAULT ((0))
ConfirmOkText bit DEFAULT ((1))
CloseDialogOnOk bit DEFAULT ((0))
RunButtonText nvarchar (100)
LoadProcessName nvarchar (255) dbo.Processes.ProcessName
GipeParams bit DEFAULT ((0))
Summary nvarchar (max)
ReturnTableNames nvarchar (max)
Reserved bit DEFAULT ((0))
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Classification Table

Table ID: 539148966; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ClassId nvarchar (50)
Descrip nvarchar (255)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Objects Table

Table ID: 571149080; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProcessName nvarchar (255) dbo.Processes.ProcessName
ObjectName nvarchar (50) dbo.Objects.ObjectName
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Params Table

Table ID: 603149194; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProcessName nvarchar (255) dbo.Processes.ProcessName
ParamName nvarchar (50)
Hide bit DEFAULT ((0))
ParamTypeId nvarchar (50) dbo.Processes_Params_Types.ParamTypeId
TableName nvarchar (250)
ObjectName nvarchar (50) dbo.Objects.ObjectName
DefaultValue nvarchar (250)
Label varchar (250)
IOTypeId nvarchar (5) dbo.Processes_Params_TypeIO.IOTypeId
PositionX smallint DEFAULT ((0))
PositionY smallint DEFAULT ((0))
Width smallint DEFAULT ((1))
Height smallint DEFAULT ((1))
TypeId nvarchar (50) dbo.Objects_Properties_Types.TypeId
Locked bit DEFAULT ((0))
CustomPropName nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DetachedFromProcess bit DEFAULT ((0))
SearchFunction nvarchar (250)
SearchCollection nvarchar (50) dbo.Objects.ObjectName
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50) dbo.Objects.ObjectName
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50) DEFAULT ((0))
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (500)
Tag varchar (500)
HelpId nvarchar (50) dbo.Help.HelpId
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
IsRequired bit DEFAULT ((0))
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
ToolbarName nvarchar (50) dbo.ToolBars.ToolbarName
Separator nvarchar (1) DEFAULT (N'|')
CascadeDependencies bit DEFAULT ((0))
RootPathType nvarchar (25) DEFAULT (N'RelativePath')dbo.Root_Path_Types.TypeId
ImageCompressionType smallint dbo.Image_Compression_Types.TypeId
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit DEFAULT ((0))
ExtensionId nvarchar (100) DEFAULT (N'sysAll')dbo.Extensions.ExtensionId
Autoselect bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Params_Dependencies Table

Table ID: 635149308; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProcessName nvarchar (255) dbo.Processes_Params.ProcessName
ParamName nvarchar (50) dbo.Processes_Params.ParamName
DependingParamName nvarchar (50)
Order int
Active bit
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
Offline bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Params_TypeIO Table

Table ID: 667149422; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
IOTypeId nvarchar (5)
Descrip nvarchar (50)

Processes_Params_Types Table

Table ID: 699149536; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ParamTypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Processes Table

Table ID: 731149650; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Guid uniqueidentifier DEFAULT (newid())
WorkflowName nvarchar (255)
ParentProcessName nvarchar (255) dbo.Processes.ProcessName
ParentObjectName nvarchar (50)
ParentEventName nvarchar (50)
ProcessName nvarchar (255) dbo.Processes.ProcessName
Order int DEFAULT ((0))
ExecuteCondition nvarchar (max)
ContinueAfterFail bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Processes_Params Table

Table ID: 763149764; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Guid uniqueidentifier dbo.Processes_Processes.Guid
InputProcessName nvarchar (255) dbo.Processes_Params.ProcessName
InputParamName nvarchar (50) dbo.Processes_Params.ParamName
OutputProcessName nvarchar (255) dbo.Processes_Params.ProcessName
OutputParamName nvarchar (50) dbo.Processes_Params.ParamName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Processes_Types Table

Table ID: 795149878; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId int
Descrip nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
Active bit DEFAULT ((1))

Processes_Workflows_Areas Table

Table ID: 827149992; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProcessName nvarchar (255) dbo.Processes.ProcessName
WorkflowAreaId nvarchar (50) dbo.Workflows_Areas.WorkflowAreaId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Redsys_Logs Table

Table ID: 859150106; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TransactionId nvarchar (100)
StatusId nvarchar (50) dbo.Redsys_Logs_Status.StatusId
CreatedDate smalldatetime
ObjectToken nvarchar (max)
Response nvarchar (max)
ErrorMsg nvarchar (max)
UserName nvarchar (256)

Redsys_Logs_Status Table

Table ID: 891150220; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
StatusId nvarchar (50)
Descrip nvarchar (255)

RedSys_Settings Table

Table ID: 923150334; Created: November 16, 2021, 18:20:31
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
AmountField nvarchar (50)
SuccessMessage nvarchar (255)
ErrorMessage nvarchar (255)
OnlySuccess bit

RegEx Table

Table ID: 955150448; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
RegExId nvarchar (100)
RegEx nvarchar (500)
Descrip nvarchar (255)
ValidItems nvarchar (500)
UnvalidItems nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Reports Table

Table ID: 987150562; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ReportName nvarchar (100)
ReportDescrip nvarchar (255)
TypeId nvarchar (20) DEFAULT ('crystal')dbo.Reports_Types.TypeId
ReportPath nvarchar (255)
AdditionalWhere nvarchar (1000)
NoFilter bit DEFAULT ((0))
Order int DEFAULT ((0))
IconName nvarchar (100) dbo.Icons.IconName
PDF bit DEFAULT ((1))
Word bit DEFAULT ((0))
Excel bit DEFAULT ((0))
ParamsTargetId nvarchar (50) dbo.Targets.TargetId
LoadProcessName nvarchar (255) dbo.Processes.ProcessName
ReportMode nvarchar (10) DEFAULT ('pdf')dbo.Reports_Modes.ReportModeId
FilterSentence nvarchar (500)
RoleSentence nvarchar (500)
ObjectName nvarchar (50)
TemplateId nvarchar (50)
FilterReportReplacingSentence bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Reports_Modes Table

Table ID: 1019150676; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ReportModeId nvarchar (10)
Descrip nvarchar (50)
IconName nvarchar (100) dbo.Icons.IconName

Reports_Params Table

Table ID: 1051150790; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports.ReportName
ParamName nvarchar (50)
Label varchar (250)
PositionX smallint DEFAULT ((0))
PositionY smallint DEFAULT ((0))
Width smallint DEFAULT ((1))
Height smallint DEFAULT ((1))
Hide bit
TypeId nvarchar (50) dbo.Objects_Properties_Types.TypeId
Locked bit DEFAULT ((0))
CustomPropName nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DefaultValue nvarchar (250)
DetachedFromProcess bit DEFAULT ((0))
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50) dbo.Objects.ObjectName
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50) DEFAULT ((0))
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (500)
Tag varchar (50)
HelpId nvarchar (50) dbo.Help.HelpId
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
IsRequired bit DEFAULT ((0))
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100) dbo.Icons.IconName
ToolbarName nvarchar (50) dbo.ToolBars.ToolbarName
Separator nvarchar (1) DEFAULT (N'|')
CascadeDependencies bit DEFAULT ((0))
RootPathType nvarchar (25) DEFAULT (N'RelativePath')dbo.Root_Path_Types.TypeId
ImageCompressionType smallint dbo.Image_Compression_Types.TypeId
ImageMaxWidth smallint
ImageMaxHeight smallint
ExtensionId nvarchar (100) DEFAULT (N'sysAll')dbo.Extensions.ExtensionId
Autoselect bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Reports_Params_Dependencies Table

Table ID: 1083150904; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports_Params.ReportName
ParamName nvarchar (50) dbo.Reports_Params.ParamName
DependingParamName nvarchar (50)
order int
Active bit
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Reports_Types Table

Table ID: 1115151018; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (20)
Descrip varchar (50)
IconName nvarchar (100) dbo.Icons.IconName
Active bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Root_Path_Types Table

Table ID: 1147151132; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TypeId nvarchar (25)
Description nvarchar (50)
Active bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Scheduler Table

Table ID: 1179151246; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
SchedulerName nvarchar (20)
ActiveMode nvarchar (20)
MonthView bit
AgendaWeekView bit
AgendaDayView bit
ListWeekView bit
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLFilterField nvarchar (500)
DirectTemplate nvarchar (500)
ObjectName nvarchar (50)
ViewName nvarchar (255)
MinTime nvarchar (5)
MaxTime nvarchar (5)
OnClickEvent bit
AllDaySlot bit
SlotDuration nvarchar (5)
TokenDefault nvarchar (100)
EventPageTypeId nvarchar (50)
EventTargetId nvarchar (50)
HolidaysObjectName nvarchar (255)
HolidaysViewName nvarchar (255)
DateHolidayField nvarchar (255)
EventLimit bit DEFAULT ((1))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Scheduler_Objects Table

Table ID: 1211151360; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
SchedulerName nvarchar (20) dbo.Scheduler.SchedulerName
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
ViewName nvarchar (255) dbo.Objects_Views.ViewName
StartDateField nvarchar (50)
EndDateField nvarchar (50)
StartTimeField nvarchar (50)
EndTimeField nvarchar (50)
DurationField nvarchar (50)
ColorField nvarchar (50)
DescripTemplate nvarchar (max)
UserIdField nvarchar (255)
TextColorField nvarchar (50)
AllDayField nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Scheduler_Views Table

Table ID: 1243151474; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
ViewId nvarchar (20)
Descrip nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Scripts_Jobs Table

Table ID: 1275151588; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ScriptId nvarchar (100) DEFAULT (newid())
Descrip nvarchar (250)
Notes nvarchar (max)
CreationDate smalldatetime
State nvarchar (50) dbo.Scripts_Jobs_States.State
Script nvarchar (max)
ConnStringId nvarchar (50) dbo.DbConnectionStrings.ConnStringId
ExecuteOrder smallint DEFAULT ((0))
StartDate smalldatetime
EndDate smalldatetime
ErrorMessage nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Scripts_Jobs_States Table

Table ID: 1307151702; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
State nvarchar (50)
Descrip nvarchar (50)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_IP_Lockout Table

Table ID: 1339151816; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:20:33
Name Type NULL Comment
Id int IDENTITY
IP nvarchar (50)
LockoutDate datetime DEFAULT (getdate())
LockoutEndDate datetime
Reason nvarchar (1000)

Security_Master_Tables_Roles Table

Table ID: 1371151930; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TableName nvarchar (250) dbo.Master_Tables.TableName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
CanUpdate bit DEFAULT ((0))
CanDelete bit DEFAULT ((0))
CanInsert bit DEFAULT ((0))
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Master_Tables_Users Table

Table ID: 1403152044; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TableName nvarchar (250) dbo.Master_Tables.TableName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
CanUpdate bit DEFAULT ((0))
CanDelete bit DEFAULT ((0))
CanInsert bit DEFAULT ((0))
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Modules_Faculties Table

Table ID: 1435152158; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ModuleName nvarchar (100) dbo.Modules.ModuleName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Modules_Roles Table

Table ID: 1467152272; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ModuleName nvarchar (100) dbo.Modules.ModuleName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Modules_Users Table

Table ID: 1499152386; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ModuleName nvarchar (100) dbo.Modules.ModuleName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Navigation_Nodes_Faculties Table

Table ID: 1531152500; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NodeId uniqueidentifier dbo.Navigation_Nodes.NodeId
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Navigation_Nodes_Roles Table

Table ID: 1563152614; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NodeId uniqueidentifier dbo.Navigation_Nodes.NodeId
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Navigation_Nodes_Users Table

Table ID: 1595152728; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NodeId uniqueidentifier dbo.Navigation_Nodes.NodeId
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Faculties Table

Table ID: 1627152842; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit DEFAULT ((0))
ViewFilter nvarchar (2048)
CanViewCollection bit DEFAULT ((0))
ViewFilterCollection nvarchar (2048)
CanInsert bit DEFAULT ((0))
InsertFilter nvarchar (2048)
CanEdit bit DEFAULT ((0))
EditFilter nvarchar (2048)
CanDelete bit DEFAULT ((0))
DeleteFilter nvarchar (2048)
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Processes_Faculties Table

Table ID: 1659152956; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ProcessName nvarchar (255) dbo.Processes.ProcessName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Processes_Roles Table

Table ID: 1691153070; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ProcessName nvarchar (255) dbo.Processes.ProcessName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Processes_Users Table

Table ID: 1723153184; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
ProcessName nvarchar (255) dbo.Processes.ProcessName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
ViewFilter nvarchar (2048)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Properties_Faculties Table

Table ID: 1755153298; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
CanEdit bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Properties_Roles Table

Table ID: 1787153412; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
CanEdit bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Properties_Users Table

Table ID: 1819153526; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
PropertyName nvarchar (50) dbo.Objects_Properties.PropertyName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
CanEdit bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Roles Table

Table ID: 1851153640; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit DEFAULT ((0))
ViewFilter nvarchar (2048)
CanViewCollection bit DEFAULT ((0))
ViewFilterCollection nvarchar (2048)
CanInsert bit DEFAULT ((0))
InsertFilter nvarchar (2048)
CanEdit bit DEFAULT ((0))
EditFilter nvarchar (2048)
CanDelete bit DEFAULT ((0))
DeleteFilter nvarchar (2048)
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Templates_Faculties Table

Table ID: 1883153754; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TemplateId nvarchar (50) dbo.Objects_Templates.TemplateId
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Templates_Roles Table

Table ID: 1915153868; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TemplateId nvarchar (50) dbo.Objects_Templates.TemplateId
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Templates_Users Table

Table ID: 1947153982; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
TemplateId nvarchar (50) dbo.Objects_Templates.TemplateId
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Objects_Users Table

Table ID: 1979154096; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit DEFAULT ((0))
ViewFilter nvarchar (2048)
CanViewCollection bit DEFAULT ((0))
ViewFilterCollection nvarchar (2048)
CanInsert bit DEFAULT ((0))
InsertFilter nvarchar (2048)
CanEdit bit DEFAULT ((0))
EditFilter nvarchar (2048)
CanDelete bit DEFAULT ((0))
DeleteFilter nvarchar (2048)
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Offline_Menus_Faculties Table

Table ID: 2011154210; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
MenuId uniqueidentifier dbo.Offline_Menus.MenuId
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Offline_Menus_Roles Table

Table ID: 2043154324; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
MenuId uniqueidentifier dbo.Offline_Menus.MenuId
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Offline_Menus_Users Table

Table ID: 2075154438; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
MenuId uniqueidentifier dbo.Offline_Menus.MenuId
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Faculties Table

Table ID: 2107154552; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
Canview bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Modules_Faculties Table

Table ID: 2139154666; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
ModuleName nvarchar (100) dbo.Modules.ModuleName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Modules_Roles Table

Table ID: 23671132; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
ModuleName nvarchar (100) dbo.Modules.ModuleName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Modules_Users Table

Table ID: 55671246; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
ModuleName nvarchar (100) dbo.Modules.ModuleName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanView bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Roles Table

Table ID: 87671360; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
RoleId nvarchar (128) dbo.AspNetRoles.Id
Canview bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Pages_Users Table

Table ID: 119671474; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
PageName nvarchar (100) dbo.Pages.PageName
UserId nvarchar (128) dbo.AspNetUsers.Id
Canview bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Reports_Faculties Table

Table ID: 151671588; Created: November 16, 2021, 18:20:31; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports.ReportName
FacultyId nvarchar (128) dbo.AspNetFaculties.FacultyId
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Reports_Roles Table

Table ID: 183671702; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports.ReportName
RoleId nvarchar (128) dbo.AspNetRoles.Id
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Security_Reports_Users Table

Table ID: 215671816; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
ReportName nvarchar (100) dbo.Reports.ReportName
UserId nvarchar (128) dbo.AspNetUsers.Id
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Settings Table

Table ID: 247671930; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
SettingName nvarchar (150)
SettingValue nvarchar (max)
IconName nvarchar (100) dbo.Icons.IconName
Description nvarchar (1000)
SettingCustomProperty nvarchar (50)
Active bit DEFAULT ((1))
GroupName nvarchar (20) dbo.Settings_Groups.GroupName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Settings_Groups Table

Table ID: 279672044; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
GroupName nvarchar (20) DEFAULT (newid())
Descrip nvarchar (250)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Settings_Values Table

Table ID: 311672158; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
SettingName nvarchar (150)
SettingValue nvarchar (1000)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Skins Table

Table ID: 343672272; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
SkinId nvarchar (50)
Descrip nvarchar (100)
Css nvarchar (max)
Script nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Skins_Css Table

Table ID: 375672386; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
CssId nvarchar (150) DEFAULT (newid())
SkinId nvarchar (50) dbo.Skins.SkinId
CssPath nvarchar (500)
Descrip nvarchar (100)
InBundle bit DEFAULT ((1))
Order int DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())
Enabled bit DEFAULT ((1))

Skins_Variables Table

Table ID: 407672500; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:23
Name Type NULL Comment
SkinId nvarchar (50) dbo.Skins.SkinId
VarName nvarchar (50)
Descrip nvarchar (50)
VarValue nvarchar (100)
VarType nvarchar (50)
VarGroup nvarchar (50)
VarOrder int DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Targets Table

Table ID: 439672614; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TargetId nvarchar (50)
Descrip nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Tests Table

Table ID: 471672728; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
TestId nvarchar (100) DEFAULT (newid())
Title nvarchar (100)
Path nvarchar (500)
ExcludeCategories nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Timeline_Layouts Table

Table ID: 503672842; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
LayoutName nvarchar (25)
Order int

Timeline_Ranges Table

Table ID: 535672956; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
RangeName nvarchar (25)
Order int

Timelines_Settings Table

Table ID: 567673070; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
TimelineSettingName nvarchar (50)
TimelineSettingDescrip nvarchar (100)
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
ObjectName nvarchar (50) dbo.Objects.ObjectName
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
ObjectName nvarchar (50) dbo.Objects_Properties.ObjectName
Advanced bit DEFAULT ((0))
Editable bit DEFAULT ((0))
WithGroups bit DEFAULT ((0))
ShowItemsWithoutGroup bit DEFAULT ((0))
TitleItemsWithoutGroup nvarchar (25)
LayoutName nvarchar (25) DEFAULT ('Left')dbo.Timeline_Layouts.LayoutName
DefaultRangeName nvarchar (25) DEFAULT ('Week')dbo.Timeline_Ranges.RangeName
ShowControls bit DEFAULT ((1))
OnInsertOpenNewWithDefaults bit DEFAULT ((1))
PropertyDescrip nvarchar (50) dbo.Objects_Properties.PropertyName
PropertyStartDate nvarchar (50) dbo.Objects_Properties.PropertyName
PropertyEndDate nvarchar (50) dbo.Objects_Properties.PropertyName
PropertyGroup nvarchar (50) dbo.Objects_Properties.PropertyName
GroupViewName nvarchar (255) dbo.Objects_Views.ViewName
GroupIdField nvarchar (100)
GroupDescripField nvarchar (100)
GroupClassNameField nvarchar (100)
GroupStyleField nvarchar (100)
GroupContentTemplate nvarchar (max)
ItemViewName nvarchar (255) dbo.Objects_Views.ViewName
ItemDescripField nvarchar (100)
ItemStartDateField nvarchar (100)
ItemEndDateField nvarchar (100)
ItemGroupField nvarchar (100)
ItemEditableField nvarchar (100)
ItemClassNameField nvarchar (100)
ItemStyleField nvarchar (100)
ItemTypeField nvarchar (100)
ItemContentTemplate nvarchar (max)
ItemVisibleFrameTemplate nvarchar (max)
OnMovingFunction nvarchar (max)
OnDropObjectOnItemFunction nvarchar (max)
OnDeleteFunction nvarchar (max)
CustomOptions nvarchar (max)
DefaultTime int DEFAULT ((60))
EventPageTypeId nvarchar (50) DEFAULT ('edit')
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

ToolBars Table

Table ID: 599673184; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ToolbarName nvarchar (50)
Descrip nvarchar (150)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

ToolBars_Buttons Table

Table ID: 631673298; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ButtonId nvarchar (100) DEFAULT (newid())
ToolbarName nvarchar (50) dbo.ToolBars.ToolbarName
ParentButtonId nvarchar (100) dbo.ToolBars_Buttons.ButtonId
Order int DEFAULT ((0))
TypeId nvarchar (50) dbo.ToolBars_Buttons_Types.ButtonType
PositionId nvarchar (50) dbo.ToolBars_Buttons_Positions.PositionId
Text nvarchar (150)
Tooltip nvarchar (150)
IconName nvarchar (100) dbo.Icons.IconName
HideText bit DEFAULT ((0))
CssClass nvarchar (255)
SQlSentence nvarchar (max)
ProcessName nvarchar (255)
TargetId varchar (50) DEFAULT ('current')
ReportName nvarchar (100) dbo.Reports.ReportName
HelpId nvarchar (50) dbo.Help.HelpId
Disabled bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

ToolBars_Buttons_Positions Table

Table ID: 663673412; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
PositionId nvarchar (50)

ToolBars_Buttons_Types Table

Table ID: 695673526; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ButtonType nvarchar (50)
Descrip nvarchar (250)

Translate Table

Table ID: 727673640; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
CultureId nvarchar (8) dbo.Cultures.CultureId
Original nvarchar (255)
Text nvarchar (255)
Area nvarchar (100) dbo.Translate_Areas.Area
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Translate_Areas Table

Table ID: 759673754; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Area nvarchar (100)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Versions Table

Table ID: 791673868; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
VersionNumber nvarchar (50)
InstallDate datetime
IsUpdate bit DEFAULT ((0))
OriginDatabase nvarchar (255)
UpdateLog nvarchar (max)

Versions_Differences Table

Table ID: 823673982; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
DifferenceId nvarchar (50) DEFAULT (newid())
VersionNumber nvarchar (50) dbo.Versions.VersionNumber
TableName nvarchar (256)
FieldName nvarchar (256)
RowKey nvarchar (1000)
SystemValue nvarchar (max)
UserValue nvarchar (max)
CurrentValue nvarchar (max)
ManualValue nvarchar (max)
RowOriginId int dbo.Origins.OriginId
Action smallint dbo.Configuration_Actions_Types.ActionId
Applied bit DEFAULT ((0))
Revised bit DEFAULT ((0))

Versions_Scripts Table

Table ID: 855674096; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ScriptId nvarchar (256) dbo.Configuration_Scripts.ScriptId
VersionNumber nvarchar (50) dbo.Versions.VersionNumber
ExecutedDate datetime
Result bit
ExecuteLog nvarchar (max)

Videos Table

Table ID: 887674210; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
VideoName nvarchar (100)
Title nvarchar (250)
Descrip nvarchar (max)
Url nvarchar (250)
Classification nvarchar (50) dbo.Videos_Classification.Classification
Category nvarchar (50) dbo.Videos_Categories.Category
Image nvarchar (250)
Author nvarchar (100)
Duration int
Order int DEFAULT ((0))
IsNew bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Videos_Categories Table

Table ID: 919674324; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Category nvarchar (50)
Descrip nvarchar (250)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Videos_Classification Table

Table ID: 951674438; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Classification nvarchar (50)
Title nvarchar (250)
Descrip nvarchar (max)
IconName nvarchar (100) dbo.Icons.IconName
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebAPI_Apps Table

Table ID: 983674552; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:20:33
Name Type NULL Comment
AppName nvarchar (255)
Descrip nvarchar (255)
Icon nvarchar (500)
ReturnTokenUrl nvarchar (500)
ClientSecret nvarchar (500)
isAuthorized bit DEFAULT ((1))

WebAPI_Objects Table

Table ID: 1015674666; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects.ObjectName
CanView bit DEFAULT ((0))
CanViewCollection bit DEFAULT ((0))
CanInsert bit DEFAULT ((0))
CanEdit bit DEFAULT ((0))
CanDelete bit DEFAULT ((0))
CanPrint bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebAPI_Processes Table

Table ID: 1047674780; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ProcessName nvarchar (255) dbo.Processes.ProcessName
CanView bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebAPI_Roles Table

Table ID: 1079674894; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
RoleId nvarchar (128) dbo.AspNetRoles.Id
isAuthorized bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebAPI_Users Table

Table ID: 1111675008; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
UserId nvarchar (128) dbo.AspNetUsers.Id
isAuthorized bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebAPI_Views Table

Table ID: 1143675122; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ObjectName nvarchar (50) dbo.Objects_Views.ObjectName
ViewName nvarchar (255) dbo.Objects_Views.ViewName
CanView bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

WebHooks Table

Table ID: 1175675236; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:20:35
Name Type NULL Comment
WebHookID nvarchar (255)
Origin nvarchar (255)
ProcessName nvarchar (255)
RequiresAuthorization bit DEFAULT ((0))
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows Table

Table ID: 1207675350; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
WorkflowId nvarchar (255) DEFAULT (newid())
Version smallint
ModuleId nvarchar (50) dbo.Workflows_Modules.WorkflowModuleId
AreaId nvarchar (50) dbo.Workflows_Areas.WorkflowAreaId
Descrip nvarchar (255)
WorkflowData nvarchar (max)
Active bit
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Areas Table

Table ID: 1239675464; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:25
Name Type NULL Comment
WorkflowAreaId nvarchar (50) DEFAULT (newid())
Descrip nvarchar (500)
ParentAreaId nvarchar (50) dbo.Workflows_Areas.WorkflowAreaId
Observations nvarchar (4000)
IconName nvarchar (100) dbo.Icons.IconName
AreaData nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Executions Table

Table ID: 1271675578; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ExecutionId bigint
ParentExecutionId bigint
MasterExecutionId bigint
WorkflowId nvarchar (255) dbo.Workflows.WorkflowId
WorkflowVersion smallint dbo.Workflows.Version
Start datetime
Finish datetime
ResultId smallint dbo.Workflows_Results.ResultId
StatusId smallint dbo.Workflows_Status.StatusId
ErrorMessage nvarchar (max)
WarningMessage nvarchar (max)
ExecutionData nvarchar (max)
UserId nvarchar (128)

Workflows_Executions_Nodes Table

Table ID: 1303675692; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
Id bigint
ExecutionId bigint dbo.Workflows_Executions.ExecutionId
NodeId nvarchar (50)
ThreadId int
Start datetime
ProcessTime time
Finish datetime
ResultId smallint dbo.Workflows_Results.ResultId
StatusId smallint dbo.Workflows_Status.StatusId
ErrorMessage nvarchar (max)
WarningMessage nvarchar (max)
ExecutionData nvarchar (max)

Workflows_Modules Table

Table ID: 1335675806; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
WorkflowModuleId nvarchar (50) DEFAULT (newid())
Descrip nvarchar (500)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Nodes Table

Table ID: 1367675920; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
NodeId uniqueidentifier DEFAULT (newid())
WorkflowName nvarchar (255) dbo.Workflows.WorkflowId
Version smallint dbo.Workflows.Version
NodeType smallint dbo.Workflows_Nodes_Types.WorkflowNodeTypeId
GraphId int
ProcessName nvarchar (255) dbo.Processes.ProcessName
ObjectName nvarchar (50) dbo.Objects.ObjectName
EventName nvarchar (50)
ExecuteCondition nvarchar (max)
ContinueAfterFail bit
InitialNode bit
NodeLabel nvarchar (1000)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Nodes_Types Table

Table ID: 1399676034; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
WorkflowNodeTypeId smallint
Descrip nvarchar (50)

Workflows_Relations Table

Table ID: 1431676148; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
RelationId uniqueidentifier DEFAULT (newid())
WorkflowName nvarchar (255) dbo.Workflows.WorkflowId
Version smallint dbo.Workflows.Version
GraphId int
ParentGuid uniqueidentifier
ChildGuid uniqueidentifier
ParentValue nvarchar (255)
ExecuteCondition nvarchar (max)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Relations_Parameters Table

Table ID: 1463676262; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ParameterRelationId uniqueidentifier DEFAULT (newid())
RelationId uniqueidentifier dbo.Workflows_Relations.RelationId
ChildParamName nvarchar (50)
ParentType nvarchar (50) dbo.Workflows_Relations_Types.RelationType
ParentNode nvarchar (255)
ParentParamName nvarchar (50)
DefaultValue nvarchar (1000)
OriginId int DEFAULT ([dbo].[funNet_GetOrigin]())

Workflows_Relations_Types Table

Table ID: 1495676376; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
RelationType nvarchar (50)
Descrip nvarchar (255)

Workflows_Results Table

Table ID: 1527676490; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
ResultId smallint
Description nvarchar (100)

Workflows_Status Table

Table ID: 1559676604; Created: November 16, 2021, 18:20:32; Modified: November 16, 2021, 18:21:24
Name Type NULL Comment
StatusId smallint
Description nvarchar (100)

zVersion_AspNetFaculties Table

Table ID: 593437188; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
FacultyId nvarchar (128)
Name nvarchar (256)
Descrip nvarchar (500)
OriginId int

zVersion_AspNetProfiles Table

Table ID: 609437245; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ProfileName nvarchar (100)
Descrip nvarchar (100)
CultureId nvarchar (8)
WebInterfaceName nvarchar (100)
MobileInterfaceName nvarchar (100)
StartupPageName nvarchar (100)
MailAccountId nvarchar (100)
OriginId int

zVersion_AspNetRoles Table

Table ID: 625437302; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Id nvarchar (128)
Name nvarchar (256)
IsDesigner bit
IsAdmin bit
Hidden bit
OriginId int

zVersion_AspNetUsers Table

Table ID: 641437359; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Id nvarchar (128)
RoleId nvarchar (128)
ProfileName nvarchar (100)
Email nvarchar (256)
EmailConfirmed bit
PasswordHash nvarchar (max)
SecurityStamp nvarchar (max)
PhoneNumber nvarchar (50)
PhoneNumberConfirmed bit
TwoFactorEnabled bit
LockoutEndDateUtc datetime
LockoutEnabled bit
AccessFailedCount int
UserName nvarchar (256)
IPGroup nvarchar (50)
Reference nvarchar (50)
SubReference nvarchar (50)
Avatar nvarchar (max)
Name nvarchar (100)
SurName nvarchar (100)
NickName nvarchar (100)
CultureId nvarchar (8)
MailAccountId nvarchar (100)
OriginId int

zVersion_AspNetUsers_Faculties Table

Table ID: 657437416; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
UserId nvarchar (128)
FacultyId nvarchar (128)
OriginId int

zVersion_AspNetUsers_Settings Table

Table ID: 673437473; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
UserId nvarchar (128)
SkinId int
MobileSkinId varchar (50)
DefaultPageSize int
DefaultDropDownRows int
MailAccount nvarchar (50)
MailUser nvarchar (100)
MailVisibleName nvarchar (100)
POP3Host nvarchar (100)
SMTPHost nvarchar (100)
MaillPassowrd varchar (50)
DeleteMailsOnServer bit
SMTPPort int
POPPort int
UseSSL bit
MailSignature nvarchar (1000)
OriginId int

zVersion_AspNetUsers_TokenTypes Table

Table ID: 689437530; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
TokenType nvarchar (64)
Descrip nvarchar (max)
IconName nvarchar (100)
OriginId int

zVersion_Blacklist Table

Table ID: 705437587; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Id nvarchar (100)
Method nvarchar (255)
Param nvarchar (255)
ExcludeList nvarchar (max)
ExcludeRegex nvarchar (max)
OriginId int

zVersion_Charts_Animations Table

Table ID: 721437644; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Animation nvarchar (100)
OriginId int

zVersion_Charts_Settings Table

Table ID: 737437701; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ChartSettingName nvarchar (100)
Descrip nvarchar (255)
ShowLabels bit
Colors nvarchar (500)
BorderColors nvarchar (500)
ShowLegend bit
LegendPos nvarchar (20)
ToolTipBackgroundColor nvarchar (10)
ShowTitle bit
TitleFontStyle nvarchar (150)
TitleFontSize int
TitlePosition nvarchar (20)
TitleFontColor nvarchar (20)
Responsive bit
MinXAxes int
MinYAxes int
AnimationDuration int
AnimationStyle nvarchar (100)
OriginId int

zVersion_Chatters_Config Table

Table ID: 753437758; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ObjectName nvarchar (50)
ObjectPK nvarchar (50)
OriginId int

zVersion_Chatters_Groups Table

Table ID: 769437815; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ChatterGroupId uniqueidentifier
Name nvarchar (50)
OriginId int

zVersion_Chatters_Groups_Users Table

Table ID: 785437872; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ChatterGroupId uniqueidentifier
UserId nvarchar (128)
OriginId int

zVersion_ContextVars Table

Table ID: 801437929; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
VarName nvarchar (50)
VarSQL nvarchar (max)
Order int
ConnStringId nvarchar (100)
OriginId int

zVersion_Countries Table

Table ID: 817437986; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
IsoCode nvarchar (2)
Iso3 nvarchar (3)
Name nvarchar (50)
IsoName nvarchar (50)
Flag nvarchar (1009)
Active bit
OriginId int

zVersion_Cultures Table

Table ID: 833438043; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
CultureId nvarchar (8)
CountryISO nvarchar (2)
Name nvarchar (100)
Flag nvarchar (100)
Active bit
OriginId int

zVersion_DbConnectionStrings Table

Table ID: 849438100; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ConnStringId nvarchar (50)
Descrip nvarchar (100)
UpdateDataModel bit
DacpacName nvarchar (150)
Active bit
Reserved bit
OriginId int

zVersion_DbConnectionStrings_LinkedServers Table

Table ID: 865438157; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ConnStringId nvarchar (50)
ChildConnStringId nvarchar (50)
ServerName nvarchar (100)
OriginId int

zVersion_Documents_Category Table

Table ID: 881438214; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
CategoryId nvarchar (50)
Category nvarchar (255)
OriginId int

zVersion_Documents_Objects_Config Table

Table ID: 897438271; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ObjectName nvarchar (50)
ObjectPK nvarchar (50)
ERPObjectName nvarchar (250)
TypeId nvarchar (50)
Path nvarchar (500)
DefaultCategoryId nvarchar (50)
CategoryFilter nvarchar (max)
DropboxFolderCreate bit
DropboxFolderLink bit
DropboxFileCreate bit
DropboxFileLink bit
DriveFolderCreate bit
DriveFolderLink bit
DriveFileCreate bit
DriveFileLink bit
DiskFolderCreate bit
DiskFolderLink bit
DiskFileCreate bit
DiskFileLink bit
ExtensionId nvarchar (100)
OfflineFilter nvarchar (max)
OriginId int

zVersion_Documents_Objects_Config_Types Table

Table ID: 913438328; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (250)
Active bit
OriginId int

zVersion_Events_Actions Table

Table ID: 929438385; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
EventAction nvarchar (50)
Description nvarchar (255)
OriginId int

zVersion_Events_Classes Table

Table ID: 945438442; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
EventClass nvarchar (50)
Description nvarchar (255)
OriginId int

zVersion_Events_Classes_Types Table

Table ID: 961438499; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
EventClass nvarchar (50)
EventType nvarchar (50)
Description nvarchar (255)
OriginId int

zVersion_Events_Types Table

Table ID: 977438556; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
EventType nvarchar (50)
Description nvarchar (255)
OriginId int

zVersion_Exceptions Table

Table ID: 993438613; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Id nvarchar (100)
Msg nvarchar (900)
OriginId int

zVersion_Export_Formats Table

Table ID: 1009438670; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Format nvarchar (50)
Description nvarchar (100)
IconName nvarchar (100)
MaxNumber int
Active bit
Order int
OriginId int

zVersion_Extensions Table

Table ID: 1025438727; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
ExtensionId nvarchar (100)
Descrip nvarchar (500)
Extensions nvarchar (500)
OriginId int

zVersion_Follow_Objects_Child_Config Table

Table ID: 1041438784; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Object nvarchar (50)
ChildObject nvarchar (50)
OriginId int

zVersion_Follow_Objects_Config Table

Table ID: 1057438841; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Object nvarchar (50)
Disable bit
OriginId int

zVersion_GreyList Table

Table ID: 1073438898; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Id nvarchar (100)
Method nvarchar (255)
Param nvarchar (255)
ExcludeList nvarchar (max)
ExcludeRegex nvarchar (max)
OriginId int

zVersion_Help Table

Table ID: 1089438955; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
HelpId nvarchar (50)
Title nvarchar (150)
HTMLText nvarchar (max)
TargetId nvarchar (50)
IconName nvarchar (100)
ExternalUrl nvarchar (255)
Order int
Category nvarchar (50)
Tag nvarchar (200)
OriginId int

zVersion_Help_Categories Table

Table ID: 1105439012; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
Category nvarchar (50)
Descrip nvarchar (250)
IconName nvarchar (100)
OriginId int

zVersion_Help_SamplesJS Table

Table ID: 1121439069; Created: November 16, 2021, 18:21:26
Name Type NULL Comment
HelpJSId nvarchar (50)
Title nvarchar (150)
HTMLCode nvarchar (max)
JSCode nvarchar (max)
CSSCode nvarchar (max)
OriginId int

zVersion_Icons Table

Table ID: 1137439126; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
IconName nvarchar (100)
Classification nvarchar (50)
CSSClass nvarchar (100)
ImagePath nvarchar (255)
Category nvarchar (100)
OriginId int

zVersion_Interfaces Table

Table ID: 1153439183; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
InterfaceName nvarchar (100)
TypeId int
Descrip nvarchar (100)
IsDefault bit
Logo nvarchar (255)
SkinId nvarchar (50)
Script nvarchar (max)
Style nvarchar (1000)
MainNavigateId uniqueidentifier
NavigateId uniqueidentifier
StartupPageName nvarchar (250)
DefaultPageSize int
DefaultDropDownRows int
OriginId int

zVersion_Interfaces_Types_JS Table

Table ID: 1169439240; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
InterfaceTypeId uniqueidentifier
TypeId int
FilePath nvarchar (255)
Description nvarchar (255)
Order int
OriginId int

zVersion_Jobs Table

Table ID: 1185439297; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
JobName nvarchar (50)
JobGroup nvarchar (50)
Enabled bit
Descrip nvarchar (250)
FirstExecutionDate datetime
LastExecutionDate datetime
TriggerExpression nvarchar (50)
ExecuteInmediatlyAfterMisfire bit
ObjectName nvarchar (50)
ObjectWhere nvarchar (max)
UserName nvarchar (256)
ProcessName nvarchar (255)
Params nvarchar (max)
OriginId int

zVersion_Jobs_Triggers Table

Table ID: 1201439354; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
TriggerExpression nvarchar (50)
Descrip nvarchar (250)
OriginId int

zVersion_Kanban_Boards Table

Table ID: 1217439411; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
BoardName nvarchar (50)
BoardGroup nvarchar (50)
Title nvarchar (100)
Descrip nvarchar (250)
OwnerId nvarchar (128)
BoardTypeName nvarchar (50)
ObjectName nvarchar (50)
ObjectKey nvarchar (500)
OriginId int

zVersion_Kanban_Boards_Columns Table

Table ID: 1233439468; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
BoardName nvarchar (50)
ColumnName nvarchar (50)
Descrip nvarchar (50)
CssClass nvarchar (50)
IconId nvarchar (100)
Order int
Hidden bit
OriginId int

zVersion_Kanban_Boards_Types Table

Table ID: 1249439525; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
BoardTypeName nvarchar (50)
Descrip nvarchar (250)
OriginId int

zVersion_Kanban_Boards_Types_Columns Table

Table ID: 1265439582; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
BoardTypeName nvarchar (50)
ColumnName nvarchar (50)
Descrip nvarchar (50)
CssClass nvarchar (50)
IconId nvarchar (100)
Order int
Hidden bit
OriginId int

zVersion_Kanban_Cards Table

Table ID: 1281439639; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
CardId nvarchar (100)
BoardName nvarchar (50)
ColumnName nvarchar (50)
Descrip nvarchar (max)
OwnerId nvarchar (128)
OriginId int

zVersion_Kanban_Settings Table

Table ID: 1297439696; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
KanbanSettingsName nvarchar (50)
BoardTitleTemplate nvarchar (max)
BoardDescripTemplate nvarchar (max)
BoardObjectName nvarchar (50)
ColumnViewName nvarchar (255)
ColumnDescripField nvarchar (100)
ColumnIdField nvarchar (100)
ColumnCssClassField nvarchar (100)
ColumnIconIdField nvarchar (100)
CardObjectName nvarchar (50)
CardViewName nvarchar (255)
CardIdField nvarchar (100)
CardColumnIdField nvarchar (100)
CardDescripField nvarchar (100)
CardContentTemplate nvarchar (max)
onChangeColumnProcess nvarchar (255)
onCardClick nvarchar (50)
EndBoxLastState nvarchar (100)
EndBoxProcess nvarchar (255)
EndBoxText nvarchar (255)
EndBoxIconName nvarchar (100)
EndBoxCssClass nvarchar (100)
OriginId int

zVersion_Layouts Table

Table ID: 1313439753; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
LayoutName nvarchar (100)
IconName nvarchar (100)
LayoutDescrip nvarchar (255)
LayoutTemplate nvarchar (max)
ImagePath nvarchar (255)
Offline bit
OriginId int

zVersion_MailChimp_Settings Table

Table ID: 1329439810; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
SettingName nvarchar (255)
Descrip nvarchar (255)
Value nvarchar (255)
OriginId int

zVersion_Mails_Folders Table

Table ID: 1345439867; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
FolderId nvarchar (50)
Descrip nvarchar (500)
IconName nvarchar (100)
Generic bit
IsInbox bit
IsSent bit
IsOutbox bit
CanSelect bit
Parent nvarchar (50)
OriginId int

zVersion_Mails_Folders_Accounts Table

Table ID: 1361439924; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
MailAccountId nvarchar (100)
FolderId nvarchar (50)
Sync bit
SyncError nvarchar (max)
OriginId int

zVersion_Mails_Objects_Config Table

Table ID: 1377439981; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
ObjectName nvarchar (50)
KeyProperty nvarchar (150)
EmailField nvarchar (1000)
DomainFilter bit
Path nvarchar (500)
OriginId int

zVersion_Mails_Templates Table

Table ID: 1393440038; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
Name nvarchar (100)
Body nvarchar (max)
Subject nvarchar (500)
OriginId int

zVersion_Master_Tables Table

Table ID: 1409440095; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
TableName nvarchar (250)
Descrip nvarchar (255)
GroupName nvarchar (100)
CollectionName nvarchar (50)
IconName nvarchar (100)
Order int
ConnStringId nvarchar (50)
OriginId int

zVersion_Master_Tables_Groups Table

Table ID: 1425440152; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
GroupName nvarchar (100)
Descrip nvarchar (200)
IconName nvarchar (100)
Order int
OriginId int

zVersion_Master_Tables_Properties Table

Table ID: 1441440209; Created: November 16, 2021, 18:21:27
Name Type NULL Comment
TableName nvarchar (250)
FieldName nvarchar (100)
SqlSentence nvarchar (max)
ConnStringId nvarchar (50)
OriginId int

zVersion_Menus Table

Table ID: 1457440266; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
MenuId nvarchar (50)
Descrip nvarchar (50)
ParentId nvarchar (50)
IconName nvarchar (100)
OriginId int

zVersion_Modules Table

Table ID: 1473440323; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ModuleName nvarchar (100)
TypeId nvarchar (50)
ClassId nvarchar (50)
ObjectName nvarchar (50)
ObjectFilter nvarchar (1000)
Descrip nvarchar (250)
Title nvarchar (250)
ContainerId nvarchar (50)
CollapsibleButton bit
FullscreenButton bit
RefreshButton bit
SearchButton bit
SQlSentence nvarchar (max)
Header nvarchar (max)
HTMLText nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
CssText nvarchar (max)
ScriptText nvarchar (max)
ChartTypeId nvarchar (50)
ChartSettingName nvarchar (100)
Series nvarchar (500)
Labels nvarchar (500)
Value nvarchar (500)
Params nvarchar (255)
JsonOptions nvarchar (500)
Path nvarchar (255)
TransFormFilePath nvarchar (255)
IconName nvarchar (100)
PagerId nvarchar (50)
PageSize int
ConnStringID nvarchar (50)
ToolbarName nvarchar (50)
GridbarName nvarchar (50)
TemplateId nvarchar (50)
HeaderClass nvarchar (50)
ModuleClass nvarchar (50)
JSAfterLoad nvarchar (500)
Searcher bit
ShowWhenNew bit
ManualInit bit
SchedulerName nvarchar (20)
TimelineSettingName nvarchar (50)
KanbanSettingsName nvarchar (50)
ChartBackground nvarchar (255)
ChartBorder nvarchar (255)
Reserved bit
Cache int
Offline bit
PresetName nvarchar (50)
MixedChartTypes nvarchar (255)
MixedChartLabels nvarchar (255)
ChartLineBorderDash bit
ChartLineFill bit
OriginId int

zVersion_Modules_ChartsGauges_Types Table

Table ID: 1489440380; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ChartTypeId nvarchar (50)
Descrip nvarchar (100)
ImageUrl nvarchar (255)
OriginId int

zVersion_Modules_Classification Table

Table ID: 1505440437; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ClassId nvarchar (50)
Descrip nvarchar (255)
IconName nvarchar (100)
OriginId int

zVersion_Modules_Containers Table

Table ID: 1521440494; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ContainerId nvarchar (50)
Descrip nvarchar (255)
TemplateHtml varchar (max)
CssClass nvarchar (50)
OriginId int

zVersion_Modules_Events Table

Table ID: 1537440551; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ModuleEventId nvarchar (50)
ModuleName nvarchar (100)
EventClass nvarchar (50)
EventType nvarchar (50)
EventAction nvarchar (50)
ProcessName nvarchar (255)
ObjectFilter nvarchar (50)
PropertyFilter nvarchar (50)
ProcessFilter nvarchar (255)
ModuleFilter nvarchar (100)
PageFilter nvarchar (100)
MethodFilter nvarchar (255)
OriginId int

zVersion_Modules_Pager_Types Table

Table ID: 1553440608; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
PagerId nvarchar (50)
Descrip nvarchar (100)
NumButtons int
Template nvarchar (1000)
Position nvarchar (50)
OriginId int

zVersion_Modules_Types Table

Table ID: 1569440665; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (255)
IconName nvarchar (100)
SettingsTable nvarchar (255)
WebComponent nvarchar (50)
UseCollection bit
Reserved bit
OriginId int

zVersion_Navigation_Nodes Table

Table ID: 1585440722; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
NodeId uniqueidentifier
ParentNodeId uniqueidentifier
Order int
Title nvarchar (255)
IconName nvarchar (100)
Descrip nvarchar (100)
TypeId nvarchar (50)
Params nvarchar (255)
Url nvarchar (255)
TargetId nvarchar (50)
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ReportName nvarchar (100)
HelpId nvarchar (50)
ReportWhere nvarchar (1000)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
Defaults varchar (2000)
SQLSentence nvarchar (max)
SQLConStringId nvarchar (50)
WebComponent nvarchar (1000)
TableName nvarchar (250)
BadgeClass nvarchar (100)
BadgeSQL nvarchar (max)
BadgeConStringId nvarchar (50)
BadgeRefresh int
Enabled bit
cssClass nvarchar (250)
OriginId int

zVersion_Navigation_Nodes_Types Table

Table ID: 1601440779; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100)
OriginId int

zVersion_News Table

Table ID: 1617440836; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
NewsId uniqueidentifier
Title nvarchar (255)
TypeId nvarchar (100)
ImagePath nvarchar (255)
Descrip nvarchar (max)
UrlLink nvarchar (255)
PublicationDate smalldatetime
EndDate smalldatetime
UserId nvarchar (128)
PublicArticle bit
Publish bit
Alert bit
OriginId int

zVersion_News_Types Table

Table ID: 1633440893; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
NewsTypeId nvarchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
OriginId int

zVersion_Notices Table

Table ID: 1649440950; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
NoticeId nvarchar (100)
Title nvarchar (500)
Message nvarchar (1000)
AfterClickEvent nvarchar (max)
ReminderTime smalldatetime
ExpiryTime smalldatetime
MethodName nvarchar (15)
CausesSync bit
AllUsers bit
AllUsersIsSent bit
Error bit
ErrorMsg varchar (max)
CSSClass nvarchar (125)
InsertDate datetime
OriginId int
TypeId nvarchar (50)
Params nvarchar (255)
Url nvarchar (255)
TargetId nvarchar (50)
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ReportName nvarchar (100)
HelpId nvarchar (50)
ReportWhere nvarchar (1000)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
SQLSentence nvarchar (max)
SQLConStringId nvarchar (50)
WebComponent nvarchar (1000)
TableName nvarchar (250)

zVersion_Notices_Sentences Table

Table ID: 1665441007; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
SentenceId nvarchar (100)
Decrip nvarchar (250)
MailSentence nvarchar (max)
NoticeSentence nvarchar (max)
NoticeAllUsers bit
NoticeUsersSentence nvarchar (max)
UpdateNoticeSentence nvarchar (max)
UpdateMailSentence nvarchar (max)
ConnStringId nvarchar (50)
JobName nvarchar (50)
OriginId int

zVersion_Objects Table

Table ID: 1681441064; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50)
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit
DefaultPageSize int
ParsedDescrip nvarchar (255)
Auditable int
Active bit
CanInsert bit
CanUpdate bit
CanDelete bit
CanView bit
CanPrint bit
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit
UpdateTriggerEvent bit
DeleteTriggerEvent bit
HelpId nvarchar (50)
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier
Clonable bit
ViewKeys nvarchar (100)
IgnoreDBRequired bit
ConnStringID nvarchar (50)
TransactionOn bit
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit
OriginId int

zVersion_Objects_Additional_Tables Table

Table ID: 1697441121; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
TableName nvarchar (255)
KeyMap nvarchar (255)
Descrip nvarchar (255)
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
ConnStringId nvarchar (50)
Offline bit
OriginId int

zVersion_Objects_Images_Classification Table

Table ID: 1713441178; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ImageClassId nvarchar (50)
Descrip nvarchar (150)
OriginId int

zVersion_Objects_Images_Recognition_Settings Table

Table ID: 1729441235; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
KeyProperty nvarchar (150)
RootPath nvarchar (250)
Models nvarchar (250)
ExtensionId nvarchar (100)
OriginId int

zVersion_Objects_Images_Settings Table

Table ID: 1745441292; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
KeyProperty nvarchar (150)
RootPath nvarchar (250)
TypeId nvarchar (50)
ERPObjectName nvarchar (250)
DefaultCategoryId nvarchar (50)
ExtensionId nvarchar (100)
OfflineFilter nvarchar (max)
OriginId int

zVersion_Objects_Interfaces Table

Table ID: 1761441349; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
InterfaceName nvarchar (100)
OriginId int

zVersion_Objects_Objects Table

Table ID: 1777441406; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
ChildCollection nvarchar (50)
ObjectRelation nvarchar (255)
ObjectDefaults nvarchar (255)
ShowInMenu bit
ShowInAnalysis bit
OneToOneRelation bit
Order int
RemoveOnDelete bit
OriginId int

zVersion_Objects_Presets Table

Table ID: 1793441463; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
PresetName nvarchar (50)
ObjectName nvarchar (50)
Title nvarchar (250)
Filter nvarchar (max)
IconName nvarchar (100)
IconClass nvarchar (100)
TitleClass nvarchar (100)
Order int
Offline bit
Originid int

zVersion_Objects_Processes Table

Table ID: 1809441520; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
MenuId nvarchar (50)
Order int
Active bit
SQLEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (255)
EnabledProperty nvarchar (50)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
BagOnly bit
ClearSelectionBag bit
Offline bit
OriginId int

zVersion_Objects_Processes_Interfaces Table

Table ID: 1825441577; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
InterfaceName nvarchar (100)
OriginId int

zVersion_Objects_Properties Table

Table ID: 1841441634; Created: November 16, 2021, 18:21:28
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
Label varchar (250)
PositionY smallint
PositionX smallint
Width smallint
Height smallint
Hide bit
ClientReadOnly bit
FormDisplay bit
TypeId nvarchar (50)
Locked bit
CustomPropName nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLEditSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DefaultValue nvarchar (250)
PersistDefaultValue bit
IgnoreDBDefaultValue bit
DetachedFromDB bit
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50)
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50)
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (max)
Tag varchar (500)
HelpId nvarchar (50)
ConnStringId nvarchar (50)
IsRequired bit
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100)
ToolbarName nvarchar (50)
Separator nvarchar (1)
AutoIncrement bit
AutoIncrementFunction nvarchar (1000)
CascadeDependencies bit
RootPathType nvarchar (25)
PageSize int
ImageCompressionType smallint
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit
ExtensionId nvarchar (100)
Autoselect bit
OriginId int

zVersion_Objects_Properties_Dependencies Table

Table ID: 1857441691; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
DependingPropertyName nvarchar (50)
Order int
Active bit
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (255)
Offline bit
OriginId int

zVersion_Objects_Properties_Templates Table

Table ID: 1873441748; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
CustomPropName nvarchar (50)
Descrip nvarchar (100)
TypeId nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLEditSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
Label varchar (250)
Width smallint
Height smallint
DefaultValue nvarchar (250)
PersistDefaultValue bit
IgnoreDBDefaultValue bit
DetachedFromDB bit
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50)
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50)
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (max)
Tag varchar (50)
HelpId nvarchar (50)
ConnStringId nvarchar (50)
IsRequired bit
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100)
Separator nvarchar (1)
PageSize int
ImageCompressionType smallint
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit
ExtensionId nvarchar (100)
Autoselect bit
OriginId int

zVersion_Objects_Properties_Types Table

Table ID: 1889441805; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (255)
WebComponent nvarchar (50)
OfflineWebComponent nvarchar (50)
DefaultSize int
IconName nvarchar (100)
OriginId int
SearchTypes nvarchar (500)
DefaultSearchType nvarchar (50)
ShowInObjects bit
ShowInProcesses bit
ShowInReports bit

zVersion_Objects_Reports Table

Table ID: 1905441862; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
ReportName nvarchar (100)
ObjectName nvarchar (50)
SQLEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (255)
EnabledProperty nvarchar (50)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
Active bit
OriginId int

zVersion_Objects_Search Table

Table ID: 1921441919; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
SearchId uniqueidentifier
ObjectName nvarchar (50)
Name nvarchar (100)
Generic bit
IsDefault bit
Type nvarchar (20)
Order int
UserId nvarchar (128)
SQLSentence nvarchar (max)
OriginId int

zVersion_Objects_Search_Properties Table

Table ID: 1937441976; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
SearchId uniqueidentifier
ObjectName nvarchar (50)
PropertyName nvarchar (50)
ObjectPath nvarchar (500)
Size int
Order int
Label nvarchar (250)
PropertySearchType nvarchar (20)
OriginId int

zVersion_Objects_Search_Properties_Types Table

Table ID: 1953442033; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
PropertySearchType nvarchar (20)
Descrip nvarchar (255)
WebComponent nvarchar (50)
DefaultSize int
IconName nvarchar (100)
OriginId int

zVersion_Objects_Templates Table

Table ID: 1969442090; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
TemplateId nvarchar (50)
ObjectName nvarchar (50)
TypeId nvarchar (50)
Descrip nvarchar (500)
Body nvarchar (max)
ViewName nvarchar (255)
WhereSentence nvarchar (1000)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
ModuleClass nvarchar (100)
IsDefault bit
Offline bit
UserDefinedGroups bit
Active bit
OriginId int

zVersion_Objects_Templates_Groups Table

Table ID: 1985442147; Created: November 16, 2021, 18:21:29
Name Type NULL Comment
TemplateId nvarchar (50)
GroupField nvarchar (50)
Order int
OrderType nvarchar (4)
Header nvarchar (max)
Footer nvarchar (max)
Offline bit
Label varchar (250)
UserDefault bit
OriginId int

zVersion_Objects_Templates_Samples Table

Table ID: 2001442204; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
SampleId nvarchar (150)
TypeId nvarchar (50)
Descrip nvarchar (500)
Body nvarchar (max)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
Img nvarchar (250)
Offline bit
OriginId int

zVersion_Objects_Templates_Types Table

Table ID: 2017442261; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
Body nvarchar (max)
Header varchar (max)
Footer varchar (max)
IconName nvarchar (100)
OriginId int

zVersion_Objects_Views Table

Table ID: 2033442318; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ObjectName nvarchar (50)
ViewName nvarchar (255)
Descrip nvarchar (255)
ConnStringId nvarchar (50)
SQLSentence nvarchar (max)
NoFilter bit
ShowAsGrid bit
Active bit
System bit
IsDefault bit
OrderBy nvarchar (max)
Offline bit
PrimaryKeys nvarchar (max)
IndexFields nvarchar (max)
OriginId int

zVersion_Objects_Views_Properties Table

Table ID: 2049442375; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ObjectName nvarchar (50)
ViewName nvarchar (255)
ObjectPropertyName nvarchar (50)
PropertyName nvarchar (50)
ObjectPath nvarchar (500)
Order int
Label nvarchar (250)
OriginId int

zVersion_Objects_Workflows_Areas Table

Table ID: 2065442432; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ObjectName nvarchar (50)
WorkflowAreaId nvarchar (50)
OriginId int

zVersion_Offline_Apps Table

Table ID: 2081442489; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
Title nvarchar (50)
Descrip nvarchar (max)
IconName nvarchar (100)
APKUrl nvarchar (600)
APKWebService nvarchar (600)
SyncDataProcessName nvarchar (255)
Active bit
OriginId int

zVersion_Offline_Files Table

Table ID: 2097442546; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
FileName nvarchar (150)
AppName nvarchar (50)
FilePath nvarchar (500)
FileDate smalldatetime
Enabled bit
OriginID int

zVersion_Offline_Menus Table

Table ID: 2113442603; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
MenuId uniqueidentifier
AppName nvarchar (50)
ParentMenuId uniqueidentifier
Order int
Title nvarchar (255)
IconName nvarchar (100)
Descrip nvarchar (255)
TypeId nvarchar (50)
Url nvarchar (255)
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
Enabled bit
cssClass nvarchar (255)
OriginID int

zVersion_Offline_Menus_Types Table

Table ID: 2129442660; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100)
OriginId int

zVersion_Offline_Objects Table

Table ID: 2145442717; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
ObjectName nvarchar (50)
BufferSize int
UpdateRelatedPrimaryKeys bit
SyncImmediately bit
SendData bit
GetData bit
TableName nvarchar (255)
OriginId int

zVersion_Offline_Pages Table

Table ID: 13959126; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
PageName nvarchar (50)
ObjectName nvarchar (50)
TypeId nvarchar (50)
Title nvarchar (150)
Body nvarchar (max)
Header nvarchar (max)
Footer nvarchar (max)
Empty nvarchar (max)
SQLSentence nvarchar (max)
SQLAdditionalWhere nvarchar (max)
SQLOrderBy nvarchar (max)
SQLSearchFilter nvarchar (max)
IsDefault bit
ShowSearchBar bit
JSAfterLoad nvarchar (500)
OriginId int

zVersion_Offline_Pages_Groups Table

Table ID: 29959183; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
PageName nvarchar (50)
GroupField nvarchar (50)
Order int
OrderType nvarchar (4)
Header nvarchar (max)
Footer nvarchar (max)
OriginId int

zVersion_Offline_Scripts Table

Table ID: 45959240; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
Name nvarchar (50)
JSScript nvarchar (max)
Enabled bit
Order int
LastChange datetime
OriginId int

zVersion_Offline_Styles Table

Table ID: 61959297; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
AppName nvarchar (50)
Name nvarchar (50)
CSSCode nvarchar (max)
Enabled bit
Order int
LastChange datetime
OriginId int

zVersion_Pages Table

Table ID: 77959354; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
PageName nvarchar (100)
TypeId nvarchar (50)
ObjectName nvarchar (50)
InterfaceName nvarchar (100)
LayoutName nvarchar (100)
Name nvarchar (255)
IconName nvarchar (100)
Descrip nvarchar (100)
UrlRewrite nvarchar (255)
Script nvarchar (max)
ScriptActive bit
Style nvarchar (1000)
RefreshInterval int
Sytem bit
Generic bit
BodyCssClass nvarchar (200)
Offline bit
OriginId int

zVersion_Pages_Modules Table

Table ID: 93959411; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
PageName nvarchar (100)
ModuleName nvarchar (100)
LayoutPositionId nvarchar (50)
RelationWhere nvarchar (1000)
Order int
SQlEnabled nvarchar (max)
SQLEnabledDescrip nvarchar (250)
Title nvarchar (250)
IconName nvarchar (100)
HeaderClass nvarchar (50)
ModuleClass nvarchar (50)
ConnStringID nvarchar (50)
OriginId int

zVersion_Pages_Modules_Tabs Table

Table ID: 109959468; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
TabModuleName nvarchar (100)
ModuleName nvarchar (100)
Order int
OriginId int

zVersion_Pages_Types Table

Table ID: 125959525; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
TypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100)
OriginId int

zVersion_Plugins Table

Table ID: 141959582; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
PluginId uniqueidentifier
Path nvarchar (500)
Descrip nvarchar (100)
Order int
typeId int
Bundle bit
Enabled bit
OriginId int

zVersion_Processes Table

Table ID: 157959639; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ProcessName nvarchar (255)
TypeId int
ClassId nvarchar (50)
ConfirmText varchar (200)
ProcessDescrip nvarchar (500)
ParamsDescrip nvarchar (500)
ReturnDescrip nvarchar (500)
JSforParams varchar (500)
File varchar (255)
Class varchar (255)
Method varchar (50)
StoredName varchar (255)
Code varchar (max)
ExternalUrl varchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ReportName nvarchar (100)
HelpId uniqueidentifier
ReportWhere nvarchar (1000)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
Defaults varchar (2000)
TimeOut int
ConnStringId nvarchar (255)
TargetId nvarchar (50)
ProcessFlowText nvarchar (500)
Auditable bit
Refresh bit
IsTransacted bit
AdminOnly bit
ConfirmOkText bit
CloseDialogOnOk bit
RunButtonText nvarchar (100)
LoadProcessName nvarchar (255)
GipeParams bit
Summary nvarchar (max)
ReturnTableNames nvarchar (max)
Reserved bit
Offline bit
OriginId int

zVersion_Processes_Classification Table

Table ID: 173959696; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ClassId nvarchar (50)
Descrip nvarchar (255)
OriginId int

zVersion_Processes_Objects Table

Table ID: 189959753; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ProcessName nvarchar (255)
ObjectName nvarchar (50)
Offline bit
OriginId int

zVersion_Processes_Params Table

Table ID: 205959810; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ProcessName nvarchar (255)
ParamName nvarchar (50)
Hide bit
ParamTypeId nvarchar (50)
TableName nvarchar (250)
ObjectName nvarchar (50)
DefaultValue nvarchar (250)
Label varchar (250)
IOTypeId nvarchar (5)
PositionX smallint
PositionY smallint
Width smallint
Height smallint
TypeId nvarchar (50)
Locked bit
CustomPropName nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DetachedFromProcess bit
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50)
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50)
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (500)
Tag varchar (500)
HelpId nvarchar (50)
ConnStringId nvarchar (50)
IsRequired bit
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100)
ToolbarName nvarchar (50)
Separator nvarchar (1)
CascadeDependencies bit
RootPathType nvarchar (25)
ImageCompressionType smallint
ImageMaxWidth smallint
ImageMaxHeight smallint
Offline bit
ExtensionId nvarchar (100)
Autoselect bit
OriginId int

zVersion_Processes_Params_Dependencies Table

Table ID: 221959867; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ProcessName nvarchar (255)
ParamName nvarchar (50)
DependingParamName nvarchar (50)
Order int
Active bit
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (50)
Offline bit
OriginId int

zVersion_Processes_Params_Types Table

Table ID: 237959924; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
ParamTypeId nvarchar (50)
Descrip nvarchar (100)
IconName nvarchar (100)
OriginId int

zVersion_Processes_Processes Table

Table ID: 253959981; Created: November 16, 2021, 18:21:30
Name Type NULL Comment
Guid uniqueidentifier
WorkflowName nvarchar (255)
ParentProcessName nvarchar (255)
ParentObjectName nvarchar (50)
ParentEventName nvarchar (50)
ProcessName nvarchar (255)
Order int
ExecuteCondition nvarchar (max)
ContinueAfterFail bit
OriginId int

zVersion_Processes_Processes_Params Table

Table ID: 269960038; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
Guid uniqueidentifier
InputProcessName nvarchar (255)
InputParamName nvarchar (50)
OutputProcessName nvarchar (255)
OutputParamName nvarchar (50)
OriginId int

zVersion_Processes_Workflows_Areas Table

Table ID: 285960095; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ProcessName nvarchar (255)
WorkflowAreaId nvarchar (50)
OriginId int

zVersion_RegEx Table

Table ID: 301960152; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
RegExId nvarchar (100)
RegEx nvarchar (500)
Descrip nvarchar (255)
ValidItems nvarchar (500)
UnvalidItems nvarchar (500)
OriginId int

zVersion_Reports Table

Table ID: 317960209; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
ReportDescrip nvarchar (255)
TypeId nvarchar (20)
ReportPath nvarchar (255)
AdditionalWhere nvarchar (1000)
NoFilter bit
Order int
IconName nvarchar (100)
PDF bit
Word bit
Excel bit
ParamsTargetId nvarchar (50)
LoadProcessName nvarchar (255)
ReportMode nvarchar (10)
FilterSentence nvarchar (500)
RoleSentence nvarchar (500)
ObjectName nvarchar (50)
TemplateId nvarchar (50)
FilterReportReplacingSentence bit
OriginId int

zVersion_Reports_Params Table

Table ID: 333960266; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
ParamName nvarchar (50)
Label varchar (250)
PositionX smallint
PositionY smallint
Width smallint
Height smallint
Hide bit
TypeId nvarchar (50)
Locked bit
CustomPropName nvarchar (50)
Mask nvarchar (250)
SQlSentence nvarchar (max)
SQLFilter nvarchar (1000)
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLObjectName nvarchar (50)
SQLViewName nvarchar (255)
SQLOfflineSentence nvarchar (max)
SQLOfflineOrderBy nvarchar (max)
WhereSentence nvarchar (1000)
DefaultValue nvarchar (250)
DetachedFromProcess bit
SearchFunction nvarchar (250)
SearchCollection nvarchar (50)
SearchWhere nvarchar (500)
SearchReturnFields nvarchar (250)
SecurityObject nvarchar (50)
AllowNew nvarchar (50)
AllowNewFunction nvarchar (250)
AllowNewReturnFields nvarchar (250)
AllowNewDefaults nvarchar (500)
ObjNameLink nvarchar (50)
ObjWhereLink nvarchar (1000)
TargetIdLink nvarchar (50)
Style nvarchar (100)
CSSClass nvarchar (100)
LabelStyle nvarchar (100)
LabelCSSClass nvarchar (100)
DecimalPlaces int
RootPath nvarchar (255)
FormatString nvarchar (100)
DirectTemplate nvarchar (500)
Tag varchar (50)
HelpId nvarchar (50)
ConnStringId nvarchar (50)
IsRequired bit
IsRequiredMessage nvarchar (255)
minValue nvarchar (50)
minValueMessage nvarchar (255)
maxValue nvarchar (50)
maxValueMessage nvarchar (255)
RegExp nvarchar (500)
RegExpText nvarchar (50)
SQLValidator nvarchar (500)
ValidatorMessage nvarchar (255)
OnChangeJsFunction nvarchar (500)
OnChangeProcessName nvarchar (255)
PlaceHolder nvarchar (100)
IconName nvarchar (100)
ToolbarName nvarchar (50)
Separator nvarchar (1)
CascadeDependencies bit
RootPathType nvarchar (25)
ImageCompressionType smallint
ImageMaxWidth smallint
ImageMaxHeight smallint
ExtensionId nvarchar (100)
Autoselect bit
OriginId int

zVersion_Reports_Params_Dependencies Table

Table ID: 349960323; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
ParamName nvarchar (50)
DependingParamName nvarchar (50)
order int
Active bit
Descrip nvarchar (255)
SQLValue nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLClass nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)
ConnStringId nvarchar (50)
OriginId int

zVersion_Reports_Types Table

Table ID: 365960380; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TypeId nvarchar (20)
Descrip varchar (50)
IconName nvarchar (100)
Active bit
OriginId int

zVersion_Root_Path_Types Table

Table ID: 381960437; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TypeId nvarchar (25)
Description nvarchar (50)
Active bit
OriginId int

zVersion_Scheduler Table

Table ID: 397960494; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
SchedulerName nvarchar (20)
ActiveMode nvarchar (20)
MonthView bit
AgendaWeekView bit
AgendaDayView bit
ListWeekView bit
SQLValueField nvarchar (100)
SQLDisplayField nvarchar (500)
SQLFilterField nvarchar (500)
DirectTemplate nvarchar (500)
ObjectName nvarchar (50)
ViewName nvarchar (255)
MinTime nvarchar (5)
MaxTime nvarchar (5)
OnClickEvent bit
AllDaySlot bit
SlotDuration nvarchar (5)
TokenDefault nvarchar (100)
EventPageTypeId nvarchar (50)
EventTargetId nvarchar (50)
HolidaysObjectName nvarchar (255)
HolidaysViewName nvarchar (255)
DateHolidayField nvarchar (255)
EventLimit bit
OriginId int

zVersion_Scheduler_Objects Table

Table ID: 413960551; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
SchedulerName nvarchar (20)
ObjectName nvarchar (50)
ViewName nvarchar (255)
StartDateField nvarchar (50)
EndDateField nvarchar (50)
StartTimeField nvarchar (50)
EndTimeField nvarchar (50)
DurationField nvarchar (50)
ColorField nvarchar (50)
DescripTemplate nvarchar (max)
UserIdField nvarchar (255)
TextColorField nvarchar (50)
AllDayField nvarchar (50)
OriginId int

zVersion_Scheduler_Views Table

Table ID: 429960608; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ViewId nvarchar (20)
Descrip nvarchar (50)
OriginId int

zVersion_Scripts_Jobs Table

Table ID: 445960665; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ScriptId nvarchar (100)
Descrip nvarchar (250)
Notes nvarchar (max)
CreationDate smalldatetime
State nvarchar (50)
Script nvarchar (max)
ConnStringId nvarchar (50)
ExecuteOrder smallint
StartDate smalldatetime
EndDate smalldatetime
ErrorMessage nvarchar (max)
OriginId int

zVersion_Scripts_Jobs_States Table

Table ID: 461960722; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
State nvarchar (50)
Descrip nvarchar (50)
OriginId int

zVersion_Security_Master_Tables_Roles Table

Table ID: 477960779; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TableName nvarchar (250)
RoleId nvarchar (128)
CanView bit
CanUpdate bit
CanDelete bit
CanInsert bit
CanPrint bit
OriginId int

zVersion_Security_Master_Tables_Users Table

Table ID: 493960836; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TableName nvarchar (250)
UserId nvarchar (128)
CanView bit
CanUpdate bit
CanDelete bit
CanInsert bit
CanPrint bit
OriginId int

zVersion_Security_Modules_Faculties Table

Table ID: 509960893; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ModuleName nvarchar (100)
FacultyId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Modules_Roles Table

Table ID: 525960950; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ModuleName nvarchar (100)
RoleId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Modules_Users Table

Table ID: 541961007; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ModuleName nvarchar (100)
UserId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Navigation_Nodes_Faculties Table

Table ID: 557961064; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
NodeId uniqueidentifier
FacultyId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Navigation_Nodes_Roles Table

Table ID: 573961121; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
NodeId uniqueidentifier
RoleId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Navigation_Nodes_Users Table

Table ID: 589961178; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
NodeId uniqueidentifier
UserId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Objects_Faculties Table

Table ID: 605961235; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
FacultyId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
OriginId int

zVersion_Security_Objects_Processes_Faculties Table

Table ID: 621961292; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
FacultyId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Objects_Processes_Roles Table

Table ID: 637961349; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
RoleId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Objects_Processes_Users Table

Table ID: 653961406; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
UserId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
OriginId int

zVersion_Security_Objects_Properties_Faculties Table

Table ID: 669961463; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
FacultyId nvarchar (128)
CanView bit
CanEdit bit
OriginId int

zVersion_Security_Objects_Properties_Roles Table

Table ID: 685961520; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
RoleId nvarchar (128)
CanView bit
CanEdit bit
OriginId int

zVersion_Security_Objects_Properties_Users Table

Table ID: 701961577; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
UserId nvarchar (128)
CanView bit
CanEdit bit
OriginId int

zVersion_Security_Objects_Roles Table

Table ID: 717961634; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
RoleId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
OriginId int

zVersion_Security_Objects_Templates_Faculties Table

Table ID: 733961691; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TemplateId nvarchar (50)
FacultyId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Objects_Templates_Roles Table

Table ID: 749961748; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TemplateId nvarchar (50)
RoleId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Objects_Templates_Users Table

Table ID: 765961805; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
TemplateId nvarchar (50)
UserId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Objects_Users Table

Table ID: 781961862; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ObjectName nvarchar (50)
UserId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
OriginId int

zVersion_Security_Offline_Menus_Faculties Table

Table ID: 797961919; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
MenuId uniqueidentifier
FacultyId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Offline_Menus_Roles Table

Table ID: 813961976; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
MenuId uniqueidentifier
RoleId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Offline_Menus_Users Table

Table ID: 829962033; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
MenuId uniqueidentifier
UserId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Pages_Faculties Table

Table ID: 845962090; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
FacultyId nvarchar (128)
Canview bit
OriginId int

zVersion_Security_Pages_Modules_Faculties Table

Table ID: 861962147; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
ModuleName nvarchar (100)
FacultyId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Pages_Modules_Roles Table

Table ID: 877962204; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
ModuleName nvarchar (100)
RoleId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Pages_Modules_Users Table

Table ID: 893962261; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
ModuleName nvarchar (100)
UserId nvarchar (128)
CanView bit
OriginId int

zVersion_Security_Pages_Roles Table

Table ID: 909962318; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
RoleId nvarchar (128)
Canview bit
OriginId int

zVersion_Security_Pages_Users Table

Table ID: 925962375; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
PageName nvarchar (100)
UserId nvarchar (128)
Canview bit
OriginId int

zVersion_Security_Reports_Faculties Table

Table ID: 941962432; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
FacultyId nvarchar (128)
CanPrint bit
OriginId int

zVersion_Security_Reports_Roles Table

Table ID: 957962489; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
RoleId nvarchar (128)
CanPrint bit
OriginId int

zVersion_Security_Reports_Users Table

Table ID: 973962546; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
ReportName nvarchar (100)
UserId nvarchar (128)
CanPrint bit
OriginId int

zVersion_Settings Table

Table ID: 989962603; Created: November 16, 2021, 18:21:31
Name Type NULL Comment
SettingName nvarchar (150)
SettingValue nvarchar (max)
IconName nvarchar (100)
Description nvarchar (1000)
SettingCustomProperty nvarchar (50)
Active bit
GroupName nvarchar (20)
OriginId int

zVersion_Settings_groups Table

Table ID: 1005962660; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
GroupName nvarchar (20)
Descrip nvarchar (250)
IconName nvarchar (100)
OriginId int

zVersion_Settings_Values Table

Table ID: 1021962717; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
SettingName nvarchar (150)
SettingValue nvarchar (1000)
OriginId int

zVersion_Skins Table

Table ID: 1037962774; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
SkinId nvarchar (50)
Descrip nvarchar (100)
Css nvarchar (max)
Script nvarchar (max)
OriginId int

zVersion_Skins_Css Table

Table ID: 1053962831; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
CssId nvarchar (150)
SkinId nvarchar (50)
CssPath nvarchar (500)
Descrip nvarchar (100)
InBundle bit
Order int
OriginId int
Enabled bit

zVersion_Skins_Variables Table

Table ID: 1069962888; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
SkinId nvarchar (50)
VarName nvarchar (50)
Descrip nvarchar (50)
VarValue nvarchar (100)
VarType nvarchar (50)
VarGroup nvarchar (50)
VarOrder int
OriginId int

zVersion_Targets Table

Table ID: 1085962945; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
TargetId nvarchar (50)
Descrip nvarchar (100)
OriginId int

zVersion_Tests Table

Table ID: 1101963002; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
TestId nvarchar (100)
Title nvarchar (100)
Path nvarchar (500)
ExcludeCategories nvarchar (500)
OriginId int

zVersion_Timelines_Settings Table

Table ID: 1117963059; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
TimelineSettingName nvarchar (50)
TimelineSettingDescrip nvarchar (100)
ObjectName nvarchar (50)
Advanced bit
Editable bit
WithGroups bit
ShowItemsWithoutGroup bit
TitleItemsWithoutGroup nvarchar (25)
LayoutName nvarchar (25)
DefaultRangeName nvarchar (25)
ShowControls bit
OnInsertOpenNewWithDefaults bit
PropertyDescrip nvarchar (50)
PropertyStartDate nvarchar (50)
PropertyEndDate nvarchar (50)
PropertyGroup nvarchar (50)
GroupViewName nvarchar (255)
GroupIdField nvarchar (100)
GroupDescripField nvarchar (100)
GroupClassNameField nvarchar (100)
GroupStyleField nvarchar (100)
GroupContentTemplate nvarchar (max)
ItemViewName nvarchar (255)
ItemDescripField nvarchar (100)
ItemStartDateField nvarchar (100)
ItemEndDateField nvarchar (100)
ItemGroupField nvarchar (100)
ItemEditableField nvarchar (100)
ItemClassNameField nvarchar (100)
ItemStyleField nvarchar (100)
ItemTypeField nvarchar (100)
ItemContentTemplate nvarchar (max)
ItemVisibleFrameTemplate nvarchar (max)
OnMovingFunction nvarchar (max)
OnDropObjectOnItemFunction nvarchar (max)
OnDeleteFunction nvarchar (max)
CustomOptions nvarchar (max)
DefaultTime int
EventPageTypeId nvarchar (50)
OriginId int

zVersion_ToolBars Table

Table ID: 1133963116; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ToolbarName nvarchar (50)
Descrip nvarchar (150)
OriginId int

zVersion_ToolBars_Buttons Table

Table ID: 1149963173; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ButtonId nvarchar (100)
ToolbarName nvarchar (50)
ParentButtonId nvarchar (100)
Order int
TypeId nvarchar (50)
PositionId nvarchar (50)
Text nvarchar (150)
Tooltip nvarchar (150)
IconName nvarchar (100)
HideText bit
CssClass nvarchar (255)
SQlSentence nvarchar (max)
ProcessName nvarchar (255)
TargetId varchar (50)
ReportName nvarchar (100)
HelpId nvarchar (50)
Disabled bit
OriginId int

zVersion_Translate Table

Table ID: 1165963230; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
CultureId nvarchar (8)
Original nvarchar (255)
Text nvarchar (255)
Area nvarchar (100)
OriginId int

zVersion_Translate_Areas Table

Table ID: 1181963287; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
Area nvarchar (100)
OriginId int

zVersion_Videos Table

Table ID: 1197963344; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
VideoName nvarchar (100)
Title nvarchar (250)
Descrip nvarchar (max)
Url nvarchar (250)
Classification nvarchar (50)
Category nvarchar (50)
Image nvarchar (250)
Author nvarchar (100)
Duration int
Order int
IsNew bit
OriginId int

zVersion_Videos_Categories Table

Table ID: 1213963401; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
Category nvarchar (50)
Descrip nvarchar (250)
IconName nvarchar (100)
OriginId int

zVersion_Videos_Classification Table

Table ID: 1229963458; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
Classification nvarchar (50)
Title nvarchar (250)
Descrip nvarchar (max)
IconName nvarchar (100)
OriginId int

zVersion_WebAPI_Objects Table

Table ID: 1245963515; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ObjectName nvarchar (50)
CanView bit
CanViewCollection bit
CanInsert bit
CanEdit bit
CanDelete bit
CanPrint bit
OriginId int

zVersion_WebAPI_Processes Table

Table ID: 1261963572; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ProcessName nvarchar (255)
CanView bit
OriginId int

zVersion_WebAPI_Roles Table

Table ID: 1277963629; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
RoleId nvarchar (128)
isAuthorized bit
OriginId int

zVersion_WebAPI_Users Table

Table ID: 1293963686; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
UserId nvarchar (128)
isAuthorized bit
OriginId int

zVersion_WebAPI_Views Table

Table ID: 1309963743; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ObjectName nvarchar (50)
ViewName nvarchar (255)
CanView bit
OriginId int

zVersion_WebHooks Table

Table ID: 1325963800; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
WebHookID nvarchar (255)
Origin nvarchar (255)
ProcessName nvarchar (255)
RequiresAuthorization bit
OriginId int

zVersion_Workflows Table

Table ID: 1341963857; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
WorkflowId nvarchar (255)
Version smallint
ModuleId nvarchar (50)
AreaId nvarchar (50)
Descrip nvarchar (255)
WorkflowData nvarchar (max)
Active bit
OriginId int

zVersion_Workflows_Areas Table

Table ID: 1357963914; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
WorkflowAreaId nvarchar (50)
Descrip nvarchar (500)
ParentAreaId nvarchar (50)
Observations nvarchar (4000)
IconName nvarchar (100)
AreaData nvarchar (max)
OriginId int

zVersion_Workflows_Modules Table

Table ID: 1373963971; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
WorkflowModuleId nvarchar (50)
Descrip nvarchar (500)
OriginId int

zVersion_Workflows_Nodes Table

Table ID: 1389964028; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
NodeId uniqueidentifier
WorkflowName nvarchar (255)
Version smallint
NodeType smallint
GraphId int
ProcessName nvarchar (255)
ObjectName nvarchar (50)
EventName nvarchar (50)
ExecuteCondition nvarchar (max)
ContinueAfterFail bit
InitialNode bit
NodeLabel nvarchar (1000)
OriginId int

zVersion_Workflows_Relations Table

Table ID: 1405964085; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
RelationId uniqueidentifier
WorkflowName nvarchar (255)
Version smallint
GraphId int
ParentGuid uniqueidentifier
ChildGuid uniqueidentifier
ParentValue nvarchar (255)
ExecuteCondition nvarchar (max)
OriginId int

zVersion_Workflows_Relations_Parameters Table

Table ID: 1421964142; Created: November 16, 2021, 18:21:32
Name Type NULL Comment
ParameterRelationId uniqueidentifier
RelationId uniqueidentifier
ChildParamName nvarchar (50)
ParentType nvarchar (50)
ParentNode nvarchar (255)
ParentParamName nvarchar (50)
DefaultValue nvarchar (1000)
OriginId int

vActive_Cultures View

Table ID: 872390177; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
CultureId nvarchar (8)
CountryISO nvarchar (2)
Name nvarchar (100)
Flag nvarchar (100)
Active bit
OriginId int

vNet_AllModules_FacultySecurity View

Table ID: 888390234; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ModuleName nvarchar (100)
Descrip nvarchar (250)
Title nvarchar (250)
ObjectName nvarchar (50)
TypeId nvarchar (50)
ModuleType nvarchar (255)
TypeIconClass nvarchar (100)
FacultyName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllModules_RoleSecurity View

Table ID: 904390291; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ModuleName nvarchar (100)
Descrip nvarchar (250)
Title nvarchar (250)
ObjectName nvarchar (50)
TypeId nvarchar (50)
ModuleType nvarchar (255)
TypeIconClass nvarchar (100)
Rolename nvarchar (256)
Id nvarchar (128)
CanView bit
NotRegistered int

vNet_AllModules_UserSecurity View

Table ID: 920390348; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ModuleName nvarchar (100)
Descrip nvarchar (250)
Title nvarchar (250)
ObjectName nvarchar (50)
TypeId nvarchar (50)
ModuleType nvarchar (255)
TypeIconClass nvarchar (100)
UserName nvarchar (100)
Id nvarchar (128)
CanView bit

vNet_AllNodes_FacultySecurity View

Table ID: 936390405; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
NodeId uniqueidentifier
Descrip nvarchar (100)
Title nvarchar (255)
TypeId nvarchar (50)
NodeType nvarchar (100)
TypeIconClass nvarchar (100)
FacultyName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllNodes_RoleSecurity View

Table ID: 952390462; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
NodeId uniqueidentifier
Descrip nvarchar (100)
Title nvarchar (255)
TypeId nvarchar (50)
NodeType nvarchar (100)
TypeIconClass nvarchar (100)
RoleName nvarchar (256)
Id nvarchar (128)
CanView bit
NotRegistered int

vNet_AllNodes_UserSecurity View

Table ID: 968390519; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
NodeId uniqueidentifier
Descrip nvarchar (100)
Title nvarchar (255)
TypeId nvarchar (50)
NodeType nvarchar (100)
TypeIconClass nvarchar (100)
UserName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllObjects_FacultySecurity View

Table ID: 984390576; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
Id nvarchar (128)
FacultyName nvarchar (256)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
IconClass nvarchar (100)

vNet_AllObjects_Properties_Dependencies View

Table ID: 1000390633; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
DependingPropertyName nvarchar (50)
Order int
Active bit
descrip nvarchar (255)
ConnStringId nvarchar (255)
HasValueDep int
HasClassDep int
HasCustomPropertyDep int
HasComboDep int
HasEnabledDep int
HasVisibleDep int
HasRequiredDep int
HasConnStringId int
SQLValue nvarchar (max)
SQLClass nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)

vNet_AllObjects_RoleSecurity View

Table ID: 1016390690; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
Id nvarchar (128)
RoleName nvarchar (256)
RoleId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
NotRegistered int
IconClass nvarchar (100)

vNet_AllObjects_UserSecurity View

Table ID: 1032390747; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
Id nvarchar (128)
Username nvarchar (256)
CanView bit
ViewFilter nvarchar (2048)
CanViewCollection bit
ViewFilterCollection nvarchar (2048)
CanInsert bit
InsertFilter nvarchar (2048)
CanEdit bit
EditFilter nvarchar (2048)
CanDelete bit
DeleteFilter nvarchar (2048)
CanPrint bit
IconClass nvarchar (100)

vNet_AllObjectsProcess_FacultySecurity View

Table ID: 1048390804; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
Id nvarchar (128)
fAcultyName nvarchar (256)
FacultyId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
ProcessType nvarchar (100)
ProcessTypeIconClass nvarchar (100)

vNet_AllObjectsProcess_RoleSecurity View

Table ID: 1064390861; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
Id nvarchar (128)
RoleName nvarchar (256)
RoleId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
NotRegistered int
ProcessType nvarchar (100)
ProcessTypeIconClass nvarchar (100)

vNet_AllObjectsProcess_UserSecurity View

Table ID: 1080390918; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
Id nvarchar (128)
UserName nvarchar (256)
UserId nvarchar (128)
CanView bit
ViewFilter nvarchar (2048)
ProcessType nvarchar (100)
ProcessTypeIconClass nvarchar (100)

vNet_AllObjectsProperties_FacultySecurity View

Table ID: 1096390975; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
Id nvarchar (128)
FacultyName nvarchar (256)
FacultyId nvarchar (128)
CanView bit
CanEdit bit
IconClass nvarchar (100)

vNet_AllObjectsProperties_RoleSecurity View

Table ID: 1112391032; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
Id nvarchar (128)
RoleName nvarchar (256)
RoleId nvarchar (128)
CanView bit
CanEdit bit
NotRegistered int
IconClass nvarchar (100)

vNet_AllObjectsProperties_UserSecurity View

Table ID: 1128391089; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
Id nvarchar (128)
UserName nvarchar (256)
CanView bit
CanEdit bit
IconClass nvarchar (100)

vNet_AllPages_FacultySecurity View

Table ID: 1144391146; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
PageName nvarchar (100)
Descrip nvarchar (100)
Name nvarchar (255)
TypeId nvarchar (50)
PageType nvarchar (100)
TypeIconClass nvarchar (100)
FacultyName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllPages_RoleSecurity View

Table ID: 1160391203; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
PageName nvarchar (100)
Descrip nvarchar (100)
Name nvarchar (255)
TypeId nvarchar (50)
PageType nvarchar (100)
TypeIconClass nvarchar (100)
RoleName nvarchar (256)
Id nvarchar (128)
CanView bit
NotRegistered int

vNet_AllPages_UserSecurity View

Table ID: 1176391260; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
PageName nvarchar (100)
Descrip nvarchar (100)
Name nvarchar (255)
TypeId nvarchar (50)
PageType nvarchar (100)
TypeIconClass nvarchar (100)
UserName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllProcess_Properties_Dependencies View

Table ID: 1192391317; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ProcessName nvarchar (255)
PropertyName nvarchar (50)
DependingPropertyName nvarchar (50)
Order int
Active bit
descrip nvarchar (255)
ConnStringId nvarchar (50)
HasValueDep int
HasClassDep int
HasCustomPropertyDep int
HasComboDep int
HasEnabledDep int
HasVisibleDep int
HasRequiredDep int
HasConnStringId int
SQLValue nvarchar (max)
SQLClass nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)

vNet_AllReport_Properties_Dependencies View

Table ID: 1208391374; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ReportName nvarchar (100)
PropertyName nvarchar (50)
DependingPropertyName nvarchar (50)
Order int
Active bit
descrip nvarchar (255)
ConnStringId nvarchar (50)
HasValueDep int
HasClassDep int
HasCustomPropertyDep int
HasComboDep int
HasEnabledDep int
HasVisibleDep int
HasRequiredDep int
HasConnStringId int
SQLValue nvarchar (max)
SQLClass nvarchar (max)
SQLComboSentence nvarchar (max)
SQLComboFilter nvarchar (max)
SQLEnabled nvarchar (max)
EnabledValues nvarchar (max)
DisabledValues nvarchar (max)
SQLVisible nvarchar (max)
VisibleValues nvarchar (max)
HiddenValues nvarchar (max)
SQLRequired nvarchar (max)
RequiredValues nvarchar (max)
NotRequiredValues nvarchar (max)
PropertyValue nvarchar (max)
CusPropName nvarchar (max)
SQLCustomProperty nvarchar (max)

vNet_AllReports_FacultySecurity View

Table ID: 1224391431; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ReportName nvarchar (100)
ReportDescrip nvarchar (255)
TypeId nvarchar (20)
ReportType varchar (50)
ReportMode nvarchar (10)
ReportTypeIconClass nvarchar (100)
IconClass nvarchar (100)
FacultyName nvarchar (256)
Id nvarchar (128)
CanPrint bit

vNet_AllReports_RoleSecurity View

Table ID: 1240391488; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ReportName nvarchar (100)
ReportDescrip nvarchar (255)
TypeId nvarchar (20)
ReportType varchar (50)
ReportMode nvarchar (10)
ReportTypeIconClass nvarchar (100)
IconClass nvarchar (100)
RoleName nvarchar (256)
Id nvarchar (128)
CanPrint bit
NotRegistered int

vNet_AllReports_UserSecurity View

Table ID: 1256391545; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ReportName nvarchar (100)
ReportDescrip nvarchar (255)
TypeId nvarchar (20)
ReportType varchar (50)
ReportMode nvarchar (10)
ReportTypeIconClass nvarchar (100)
IconClass nvarchar (100)
UserName nvarchar (256)
Id nvarchar (128)
CanPrint bit

vNet_AllRestrictedModuleSecurity View

Table ID: 1272391602; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ModuleName nvarchar (100)
RoleId varchar (13)
CanView int
ViewFilter varchar (30)
OriginId int

vNet_AllRestrictedNodeSecurity View

Table ID: 1288391659; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
NodeId uniqueidentifier
RoleId varchar (13)
CanView int
OriginId int

vNet_AllRestrictedObjectProcessSecurity View

Table ID: 1304391716; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
ProcessName nvarchar (255)
RoleId varchar (13)
CanView int
ViewFilter varchar (30)
OriginId int

vNet_AllRestrictedObjectPropertySecurity View

Table ID: 1320391773; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
PropertyName nvarchar (50)
RoleId varchar (13)
CanView int
CanEdit int
OriginId int

vNet_AllRestrictedObjectSecurity View

Table ID: 1336391830; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
ObjectName nvarchar (50)
RoleId varchar (13)
CanView int
ViewFilter varchar (30)
CanViewCollection int
ViewFilterCollection varchar (30)
CanInsert int
InsertFilter varchar (30)
CanEdit int
EditFilter varchar (30)
CanDelete int
DeleteFilter varchar (30)
CanPrint int
OriginId int

vNet_AllRestrictedPagesSecurity View

Table ID: 1352391887; Created: November 16, 2021, 18:20:35
Name Type NULL Comment
PageName nvarchar (100)
RoleId varchar (13)
CanView int
OriginId int

vNet_AllRestrictedReportsSecurity View

Table ID: 1368391944; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ReportName nvarchar (100)
RoleId varchar (13)
CanView int
OriginId int

vNet_AllRestrictedTemplatesSecurity View

Table ID: 1384392001; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
TemplateId nvarchar (50)
RoleId varchar (13)
CanView int
OriginId int

vNet_AllTemplates_FacultySecurity View

Table ID: 1400392058; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
TemplateId nvarchar (50)
Descrip nvarchar (500)
TypeId nvarchar (50)
IconClass nvarchar (100)
ObjectName nvarchar (50)
FacultyName nvarchar (256)
Id nvarchar (128)
CanView bit

vNet_AllTemplates_RoleSecurity View

Table ID: 1416392115; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
TemplateId nvarchar (50)
Descrip nvarchar (500)
TypeId nvarchar (50)
IconClass nvarchar (100)
ObjectName nvarchar (50)
RoleName nvarchar (256)
Id nvarchar (128)
CanView bit
NotRegistered int

vNet_AllTemplates_UserSecurity View

Table ID: 1432392172; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
TemplateId nvarchar (50)
Descrip nvarchar (500)
TypeId nvarchar (50)
IconClass nvarchar (100)
UserName nvarchar (256)
Id nvarchar (128)
CanView bit
ObjectName nvarchar (50)

vNet_Collections View

Table ID: 1448392229; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50)
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit
DefaultPageSize int
ParsedDescrip nvarchar (255)
Auditable int
Active bit
CanInsert bit
CanUpdate bit
CanDelete bit
CanView bit
CanPrint bit
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit
UpdateTriggerEvent bit
DeleteTriggerEvent bit
HelpId nvarchar (50)
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier
Clonable bit
ViewKeys nvarchar (100)
IgnoreDBRequired bit
ConnStringID nvarchar (50)
TransactionOn bit
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit
OriginId int

vNet_Documents_Combo View

Table ID: 1464392286; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
DocGuid uniqueidentifier
Name nvarchar (100)
CreationDate smalldatetime
Category nvarchar (255)
CSSClass nvarchar (100)
Descrip nvarchar (255)
DocumentTypeName nvarchar (50)

vNet_Events_Classes_Types View

Table ID: 1480392343; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
EventClass nvarchar (50)
EventType nvarchar (50)
ClassDescription nvarchar (255)
TypeDescription nvarchar (255)

vNet_Mails_Objects_Config View

Table ID: 1496392400; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ObjectName nvarchar (50)
KeyProperty nvarchar (150)
EmailField nvarchar (1000)
DomainFilter bit
Path nvarchar (500)
OriginId int
Descrip nvarchar (255)
IconClass nvarchar (100)

vNet_Nodes_Objects View

Table ID: 1512392457; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
NodeId uniqueidentifier
ParentNodeId uniqueidentifier
Order int
Title nvarchar (255)
IconName nvarchar (100)
Descrip nvarchar (100)
TypeId nvarchar (50)
Params nvarchar (255)
Url nvarchar (255)
TargetId nvarchar (50)
ProcessName nvarchar (255)
PageTypeId nvarchar (50)
PageName nvarchar (100)
ReportName nvarchar (100)
HelpId nvarchar (50)
ReportWhere nvarchar (1000)
ObjectName nvarchar (50)
ObjectWhere nvarchar (1000)
Defaults varchar (2000)
SQLSentence nvarchar (max)
SQLConStringId nvarchar (50)
WebComponent nvarchar (1000)
TableName nvarchar (250)
BadgeClass nvarchar (100)
BadgeSQL nvarchar (max)
BadgeConStringId nvarchar (50)
BadgeRefresh int
Enabled bit
cssClass nvarchar (250)
OriginId int

vNet_Notices_Badge View

Table ID: 1528392514; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
UserName nvarchar (256)
NotRead int

vNet_Objects View

Table ID: 1544392571; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50)
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit
DefaultPageSize int
ParsedDescrip nvarchar (255)
Auditable int
Active bit
CanInsert bit
CanUpdate bit
CanDelete bit
CanView bit
CanPrint bit
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit
UpdateTriggerEvent bit
DeleteTriggerEvent bit
HelpId nvarchar (50)
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier
Clonable bit
ViewKeys nvarchar (100)
IgnoreDBRequired bit
ConnStringID nvarchar (50)
TransactionOn bit
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit
OriginId int

vNet_ObjectsExtendend View

Table ID: 1560392628; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50)
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit
DefaultPageSize int
ParsedDescrip nvarchar (255)
Auditable int
Active bit
CanInsert bit
CanUpdate bit
CanDelete bit
CanView bit
CanPrint bit
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit
UpdateTriggerEvent bit
DeleteTriggerEvent bit
HelpId nvarchar (50)
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier
Clonable bit
ViewKeys nvarchar (100)
IgnoreDBRequired bit
ConnStringID nvarchar (50)
TransactionOn bit
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit
OriginId int
IconClass nvarchar (100)
InsertTypeDescrip nvarchar (50)
UpdateTypeDescrip nvarchar (50)
DeleteTypeDescrip nvarchar (50)
ConnectionString nvarchar (100)

vNet_ObjectsExtendendWithObjectWhere View

Table ID: 1576392685; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
Descrip nvarchar (255)
ObjectName nvarchar (50)
IconClass nvarchar (100)
Active int
ConfigDB int
Iscollection int
Offline int

vNet_OfflineApps View

Table ID: 1592392742; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
AppName nvarchar (50)
Title nvarchar (50)
Descrip nvarchar (max)
IconName nvarchar (100)
APKUrl nvarchar (600)
APKWebService nvarchar (600)
SyncDataProcessName nvarchar (255)
Active bit
OriginId int
IconClass nvarchar (100)

vNet_OfflineObjects View

Table ID: 1608392799; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
AppName nvarchar (50)
ObjectName nvarchar (50)
Iscollection bit
ObjectChildName nvarchar (50)
TableName nvarchar (255)
WhereSentence nvarchar (1000)
ConfigDB bit
OrderBy varchar (100)
Descrip nvarchar (255)
IconName nvarchar (100)
UniqueIdentifierField nvarchar (50)
ShowDefaultMenu bit
DefaultPageSize int
ParsedDescrip nvarchar (255)
Auditable int
Active bit
CanInsert bit
CanUpdate bit
CanDelete bit
CanView bit
CanPrint bit
InsertType nvarchar (10)
UpdateType nvarchar (10)
DeleteType nvarchar (10)
InsertProcessName nvarchar (255)
UpdateProcessName nvarchar (255)
DeleteProcessName nvarchar (255)
LoadProcessName nvarchar (255)
InsertTriggerEvent bit
UpdateTriggerEvent bit
DeleteTriggerEvent bit
HelpId nvarchar (50)
OverrideObjectName nvarchar (50)
OverrideObjectWhere nvarchar (1000)
NavigateNodeId uniqueidentifier
Clonable bit
ViewKeys nvarchar (100)
IgnoreDBRequired bit
ConnStringID nvarchar (50)
TransactionOn bit
InsertFlowText nvarchar (500)
UpdateFlowText nvarchar (500)
DeleteFlowText nvarchar (500)
Offline bit
BeforeUpdate nvarchar (255)
BeforeInsert nvarchar (255)
BeforeDelete nvarchar (255)
AfterUpdate nvarchar (255)
AfterInsert nvarchar (255)
AfterDelete nvarchar (255)
Reserved bit
OriginId int
CSSClass nvarchar (100)

vNet_Related_Object_Chatter View

Table ID: 1624392856; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
MessageId uniqueidentifier
Avatar nvarchar (max)
Author nvarchar (201)
UserOwner nvarchar (128)
InsertionDate datetime
Content nvarchar (max)
DestinationObjectName nvarchar (50)
DestinationObjectId nvarchar (250)
DestinationParentMessage uniqueidentifier
LoginOwner nvarchar (128)
AttachmentsCount int

vNetAdditionalTables View

Table ID: 1640392913; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
tablename nvarchar (255)
objectname nvarchar (50)

vPages_Modules_Tabs View

Table ID: 1656392970; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
PageName nvarchar (100)
ModuleName nvarchar (100)
TabModuleName nvarchar (100)
Order int

VWorkflows_Executions View

Table ID: 1672393027; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
ExecutionId bigint
ParentExecutionId bigint
MasterExecutionId bigint
WorkflowId nvarchar (255)
WorkflowVersion smallint
Start datetime
Finish datetime
ResultId smallint
StatusId smallint
ErrorMessage nvarchar (max)
WarningMessage nvarchar (max)
ExecutionData nvarchar (max)
UserId nvarchar (128)
WorkflowDescription nvarchar (255)
ResultDescription nvarchar (100)
StatusDescription nvarchar (100)
InitialGraphId int

VWorkflows_Executions_Nodes View

Table ID: 1688393084; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
Id bigint
ExecutionId bigint
NodeId nvarchar (50)
ThreadId int
Start datetime
ProcessTime time
Finish datetime
ResultId smallint
StatusId smallint
ErrorMessage nvarchar (max)
WarningMessage nvarchar (max)
ExecutionData nvarchar (max)
ParentExecutionId bigint
MasterExecutionId bigint
GraphId int
WorkflowDescription nvarchar (255)
ResultDescription nvarchar (100)
StatusDescription nvarchar (100)
NodeName nvarchar (255)

VWorkflows_Nodes_Templates View

Table ID: 1704393141; Created: November 16, 2021, 18:20:36
Name Type NULL Comment
NodeType int
NodeIcon varchar (24)
NodeKey nvarchar (255)
NodeDescrip nvarchar (768)
NodeOriginId int
NodeAreas nvarchar (50)

aDemo Stored


CREATE PROCEDURE [dbo].[aDemo]
AS
BEGIN


declare @Objetos int
select @Objetos=count(*) from objects

--Lauch javascript with an alert
SELECT concat('alert(''It works!! ',@Objetos,' objects on the database'')') as Javascript, concat(@Objetos,' objects on the database') as SuccessMessage

return 1

END

GetCustomProperty Stored

CREATE PROCEDURE [dbo].[GetCustomProperty](
@CustomPropertyName nvarchar(50)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- GetCustomProperty
--#CREATION
-- 01/08/2019 - Rommel Llumiquinga
-- Last Modified 20/08/2019 By Rommel Llumiquinga
--#CLASIFICATION
-- Flexygo/Sytem
--#DESCRIPTION
-- Get Custom Property Settings
--#PARAMETERS
-- @CustomPropertyName: Custom property name
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY

BEGIN TRAN

SELECT
Objects_Properties_Templates.[CustomPropName]
,Objects_Properties_Templates.[Descrip]
,Objects_Properties_Templates.[TypeId]
,Objects_Properties_Templates.[SQlSentence]
,Objects_Properties_Templates.[SQLEditSentence]
,Objects_Properties_Templates.[SQLFilter]
,Objects_Properties_Templates.[SQLValueField]
,Objects_Properties_Templates.[SQLDisplayField]
,Objects_Properties_Templates.[WhereSentence]
,Objects_Properties_Templates.[Label]
,Objects_Properties_Templates.[Width]
,Objects_Properties_Templates.[Height]
,Objects_Properties_Templates.[DefaultValue]
,Objects_Properties_Templates.[PersistDefaultValue]
,Objects_Properties_Templates.[IgnoreDBDefaultValue]
,Objects_Properties_Templates.[DetachedFromDB]
,Objects_Properties_Templates.[SearchFunction]
,Objects_Properties_Templates.[SearchCollection]
,Objects_Properties_Templates.[SearchWhere]
,Objects_Properties_Templates.[SearchReturnFields]
,Objects_Properties_Templates.[SecurityObject]
,Objects_Properties_Templates.[AllowNew]
,Objects_Properties_Templates.[AllowNewFunction]
,Objects_Properties_Templates.[AllowNewReturnFields]
,Objects_Properties_Templates.[AllowNewDefaults]
,Objects_Properties_Templates.[ObjNameLink]
,Objects_Properties_Templates.[ObjWhereLink]
,Objects_Properties_Templates.[TargetIdLink]
,Objects_Properties_Templates.[Style]
,Objects_Properties_Templates.[CSSClass]
,Objects_Properties_Templates.[LabelStyle]
,Objects_Properties_Templates.[LabelCSSClass]
,Objects_Properties_Templates.[DecimalPlaces]
,Objects_Properties_Templates.[RootPath]
,Objects_Properties_Templates.[FormatString]
,Objects_Properties_Templates.[DirectTemplate]
,Objects_Properties_Templates.[Tag]
,Objects_Properties_Templates.[HelpId]
,Objects_Properties_Templates.[IsRequired]
,Objects_Properties_Templates.[IsRequiredMessage]
,Objects_Properties_Templates.[minValue]
,Objects_Properties_Templates.[minValueMessage]
,Objects_Properties_Templates.[maxValue]
,Objects_Properties_Templates.[maxValueMessage]
,Objects_Properties_Templates.[RegExp]
,Objects_Properties_Templates.[RegExpText]
,Objects_Properties_Templates.[OnChangeJsFunction]
,Objects_Properties_Templates.[OnChangeProcessName]
,Objects_Properties_Templates.[PlaceHolder]
,i.[CSSClass] AS IconClass
,Objects_Properties_Templates.[Separator]
,Objects_Properties_Templates.[PageSize]
,Objects_Properties_Templates.[ConnStringId]
,Objects_Properties_Templates.[OriginId]
,OPT.WebComponent,OPT.OfflineWebComponent
FROM Objects_Properties_Templates
LEFT JOIN Objects_Properties_Types OPT ON OPT.TypeId=Objects_Properties_Templates.TypeId
LEFT JOIN Icons I ON I.IconName=Objects_Properties_Templates.IconName
WHERE CustomPropName=@CustomPropertyName;

COMMIT

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

Gipe_Test_AddBoth Stored

CREATE PROCEDURE [dbo].[Gipe_Test_AddBoth](
@NumberA decimal(18,2),
@NumberB decimal(18,2),
@NumberAB decimal(18,2) OUTPUT,
@ObjectName NVARCHAR(150) OUTPUT
)
AS
----------------------------------------------------------------------------------
--#NAME
-- Gipe_Test_AddBoth
--#CREATION
-- 15/11/2018 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- NumberA + NumberB
--#PARAMETERS
-- @NumberA: Number one to add
-- @NumberB: Number two to add
-- @NumberAB: NumberA + NumberB
-- @ObjectName: Object to return
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

set @NumberAB=@NumberA+@NumberB
SET @ObjectName='sysObject'

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

Gipe_Test_Divide4 Stored

CREATE PROCEDURE [dbo].[Gipe_Test_Divide4](
@NumberDivide4 decimal(18,2) output
)
AS
----------------------------------------------------------------------------------
--#NAME
-- Gipe_Test_Divide4
--#CREATION
-- 15/11/2018 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- Divide number by 4
--#PARAMETERS
-- @NumberDivide4: Number to divide
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN

set @NumberDivide4=@NumberDivide4/4

COMMIT

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

Gipe_Test_Multiply2 Stored

CREATE PROCEDURE [dbo].[Gipe_Test_Multiply2](
@X XML output
)
AS
----------------------------------------------------------------------------------
--#NAME
-- Gipe_Test_Multiply2
--#CREATION
-- 15/11/2018 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- Sample description
--#PARAMETERS
-- @NumMultiply2: Number to multiply by 2
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN
declare @NumMultiply2 decimal(18,4)

SELECT
@NumMultiply2 = N.V.value('@value', 'decimal(18,4)')
FROM
@x.nodes('/root/in/parentnode/param') AS N(V)
where
N.V.value('@name', 'nvarchar(50)') ='NumMultiply2'

SELECT @NumMultiply2 = @NumMultiply2 * 2

declare @o xml = N'<param name="NumMultiply2" value="' + cast(@NumMultiply2 as NVARCHAR(100)) + N'"/>'

SET @x.modify('insert sql:variable("@o") into (/root/out)[1]') ;

declare @r xml = N'<result state="1" />'

SET @x.modify('delete /root/result')

SET @x.modify('insert sql:variable("@r") into (/root)[1]') ;
END

P_Test_D Stored

CREATE PROCEDURE [dbo].[P_Test_D]
@TestId int ,
@Usuario nvarchar(50) ,
@FechaInsertUpdate datetime
AS

Declare @Usuario_ nvarchar(50)
Declare @FechaInsertUpdate_ datetime

BEGIN

DELETE _Test
WHERE TestId=@TestId And Usuario=@Usuario And Convert(varchar(20),FechaInsertUpdate,113)=Convert(varchar(20),@FechaInsertUpdate,113)

-- comprobar borrado
IF @@ROWCOUNT=1 BEGIN
RETURN -1

END ELSE BEGIN
SELECT @Usuario_=Usuario,
@FechaInsertUpdate_=FechaInsertUpdate
FROM _test WHERE TestId=@TestId

IF @Usuario_ IS NULL BEGIN
PRINT 'Could not delete. might have been previously deleted'
RETURN 0

END ELSE IF (@Usuario<>@Usuario_ Or Convert(varchar(20),@FechaInsertUpdate,113)<>Convert(varchar(20),@FechaInsertUpdate_,113)) BEGIN

PRINT 'Could not delete. might have been previously changed'
RETURN 0
END

-- no se ha podido borrar
PRINT 'Could not delete'
RETURN 0
end
END

P_Test_I Stored

CREATE PROCEDURE [dbo].[P_Test_I]
@TestId int OUTPUT,
@Descrip nvarchar(2000) ,
@DecimalField DECIMAL(18,14),
@IntegerField INT,
@ImageField varchar(MAX),
@FileField VARCHAR(MAX),
@BitField bit,
@DateField date,
@SmallDateTimeField SMALLDATETIME,
@DbComboField [NVARCHAR](50),
@ComboField [NVARCHAR](50),
@WhiteBoardField [NVARCHAR](MAX),
@ColorField [NVARCHAR](50) ,
@CoordinateField [NVARCHAR](100) ,
@CronField [NVARCHAR](250) ,
@CssField [NVARCHAR](1000),
@CustomField [NVARCHAR](100) ,
@EmailField [NVARCHAR](100),
@CheckMultiField [NVARCHAR](1000),
@FilePathField [NVARCHAR](250),
@HtmlCodeField [NVARCHAR](1000),
@HtmlEditField [NVARCHAR](1000),
@ImageFileField [NVARCHAR](250),
@JavaCodeField [NVARCHAR](1000),
@MultiComboField [NVARCHAR](1000),
@MultiLineField [NVARCHAR](250),
@NullCheckField [BIT],
@PasswordField [NVARCHAR](50),
@PhoneField [NVARCHAR](50),
@RadioField [NVARCHAR](50),
@SqlCodeField [NVARCHAR](1000),
@SwitchField [BIT],
@TagListField [NVARCHAR](1000),
@TimeField [NVARCHAR](50),
@UploadB64Field [NVARCHAR](MAX),
@UploadFile [NVARCHAR](250),
@UrlField [NVARCHAR](100),
@WeekField [NVARCHAR](100),
@IdentField [nvarchar](250),
@IdDoc INT OUTPUT,
@Usuario NVARCHAR(50) OUTPUT,
@FechaInsertUpdate datetime OUTPUT
AS
BEGIN


-- Next Id
IF @TestId IS NULL OR @TestId=0
SELECT @TestId=ISNULL(MAX(@TestId)+1,1) FROM _Test
-- Insert

INSERT INTO _Test(TestId ,Descrip ,DecimalField ,IntegerField ,ImageField ,FileField ,BitField ,DateField ,SmalldateTimeField ,Usuario)
VALUES (@TestId , @Descrip , @DecimalField, @IntegerField, @ImageField, @FileField, @BitField, @DateField, @SmallDateTimeField, @Usuario)

--Insert into _Test_Conf
INSERT INTO _Test_Conf (TestId )
SELECT T.TestID FROM _TEst T
LEFT JOIN _Test_Conf C ON T.TestId=C.TEstId
WHERE C.TestID IS NULL

-- Check
IF @@ROWCOUNT=1 BEGIN
SELECT @IdDoc=IdDoc,@Usuario=Usuario,@FechaInsertUpdate=FechaInsertUpdate FROM _Test WHERE TestId = @TestId
RETURN -1

END ELSE BEGIN
PRINT 'ERROR IN TEST INSERT.'
RETURN 0
END

END

P_Test_U Stored

CREATE PROCEDURE [dbo].[P_Test_U]
@TestId_A int,
@Usuario nvarchar(50) OUTPUT,
@FechaInsertUpdate datetime OUTPUT,
@TestId int OUTPUT,
@Descrip nvarchar(2000) OUTPUT,
@DecimalField DECIMAL(18,14) OUTPUT,
@IntegerField INT OUTPUT,
@ImageField varchar(MAX) OUTPUT,
@FileField varchar(MAX) OUTPUT,
@BitField BIT OUTPUT,
@DateField DATE OUTPUT,
@SmallDateField SMALLDATETIME OUTPUT,
@DbComboField [NVARCHAR](50) OUTPUT,
@ComboField [NVARCHAR](50) OUTPUT,
@WhiteBoardField [NVARCHAR](MAX) OUTPUT,
@ColorField [NVARCHAR](50) OUTPUT,
@CoordinateField [NVARCHAR](100) OUTPUT,
@CronField [NVARCHAR](250) OUTPUT,
@CssField [NVARCHAR](1000) OUTPUT,
@CustomField [NVARCHAR](100) OUTPUT,
@EmailField [NVARCHAR](100) OUTPUT,
@CheckMultiField [NVARCHAR](1000) OUTPUT,
@FilePathField [NVARCHAR](250) OUTPUT,
@HtmlCodeField [NVARCHAR](1000) OUTPUT,
@HtmlEditField [NVARCHAR](1000) OUTPUT,
@ImageFileField [NVARCHAR](250) OUTPUT,
@JavaCodeField [NVARCHAR](1000) OUTPUT,
@MultiComboField [NVARCHAR](1000) OUTPUT,
@MultiLineField [NVARCHAR](250) OUTPUT,
@NullCheckField [BIT] OUTPUT,
@PasswordField [NVARCHAR](50) OUTPUT,
@PhoneField [NVARCHAR](50) OUTPUT,
@RadioField [NVARCHAR](50) OUTPUT,
@SqlCodeField [NVARCHAR](1000) OUTPUT,
@SwitchField [BIT] OUTPUT,
@TagListField [NVARCHAR](1000) OUTPUT,
@TimeField [NVARCHAR](50) OUTPUT,
@UploadB64Field [NVARCHAR](MAX) OUTPUT,
@UploadFile [NVARCHAR](250) OUTPUT,
@UrlField [NVARCHAR](100) OUTPUT,
@WeekField [NVARCHAR](100) OUTPUT,
@IdentField [nvarchar](250) OUTPUT

AS

Declare @Usuario_ nvarchar(50)
Declare @FechaInsertUpdate_ datetime


BEGIN

UPDATE _Test SET TestId=@TestId, Descrip=@Descrip,InsertUpdate=1, Usuario=@usuario, FechaInsertUpdate=getdate(),
DecimalField=@DecimalField,IntegerField=@IntegerField,ImageField=@ImageField ,FileField=@FileField ,
BitField=@BitField,DateField=@DateField,SmalldateTimeField=@SmallDateField

WHERE TestId=@TestId_A AND Usuario=@Usuario And Convert(Varchar(20),FechaInsertUpdate,113)=Convert(Varchar(20),@FechaInsertUpdate,113)
END
------------------------------------------
-- Check if update was done
------------------------------------------
IF @@ROWCOUNT=1 BEGIN
SELECT @TestId=TestId,
@Descrip=Descrip,
@Usuario=Usuario,
@FechaInsertUpdate=FechaInsertUpdate
FROM _Test WHERE TestId=@TestId
RETURN -1

END ELSE BEGIN
SELECT @Usuario_=Usuario,
@FechaInsertUpdate_=FechaInsertUpdate
FROM _Test WHERE TestId=@TestId_A

IF @Usuario_ IS NULL BEGIN
PRINT 'Could not update. Might have bee previously deleted'
RETURN 0
END ELSE IF (@Usuario<>@Usuario_ OR Convert(Varchar(20),@FechaInsertUpdate,113)<>Convert(Varchar(20),@FechaInsertUpdate_,113)) BEGIN
PRINT 'Could not update. Might have bee previously modifyed'
RETURN 0
END
PRINT 'Could not update. Update Error'
RETURN 0

END

P_TestDelete_Stored Stored

CREATE PROCEDURE [dbo].[P_TestDelete_Stored]

@Values as XML,
@ContextVars as XML,
@RetValues as XML OUTPUT

AS
----------------------------------------------------------------------------------
--#NAME
-- P_TestDelete_Stored
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Testing object delete through Flexygo Stored procedure
--#PARAMETERS
-- @Values : Object properties ,
-- @ContextVars: Flexygo ciontext variables,
-- @RetValues : Flexygo process Helper (CloseParamWindow,JSCode,JSFile,LastException,Params,Refresh,Success,SuccesMessage,WarningMessage)
--#OBSERVATIONS
-- Values XML Sample
-- <Row rowId="d4ec88a0-3129-4c5d-b5ac-8c9d2867db64" ObjectName="systmpTest">
-- <Property Name="TestId" Value="3" OldValue="" TableName="_Test" IsKey="True" />
-- <Property Name="Descrip" Value="test3" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="IdDoc" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="InsertUpdate" Value="False" OldValue="False" TableName="_Test" IsKey="False" />
-- <Property Name="Usuario" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="FechaInsertUpdate" Value="14/02/2018 0:00:00" OldValue="14/02/2018 0:00:00" TableName="_Test" IsKey="False" />
-- <Property Name="Config" Value="config3" OldValue="" TableName="_Test_Conf" IsKey="False" />
-- </Row>
--
-- ContextVars XML Sample
-- <Row>
-- <Property Name="reference" Value="0" />
-- <Property Name="subReference" Value="0" />
-- <Property Name="currentRole" Value="Admins" />
-- <Property Name="currentRoleId" Value="admins" />
-- <Property Name="currentUserLogin" Value="admin" />
-- <Property Name="currentUserId" Value="1" />
-- <Property Name="currentUserFullName" Value="admin" />
-- <Property Name="currentUserCultureId" Value="en-gb" />
-- <Property Name="currentUserLang" Value="en" />
-- <Property Name="currentUserEmail" Value="info@ahora.es.com" />
-- </Row>
--
-- Return vars XML Sample
-- <Property Success="False" SuccessMessage="" WarningMessage="" JSCode="" JSFile="" CloseParamWindow="False" refresh="False" />
--
--#CHANGES
-- 13/02/2018- David Miralpeix
----------------------------------------------------------------------------------
BEGIN TRY

--Declare field variables to load
DECLARE @TestId int,
@Descrip nvarchar(2000),
@IdDoc int,
@InsertUpdate bit,
@Usuario nvarchar(50),
@FechaInsertUpdate datetime ,
@Config nvarchar(50)


--/* load XML values into table @TableValues*/


SET @TestId=@Values.value('(/Row/Property[@Name=''TestId'']/@Value)[1]', 'int' )
SET @Descrip=@Values.value('(/Row/Property[@Name=''Descrip'']/@Value)[1]', 'nvarchar(2000)' )
SET @Usuario=@Values.value('(/Row/Property[@Name=''Usuario'']/@Value)[1]', 'nvarchar(50)' )
SET @InsertUpdate=@Values.value('(/Row/Property[@Name=''InsertUpdate'']/@Value)[1]', 'bit' )
SET @FechaInsertUpdate=@Values.value('(/Row/Property[@Name=''FechaInsertUpdate'']/@Value)[1]', 'datetime' )
SET @Config=@Values.value('(/Row/Property[@Name=''Config'']/@Value)[1]', 'nvarchar(50)' )



/* perform process (delete fields into different tables) */
Delete from _Test where TestId=@TestId
Delete from _Test_Conf where TestId=@TestId

/* Process return values*/
SET @RetValues.modify('replace value of (/Property/@Success)[1] with 1')
SET @RetValues.modify('replace value of (/Property/@SuccessMessage)[1] with "All went fine"')

/* Return 0 if error */
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funprintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)


SET @RetValues.modify('replace value of (/Property/@Success)[1] with 0')
SET @RetValues.modify('replace va

P_TestDelete_Stored Stored

lue of (/Property/@SuccessMessage)[1] with "something went wrong"')

RETURN 0

END CATCH

P_TestInsert_Stored Stored

CREATE PROCEDURE [dbo].[P_TestInsert_Stored]

@Values as XML OUTPUT,
@ContextVars as XML,
@RetValues as XML OUTPUT

AS
----------------------------------------------------------------------------------
--#NAME
-- P_TestInsert_Stored
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Testing object insert through Flexygo Stored procedure
--#PARAMETERS
-- @Values : Object properties ,
-- @ContextVars: Flexygo ciontext variables,
-- @RetValues : Flexygo process Helper (CloseParamWindow,JSCode,JSFile,LastException,Params,Refresh,Success,SuccesMessage,WarningMessage)
--#OBSERVATIONS
-- Values XML Sample
-- <Row rowId="d4ec88a0-3129-4c5d-b5ac-8c9d2867db64" ObjectName="systmpTest">
-- <Property Name="TestId" Value="3" OldValue="" TableName="_Test" IsKey="True" />
-- <Property Name="Descrip" Value="test3" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="IdDoc" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="InsertUpdate" Value="False" OldValue="False" TableName="_Test" IsKey="False" />
-- <Property Name="Usuario" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="FechaInsertUpdate" Value="14/02/2018 0:00:00" OldValue="14/02/2018 0:00:00" TableName="_Test" IsKey="False" />
-- <Property Name="Config" Value="config3" OldValue="" TableName="_Test_Conf" IsKey="False" />
-- </Row>
--
-- ContextVars XML Sample
-- <Row>
-- <Property Name="reference" Value="0" />
-- <Property Name="subReference" Value="0" />
-- <Property Name="currentRole" Value="Admins" />
-- <Property Name="currentRoleId" Value="admins" />
-- <Property Name="currentUserLogin" Value="admin" />
-- <Property Name="currentUserId" Value="1" />
-- <Property Name="currentUserFullName" Value="admin" />
-- <Property Name="currentUserCultureId" Value="en-gb" />
-- <Property Name="currentUserLang" Value="en" />
-- <Property Name="currentUserEmail" Value="info@ahora.es.com" />
-- </Row>
--
-- Return vars XML Sample
-- <Property Success="False" SuccessMessage="" WarningMessage="" JSCode="" JSFile="" CloseParamWindow="False" refresh="False" />
--
--#CHANGES
-- 13/02/2018- David Miralpeix
----------------------------------------------------------------------------------
BEGIN TRY

--Declare field variables to load
DECLARE @TestId int,
@Descrip nvarchar(2000),
@InsertUpdate bit,
@Usuario nvarchar(50),
@FechaInsertUpdate datetime ,
@Config nvarchar(50)



SET @TestId=@Values.value('(/Row/Property[@Name=''TestId'']/@Value)[1]', 'int' )
SET @Descrip=@Values.value('(/Row/Property[@Name=''Descrip'']/@Value)[1]', 'nvarchar(2000)' )
SET @Usuario=@Values.value('(/Row/Property[@Name=''Usuario'']/@Value)[1]', 'nvarchar(50)' )

SET @InsertUpdate=@Values.value('(/Row/Property[@Name=''InsertUpdate'']/@Value)[1]', 'bit' )
SET @FechaInsertUpdate=@Values.value('(/Row/Property[@Name=''FechaInsertUpdate'']/@Value)[1]', 'datetime' )
SET @Config=@Values.value('(/Row/Property[@Name=''Config'']/@Value)[1]', 'nvarchar(50)' )



/* perform process (insert fields into different tables) */
INSERT INTO _Test (TestId,Descrip, Usuario, InsertUpdate, FechaInsertUpdate)
SELECT @TestId, @DEscrip ,isnull(@Usuario,'nouser') ,@InsertUpdate ,isnull(@FechaInsertUpdate ,getdate())

INSERT INTO _Test_conf (TestId, Config)
SELECT @TestId , @Config

/* change Keys */


/* Process return values*/
SET @RetValues.modify('replace value of (/Property/@Success)[1] with 1')
SET @RetValues.modify('replace value of (/Property/@SuccessMessage)[1] with "All went fine"')

/* Return 0 if error */
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funprintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAI

P_TestInsert_Stored Stored

SERROR(@CatchError,12,1)

SET @RetValues.modify('replace value of (/Property/@Success)[1] with 0')
SET @RetValues.modify('replace value of (/Property/@SuccessMessage)[1] with "Something went wrong"')
RETURN 0

END CATCH

P_TestUpdate_Stored Stored

CREATE PROCEDURE [dbo].[P_TestUpdate_Stored]
@Values as XML OUTPUT,
@ContextVars as XML,
@RetValues as XML OUTPUT

AS
----------------------------------------------------------------------------------
--#NAME
-- P_TestUpdate_Stored
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Testing object update through Flexygo Stored procedure
--#PARAMETERS
-- @Values : Object properties ,
-- @ContextVars: Flexygo ciontext variables,
-- @RetValues : Flexygo process Helper (CloseParamWindow,JSCode,JSFile,LastException,Params,Refresh,Success,SuccesMessage,WarningMessage)
--#OBSERVATIONS
-- Values XML Sample
--<Row rowId="d4ec88a0-3129-4c5d-b5ac-8c9d2867db64" ObjectName="systmpTest">
-- <Property Name="TestId" Value="3" OldValue="3" TableName="_Test" IsKey="True" />
-- <Property Name="Descrip" Value="test4" OldValue="test3" TableName="_Test" IsKey="False" />
-- <Property Name="IdDoc" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="InsertUpdate" Value="False" OldValue="False" TableName="_Test" IsKey="False" />
-- <Property Name="Usuario" Value="" OldValue="" TableName="_Test" IsKey="False" />
-- <Property Name="FechaInsertUpdate" Value="14/02/2018 0:00:00" OldValue="14/02/2018 0:00:00" TableName="_Test" IsKey="False" />
-- <Property Name="Config" Value="config4" OldValue="Config3" TableName="_Test_Conf" IsKey="False" />
--</Row>
--
-- ContextVars XML Sample
-- <Row>
-- <Property Name="reference" Value="0" />
-- <Property Name="subReference" Value="0" />
-- <Property Name="currentRole" Value="Admins" />
-- <Property Name="currentRoleId" Value="admins" />
-- <Property Name="currentUserLogin" Value="admin" />
-- <Property Name="currentUserId" Value="1" />
-- <Property Name="currentUserFullName" Value="admin" />
-- <Property Name="currentUserCultureId" Value="en-gb" />
-- <Property Name="currentUserLang" Value="en" />
-- <Property Name="currentUserEmail" Value="info@ahora.es.com" />
-- </Row>
--
-- Return vars XML Sample
-- <Property Success="False" SuccessMessage="" WarningMessage="" JSCode="" JSFile="" CloseParamWindow="False" refresh="False" />
--
--#CHANGES
-- 13/02/2018- David Miralpeix
----------------------------------------------------------------------------------
BEGIN TRY

--Declare field variables to load
DECLARE @TestId int,
@Descrip nvarchar(2000),
@DecimalField DECIMAL(18,14),
@IntegerField INT,
@ImageField varchar(MAX),
@FileField varchar(MAX),
@BitField bit,
@DateField date,
@SmallDateField SMALLDATETIME,
@InsertUpdate bit,
@Usuario nvarchar(50),
@FechaInsertUpdate datetime ,
@Config nvarchar(50),

@OldTestId int

SET @OldTestId=@Values.value('(/Row/Property[@Name=''TestId'']/@OldValue)[1]', 'int' )
SET @TestId=@Values.value('(/Row/Property[@Name=''TestId'']/@Value)[1]', 'int' )
SET @Descrip=@Values.value('(/Row/Property[@Name=''Descrip'']/@Value)[1]', 'nvarchar(2000)' )
SET @DecimalField=@Values.value('(/Row/Property[@Name=''DecimalField'']/@Value)[1]', 'decimal(18,14)' )
SET @IntegerField=@Values.value('(/Row/Property[@Name=''IntegerField'']/@Value)[1]', 'int' )
SET @ImageField=@Values.value('(/Row/Property[@Name=''ImageField'']/@Value)[1]', 'varchar(max)' )
SET @FileField=@Values.value('(/Row/Property[@Name=''FileField'']/@Value)[1]', 'varchar(max)' )
SET @BitField=@Values.value('(/Row/Property[@Name=''BitField'']/@Value)[1]', 'bit' )
SET @DateField=@Values.value('(/Row/Property[@Name=''DateField'']/@Value)[1]', 'date' )
SET @SmallDateField=@Values.value('(/Row/Property[@Name=''SmallDateField'']/@Value)[1]', 'smalldatetime' )
SET @Usuario=@Values.value('(/Row/Property[@Name=''Usuario'']/@Value)[1]', 'nvarchar(50)' )
SET @InsertUpdate=0
SET @FechaInsertUpdate=GETDATE()
SET @Config=@Values.value('(/Row/Property[@Name=''Config'']/@Value)[1]', '

P_TestUpdate_Stored Stored

nvarchar(50)' )



/* perform process (insert fields into different tables) */
UPDATE _Test set TestId=@TestId,Descrip=@Descrip,
DecimalField=@DecimalField,IntegerField=@IntegerField,ImageField=@ImageField,FileField=@FileField,BitField=@BitField,
DateField=@DateField,SmalldateTimeField=@SmallDateField
, Usuario=@Usuario, @InsertUpdate=0, FechaInsertUpdate=@FechaInsertUpdate where TestId=@OldTestId
UPDATE _Test_conf set TestId=@TestId,Config=@Config where TestId=@OldTestId

/* change Keys if necesary*/



/* Process return values*/
SET @RetValues.modify('replace value of (/Property/@Success)[1] with 1')
SET @RetValues.modify('replace value of (/Property/@SuccessMessage)[1] with "All went fine"')


RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funprintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

SET @RetValues.modify('replace value of (/Property/@Success)[1] with 0')
SET @RetValues.modify('replace value of (/Property/@SuccessMessage)[1] with "Something went wrong"')
RETURN 0

END CATCH

pChangeOriginId Stored

CREATE PROCEDURE [dbo].[pChangeOriginId](
@NewOriginId int
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pChangeOriginId
--#CREATION
-- 27/02/2019 - Rubén Pardo
--#CLASIFICATION
-- Flexygo/Sytem
--#DESCRIPTION
-- Set new origin Id
--#PARAMETERS
-- @NewOriginId: New Origin
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN

update origins set active=case originid when @NewOriginId then 1 else 0 end

RETURN 1

END

pNet_AddOfflineMenu Stored

CREATE PROCEDURE [dbo].[pNet_AddOfflineMenu]
@AppName VARCHAR(50)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_AddOfflineMenu]
--#CREATION
-- 08/06/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Add menu from table Offline_Menus
--#PARAMETERS
-- @AppName: The App Name
--#OBSERVATIONS
--
--#CHANGES
-- 22/10/2019- Dmiralpeix
----------------------------------------------------------------------------------
BEGIN TRY



Insert Into Offline_Menus (appname, Title, descrip,[Order], TypeId) values(@AppName,'new menu','new menu',0,'text')

RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CheckApp Stored

CREATE PROCEDURE [dbo].[pNet_CheckApp]
@AppName nvarchar(255)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CheckApp
--#CREATION
-- 11/11/2020
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Check if an app is authorized and returns it to get token page
--#PARAMETERS
--
--#OBSERVATIONS
-- Happy 78th Birthday mom
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

select Descrip,Icon,ReturnTokenUrl from [WebAPI_Apps] where AppName=@AppName and isAuthorized=1

RETURN 1
END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CheckConstraints Stored

CREATE PROCEDURE [dbo].[pNet_CheckConstraints]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CheckConstraints
--#CREATION
-- 29/03/2018
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Check integrity of all constraints in the database and raises an error if exists a violation
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @SQL NVARCHAR(MAX)=N'ERROR checking database constraints:' + NCHAR(13)+NCHAR(10)

DECLARE @T TABLE ([Table] NVARCHAR(MAX),[Constraint] NVARCHAR(MAX),[Where] NVARCHAR(MAX))

INSERT INTO @T([Table],[Constraint],[Where])
EXEC ( 'DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS,NO_INFOMSGS')

IF EXISTS(
SELECT 1 FROM @T
) BEGIN

SELECT @SQL = @SQL +
N'Table:'+CONVERT(NVARCHAR(MAX),ISNULL([Table],N'')) +
N',Constraint:'+CONVERT(NVARCHAR(MAX),ISNULL([Constraint],N'')) +
N',Row:'+CONVERT(NVARCHAR(MAX),ISNULL([Where],N''))+NCHAR(13)+NCHAR(10)
FROM @T

RAISERROR(@SQL,12,1)

END

RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CheckWebHook Stored

CREATE PROCEDURE [dbo].[pNet_CheckWebHook]
@WebHookID nvarchar(255),
@RequiresAuthorization bit
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CheckWebHook
--#CREATION
-- 16/11/2020
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Check if an wenhook is authorized and returns it to controller
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

select Origin, ProcessName from WebHooks where WebHookID=@WebHookID and RequiresAuthorization=@RequiresAuthorization

RETURN 1
END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CleanJobLog Stored

Create PROCEDURE [dbo].[pNet_CleanJobLog]
@jobName AS nvarchar(50)

AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CleanJobLog
--#CREATION
-- 29/10/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Cleans log from a given jos
--#PARAMETERS
-- @jobName: Job Name
--#OBSERVATIONS
--
--#CHANGES
-- 29/10/2018- David Miralpeix
----------------------------------------------------------------------------------
DELETE FROM Jobs_log WHERE jobName=@jobName

RETURN 1

pNet_ClearActionLog Stored

CREATE PROCEDURE [dbo].[pNet_ClearActionLog]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_ClearActionLog]
--#CREATION
-- 12/07/2020 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- Clears over 6 month old action logs
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

Declare @ActionLogActiveMonths int = null

select @ActionLogActiveMonths=SettingValue from Settings where SettingName='ActionLogActiveMonths' and ISNUMERIC(SettingValue)=1

if @ActionLogActiveMonths is null BEGIN
set @ActionLogActiveMonths=6
END

WHILE 1 = 1
BEGIN
DELETE TOP (1000)
ActionsLog where timestamp < dateadd(month,(@ActionLogActiveMonths*-1),getdate())

IF @@rowcount < 1000
BREAK;
END

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0


END CATCH

pNet_ClearErrorLog Stored

CREATE PROCEDURE [dbo].[pNet_ClearErrorLog]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_ClearErrorLog]
--#CREATION
-- 12/07/2020 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- clears over 1 year old error logs
--#PARAMETERS

--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN

delete from Error_Log where timestamp < dateadd(year,-1,getdate())

COMMIT

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ClearOfflineSync Stored

CREATE PROCEDURE [dbo].[pNet_ClearOfflineSync]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_ClearOfflineSync]
--#CREATION
-- 12/02/2021 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- Clears a configurable months old sync logs = default 1
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

Declare @SyncLogsClearMonth int = null

select @SyncLogsClearMonth=SettingValue from Settings where SettingName='SyncLogsClearMonth' and ISNUMERIC(SettingValue)=1

if @SyncLogsClearMonth is null BEGIN
set @SyncLogsClearMonth=1
END

WHILE 1 = 1
BEGIN
DELETE TOP (100) -- We put 100 bc its a very heavy data
FROM Offline_Sync
where SyncDate < dateadd(month,(@SyncLogsClearMonth*-1), getdate())

IF @@rowcount < 100
BREAK;
END

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0


END CATCH

pNet_ClearOldLog Stored

CREATE PROCEDURE [dbo].[pNet_ClearOldLog]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_ClearOldLog]
--#CREATION
-- 22/02/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Removes old log from cron jobs
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
-- 22/02/2018- Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction


Delete J
from
jobs_log J inner join (
select executionId, row_number() over(partition by jobName order by jobstart desc) as Ord from jobs_log) ord on J.ExecutionId=ord.ExecutionId
where ord>50



COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CloneTemplate Stored

CREATE PROCEDURE [dbo].[pNet_CloneTemplate](
@TemplateID nvarchar(50),
@NewTemplateID nvarchar(50),
@NewTemplateDescrip nvarchar(500)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CloneTemplate
--#CREATION
-- 01/11/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Clones existing template with template groups
--#PARAMETERS
-- @TemplateID Template Id,
-- @NewTemplateID New Templeat Id
-- @NewTemplateDescrip New template descrip
--#OBSERVATIONS
--
--#CHANGES
-- 01/11/2018- David MiralpeiX
----------------------------------------------------------------------------------

BEGIN TRY

begin Tran
INSERT INTO [Objects_Templates]
([TemplateId],[ObjectName],[TypeId],[Descrip],[Body],[ViewName],[WhereSentence],[Header],[Footer],[Empty],[ModuleClass],[IsDefault])
SELECT @NewTemplateID,[ObjectName],[TypeId],@NewTemplateDescrip,[Body],[ViewName],[WhereSentence],[Header],[Footer],[Empty],[ModuleClass],0 as IsDefault from Objects_Templates where TemplateId=@TemplateID


INSERT INTO [Objects_Templates_Groups]
([TemplateId],[GroupField],[Order],[OrderType],[Header],[Footer])
Select @NewTemplateID ,GroupField,[Order],OrderType,Header,Footer from Objects_Templates_Groups where TemplateId=@TemplateID


select 'flexygo.nav.openPage(''edit'',''sysObjectTemplate'',''(TemplateId=\''' + @NewTemplateID+'\'')'',null,''popup'',false,' + NCHAR(36) + '(this))' as Javascript
commit
RETURN 1

END TRY

BEGIN CATCH

Rollback
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ConfigureDependencies Stored




CREATE PROCEDURE [dbo].[pNet_ConfigureDependencies](
@ObjectName T_ObjectName,
@PropertyName T_PropertyName,
@Dependencies Tbl_Objects_Properties_Dependencies readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ConfigureDependencies
--#CREATION
-- 18/10/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Changes the dependencies of a single property.
--#PARAMETERS
-- @ObjectName: The object name.
-- @PropertyName: The property name.
-- @Dependencies: Table with the new dependencies configuration.

--#OBSERVATIONS
--
--#CHANGES
-- 18/10/2016- Rubén Pardo
-- 27/05/2019- David Miralpeix Added ConstringId
-- 23/08/2019- Rommel Llumiquinga Added PropertyValue and CusPropName
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction


delete Objects_Properties_Dependencies where ObjectName=@ObjectName and PropertyName=@PropertyName

insert into Objects_Properties_Dependencies(ObjectName,PropertyName,DependingPropertyName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId)
Select ObjectName,PropertyName,DependingPropertyName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,
SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId from @Dependencies
where
(isnull(SQLValue,'')<>'' or
isnull(SQLComboSentence,'')<>'' or
isnull(SQLComboFilter,'')<>'' or
isnull(SQLEnabled,'')<>'' or
isnull(EnabledValues,'')<>'' or
isnull(DisabledValues,'')<>'' or
isnull(SQLVisible,'')<>'' or
isnull(VisibleValues,'')<>'' or
isnull(HiddenValues,'')<>'' or
isnull(SQLClass,'')<>'' or
isnull(SQLRequired,'')<>'' or
isnull(RequiredValues,'')<>'' or
isnull(NotRequiredValues,'')<>'' or
isnull(PropertyValue,'')<>'' or
isnull(CusPropName,'')<>'' or
isnull(SQLCustomProperty,'')<>'')




COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ConfigurePageModules Stored

CREATE PROCEDURE [dbo].[pNet_ConfigurePageModules](
@PageName T_PageName OUTPUT,
@ObjectName T_ObjectName,
@LayoutName T_LayoutName,
@Modules Tbl_Modules READONLY
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ConfigurePageModules
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Changes layout and pages modules.
--#PARAMETERS
-- @PageName: Page Id to config.
-- @ObjectName: ObjectName
-- @LayoutName: New layout name
-- @Modules: Table with the new modules.

--#OBSERVATIONS
--
--#CHANGES
-- 11/10/2016- Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction

if (select Generic from pages where PageName=@PageName)=1 BEGIN

DECLARE @oldPageName T_PageName = @pageName

SET @PageName = NEWID() --isnull((select max(Pagexd) from Pages),0)+1

insert into Pages(PageName,TypeId,ObjectName,InterfaceName,LayoutName,Name,IconName,Descrip,UrlRewrite,Script,ScriptActive,[Style],RefreshInterval,Sytem,Generic)
select @PageName,TypeId,@ObjectName,InterfaceName,LayoutName,TypeId + ' '+ isnull(@ObjectName,'') as Name,IconName,Descrip,UrlRewrite,Script,ScriptActive,[Style],RefreshInterval,Sytem,0
from pages where PageName=@oldPageName

END

update pages set LayoutName=@LayoutName where PageName=@PageName

Delete O
from Pages_Modules O left join @Modules N on O.ModuleName=N.ModuleName
where O.PageName=@PageName and N.ModuleName is null

Update O set LayoutPositionId=N.LayoutPositionId,[Order]=N.[Order]
from @Modules N
inner join Pages_Modules O on O.ModuleName=N.ModuleName and O.PageName=@PageName

insert into Pages_Modules(PageName,ModuleName,LayoutPositionId,RelationWhere,[Order])
Select @PageName,N.ModuleName,N.LayoutPositionId,N.RelationWhere,N.[Order] from @Modules N
left join Pages_Modules O on O.ModuleName=N.ModuleName and O.PageName=@PageName
where O.ModuleName is null


--Borrar los modules asociados a un tab
delete pm
from Pages_Modules_Tabs pm
inner join @Modules m on pm.TabModuleName=m.TabName
where m.TabName is not null

insert into Pages_Modules_Tabs (TabModuleName,ModuleName,[Order])
select distinct TabName,ModuleName,TabOrder
from @Modules
where TabName is not null


COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ConfigureProcessDependencies Stored

CREATE PROCEDURE [dbo].[pNet_ConfigureProcessDependencies](
@ProcessName T_ProcessName,
@PropertyName T_PropertyName,
@Dependencies Tbl_Objects_Properties_Dependencies readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ConfigureProcessDependencies
--#CREATION
-- 18/10/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Changes the dependencies of a single property.
--#PARAMETERS
-- @ProcessName: The process name.
-- @PropertyName: The param property name.
-- @Dependencies: Table with the new dependencies configuration.

--#OBSERVATIONS
--
--#CHANGES
-- 21/19/2017- Rubén Pardo
-- 27/05/2019- David Miralpeix Added ConstringId
-- 23/08/2019- Rommel Llumiquinga Added PropertyValue and CusPropName
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction


delete Processes_Params_Dependencies where ProcessName=@ProcessName and ParamName=@PropertyName

insert into Processes_Params_Dependencies(ProcessName,ParamName,DependingParamName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId)
Select ObjectName,PropertyName,DependingPropertyName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,
SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId from @Dependencies
where
(isnull(SQLValue,'')<>'' or
isnull(SQLComboSentence,'')<>'' or
isnull(SQLComboFilter,'')<>'' or
isnull(SQLEnabled,'')<>'' or
isnull(EnabledValues,'')<>'' or
isnull(DisabledValues,'')<>'' or
isnull(SQLVisible,'')<>'' or
isnull(VisibleValues,'')<>'' or
isnull(HiddenValues,'')<>'' or
isnull(SQLClass,'')<>'' or
isnull(SQLRequired,'')<>'' or
isnull(RequiredValues,'')<>'' or
isnull(NotRequiredValues,'')<>'' or
isnull(PropertyValue,'')<>'' or
isnull(CusPropName,'')<>'' or
isnull(SQLCustomProperty,'')<>'')



COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ConfigureReportDependencies Stored

CREATE PROCEDURE [dbo].[pNet_ConfigureReportDependencies](
@ReportName T_ReportName,
@PropertyName T_PropertyName,
@Dependencies Tbl_Objects_Properties_Dependencies readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ConfigureReportDependencies
--#CREATION
-- 18/10/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Changes the dependencies of a single property.
--#PARAMETERS
-- @ReportName: The report name.
-- @PropertyName: The param property name.
-- @Dependencies: Table with the new dependencies configuration.

--#OBSERVATIONS
--
--#CHANGES
-- 21/19/2017- Rubén Pardo
-- 27/05/2019- David Miralpeix Added ConstringId
-- 23/08/2019- Rommel Llumiquinga Added PropertyValue and CusPropName
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction


delete Reports_Params_Dependencies where ReportName=@ReportName and ParamName=@PropertyName

insert into Reports_Params_Dependencies(ReportName,ParamName,DependingParamName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId)
Select ObjectName,PropertyName,DependingPropertyName,[Order],Active,Descrip,SQLValue,SQLComboSentence,SQLComboFilter,SQLEnabled,EnabledValues,DisabledValues,
SQLVisible,VisibleValues,HiddenValues,SQLClass,SQLRequired,RequiredValues,NotRequiredValues,PropertyValue,CusPropName,SQLCustomProperty,ConnStringId from @Dependencies
where
(isnull(SQLValue,'')<>'' or
isnull(SQLComboSentence,'')<>'' or
isnull(SQLComboFilter,'')<>'' or
isnull(SQLEnabled,'')<>'' or
isnull(EnabledValues,'')<>'' or
isnull(DisabledValues,'')<>'' or
isnull(SQLVisible,'')<>'' or
isnull(VisibleValues,'')<>'' or
isnull(HiddenValues,'')<>'' or
isnull(SQLClass,'')<>'' or
isnull(SQLRequired,'')<>'' or
isnull(RequiredValues,'')<>'' or
isnull(NotRequiredValues,'')<>'' or
isnull(PropertyValue,'')<>'' or
isnull(CusPropName,'')<>'' or
isnull(SQLCustomProperty,'')<>'')


COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CopyProcessParamsToDestProcess Stored

CREATE PROCEDURE [dbo].[pNet_CopyProcessParamsToDestProcess]
@ProcessNameO T_ProcessName,
@ProcessNameD T_ProcessName
AS
-- =============================================
-- #AUTOR:
-- CARMEN

-- #NAME:
--- PNet_CopyProcessParamsToDestProcess
-- #CREATION:
-- 03/02/2016
-- #CLASIFICATION:
--
--010-GENERAL
-- #DESCRIPTION:
-- Copy the parameters process @ProcessNameO to destiny process with copying the records in the tables : Processes_params and Processes_Params_Dependencies
-- and Returns the new proceess
-- #PARAMETERS:
-- @IdProcessNameO Number of the origin process
-- @IdProcessNameD: destiny Process

-- #OBSERVATIONS:
--
-- #CHANGES:
-- 2018-02-02 -- When the key was changed from process to string, the process was not revised and stopped working. now it works again
--
-- #EXAMPLE:
-- DECLARE @ProcessNameD int =9 ,
-- @ProcessNameO int=1,

-- EXEC PNet_CopyProcessParamsToDestProcess @ProcessNameO, @ProcessNameD

-- =============================================



DECLARE
@TableName Varchar(1000),
@OmittedCols Varchar(8000),
@FieldsString Varchar(max) ,
@SqlExecute nVarchar(max)

BEGIN TRY
IF @ProcessNameO IS NULL OR NOT EXISTS (SELECT * FROM Processes WHERE ProcessName =@ProcessNameO ) BEGIN
RAISERROR ('Error, the Origin process entered does not exist or no origin process has been entered',12,1)
RETURN 0
END

IF @ProcessNameD IS NULL OR NOT EXISTS (SELECT * FROM Processes WHERE ProcessName =@ProcessNameD ) BEGIN
RAISERROR ('Error, the Destination process entered does not exist or no origin process has been entered',12,1)
RETURN 0
END


BEGIN TRAN

SELECT
@TableName ='Processes_Params',
@OmittedCols ='ProcessName',
@FieldsString='',
@SqlExecute =''

SELECT @FieldsString = FieldsString FROM dbo.fNet_ReturnTableFieldsToString (@TableName, @OmittedCols)
IF LEN (ISNULL(@FieldsString,''))>0 BEGIN

SELECT @SqlExecute ='INSERT INTO ' + @TableName + '( ' + @OmittedCols + ','+ @FieldsString + ')
SELECT ''' + @ProcessNameD + ''',' + @FieldsString +' FROM ' + @TableName + ' T
WHERE ProcessName =''' + @ProcessNameO + ''' AND NOT EXISTS (SELECT * FROM ' + @TableName + ' D WHERE D.ProcessName = ''' + @ProcessNameD + ''' AND D.ParamName = T.ParamName )'
-- Print @sqlExecute
EXEC sp_executesql @SqlExecute
END

SELECT
@TableName ='Processes_Params_Dependencies',
@OmittedCols ='ProcessName',
@FieldsString='',
@SqlExecute =''

SELECT @FieldsString = FieldsString FROM dbo.fNet_ReturnTableFieldsToString (@TableName, @OmittedCols)

IF LEN (ISNULL(@FieldsString,''))>0 BEGIN

SELECT @SqlExecute ='INSERT INTO ' + @TableName + '( ' + @OmittedCols + ','+ @FieldsString + ')
SELECT ''' + @ProcessNameD + ''',' + @FieldsString +' FROM ' + @TableName + ' T
WHERE ProcessName =''' + @ProcessNameO + ''' AND NOT EXISTS (SELECT * FROM ' + @TableName + ' D WHERE D.ProcessName = ''' + @ProcessNameD + ''' AND D.ParamName = T.ParamName AND D.DependingParamName=T.DependingParamName )'
-- Print @sqlExecute
EXEC sp_executesql @SqlExecute
END

COMMIT TRAN
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

PNet_CopyProcessToNew Stored

CREATE PROCEDURE [dbo].[PNet_CopyProcessToNew]
@ProcessNameO T_ProcessName,
@Name T_ProcessNAme
AS
-- =============================================
-- #AUTOR:
-- CARMEN

-- #NAME:
--- PNet_CopyProcessToNew
-- #CREATION:
-- 03/02/2016
-- #CLASIFICATION:
--
--010-GENERAL
-- #DESCRIPTION:
-- Copy the process @ProcessIdO to a new process with the name @Name, copying the records in the tables : Processes, Processes_params and Processes_Params_Dependencies
-- and Returns the new proceess
-- #PARAMETERS:
-- @ProcessNameO: Name of the origin process
-- @Name : Name of the new process


-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
-- DECLARE @ProcessIdD int =NULL ,
-- @ProcessIdO int=1,
-- @Name varchar(255) ='Marcar Para Facturar'
-- EXEC PNet_CopyProcessToNew @ProcessIdO, @Name ,@@ProcessIdD OUTPUT

-- =============================================


DECLARE
@TableName Varchar(255),
@OmittedCols Varchar(8000),
@FieldsString Varchar(max) ,
@SqlExecute nVarchar(max)

BEGIN TRY
IF @ProcessNameO IS NULL OR NOT EXISTS (SELECT * FROM Processes WHERE ProcessName = @ProcessNameO ) BEGIN
RAISERROR ('Error, the origin process entered does not exist or no origin process has been entered',12,1)
RETURN 0
END

IF ISNULL(@Name ,'')='' RAISERROR ('You must report the name of the new process',12,1)
IF EXISTS (SELECT * FROM Processes WHERE ProcessName = @Name) RAISERROR ('The New Process already exists',12,1)




BEGIN TRAN


SELECT @TableName ='Processes',
@OmittedCols ='ProcessName'

SELECT @FieldsString = FieldsString FROM dbo.fNet_ReturnTableFieldsToString (@TableName, @OmittedCols)

IF LEN (ISNULL(@FieldsString,''))>0 BEGIN

SELECT @SqlExecute ='INSERT INTO ' + @TableName + '( ' + @OmittedCols + ','+ @FieldsString + ')
SELECT ''' + @Name + ''',' + @FieldsString +' FROM ' + @TableName +
' WHERE ProcessName = ''' + @ProcessNameO + ''''

--Print @sqlExecute
EXEC sp_executesql @SqlExecute
END

EXEC pNet_CopyProcessParamsToDestProcess @ProcessNameO, @Name

COMMIT TRAN
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

PNet_CopyPropertiesObjectToCollection Stored

CREATE PROCEDURE [dbo].[PNet_CopyPropertiesObjectToCollection]
@ObjectName T_ObjectName,
@Properties t_Boolean =0,
@Dependencies T_Boolean=0,
@ObjectTarget T_ObjectName
AS
-- =============================================
-- #AUTOR:
-- CARMEN

-- #NAME:
--- PNet_CopyPropertiesObjectToCollection
-- #CREATION:
-- 03/02/2016
-- #CLASIFICATION:
--
--010-GENERAL
-- #DESCRIPTION:
-- if the parameter "Properties" is true it copies properties from Object to collection , if the parameter "dependencies" is true it copies dependencies
-- If The "ObjectTarget" parameter is empty the copy is Object->Collection, else the copy is Object->Object Target
-- and Returns the new proceess
-- #PARAMETERS:
-- @ObjectName: Name of object
-- @Dependencies : 0 copy only properties , 1 copy dependencies
-- @Properties : 0 no copy Properties, 1 Copy Properties ,
-- @Object Target : Object with the same table that the object source. We copy the properties the Object source to object target.


-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
-- EXEC PNet_CopyPropertiesObjectToCollection 'Customers_Delivery_Notes_Line',1

-- =============================================


DECLARE
@TableName Varchar(255),
@OmittedCols Varchar(8000),
@FieldsString Varchar(max) ,
@SqlExecute nVarchar(max),
@CollectionName T_Objectname

BEGIN TRY
IF @ObjectName IS NULL OR NOT EXISTS (SELECT * FROM Objects WHERE ObjectName = @ObjectName ) BEGIN
RAISERROR( ' the object doesn''t exist',12,1)
RETURN 0
END

IF @ObjectTarget IS NOT NULL BEGIN

IF NOT EXISTS (SELECT * FROM Objects where Objectname =@ObjectTarget )
RAISERROR('The object target doesn''t exsist',12,1)

IF NOT EXISTS (SELECT OT.* FROM Objects OT
INNER JOIN Objects OO ON OO.ObjectName =@ObjectName AND OO.TableName =OT.TableName
WHERE OT.ObjectName =@ObjectTarget )
RAISERROR ('The Object source table isn''t the same that the Object target table.',12,1)
SELECT @CollectionName =@ObjectTarget

END ELSE
SELECT @CollectionName =ObjectName FROM Objects WHERE ObjectChildName =@ObjectName

IF ISNULL(@CollectionName ,'')='' RAISERROR ('The collection has not been found',12,1)
BEGIN TRAN
IF @Properties <>0 BEGIN -- Copy Properties

SELECT @TableName ='Objects_Properties',
@OmittedCols ='ObjectName'

SELECT @FieldsString =FieldsString FROM dbo.fNet_ReturnTableFieldsToString (@TableName, @OmittedCols)

IF LEN (ISNULL(@FieldsString,''))>0 BEGIN

SELECT @SqlExecute ='INSERT INTO ' + @TableName + '( ' + @OmittedCols + ','+ @FieldsString + ')
SELECT ''' + @CollectionName + ''',' + @FieldsString +' FROM ' + @TableName + ' O
WHERE ObjectName = ''' + @ObjectName + ''' AND NOT EXISTS (SELECT * FROM ' +@TableName + ' WHERE ObjectName =''' + @CollectionName +''' AND PropertyName=O. PropertyName)'


--Print @sqlExecute
EXEC sp_executesql @SqlExecute
END
END
IF @Dependencies <>0 BEGIN
SELECT
@TableName ='Objects_Properties_Dependencies',
@OmittedCols ='ObjectName,PropertyName,OriginId,ConnStringId',
@FieldsString='',
@SqlExecute =''

SELECT @FieldsString = FieldsString FROM dbo.fNet_ReturnTableFieldsToString (@TableName, @OmittedCols)
IF LEN (ISNULL(@FieldsString,''))>0 BEGIN

SELECT @SqlExecute ='INSERT INTO ' + @TableName + '( ' + @OmittedCols + ','+ @FieldsString + ')
SELECT ''' + @CollectionName + ''' , O.PropertyName, O.OriginId, O.ConnStringId, ' + @FieldsString +' FROM ' + @TableName + ' O
INNER JOIN Objects_Properties OP ON OP.Objectname ='''+@CollectionName + ''' AND OP.PropertyName =O.PropertyName
INNER JOIN Objects_properties OPD ON OPD.ObjectName =''' + @CollectionName +''' AND OPD.PropertyName =O.DependingPropertyName
WHERE O.ObjectName = ''' + @ObjectName + ''' AND NOT EXISTS (SELECT * FROM ' +@TableName

PNet_CopyPropertiesObjectToCollection Stored

+ ' WHERE ObjectName =''' + @CollectionName + ''' AND PropertyName=O. PropertyName AND DependingPropertyName=O.DependingPropertyName)'
--Print @sqlExecute
EXEC sp_executesql @SqlExecute
END
END

COMMIT TRAN
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateDatabase_CheckData Stored

CREATE PROCEDURE [dbo].[pNet_CreateDatabase_CheckData]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateDatabase_CheckData
--#CREATION
-- 07/09/2017
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Checks the tables and objects of the database at create time to ensure all data needed for future updates is informed
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/09/2017-JJR-Initival Version
-- 27/09/2017-JJR-Add and correct comprobations
-- 16/01/2018-RPARDO-Check registers with incorrect originId
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @AllErrors NVARCHAR(MAX)= N''
DECLARE @Error NVARCHAR(MAX)= N''
DECLARE @CRLF NVARCHAR(MAX)= NCHAR(13)+NCHAR(10)

--Check integrity between tables and configuration table
SELECT @Error = @Error +
CASE WHEN ST.Name IS NULL THEN
N'Configured table ' + CT.TableName + N' does not exist in database.'
ELSE
N'Existing table ' + ST.NAME + N' is not configured in [Configuration_Tables].'
END + @CRLF

FROM
sys.tables ST
FULL JOIN Configuration_Tables CT ON ST.Name = CT.TableName
WHERE
(ST.NAME IS NULL OR CT.TableName IS NULL)
AND NOT (
(ST.Name = '__RefactorLog' AND CT.TableName IS NULL) --SSDT Exception
OR
(ST.Name LIKE 'zVersion_%') --FlexyGo system tables

)

--Check integrity between fields and configuration table
SELECT @Error = @Error + N'Configured field ' + CDA.FieldName + N' from table ' + CDA.TableName + N' does not exist in database.' + @CRLF

FROM
Configuration_Default_Actions CDA
LEFT JOIN sys.columns SC ON CDA.TableName = OBJECT_NAME(sc.object_id) AND CDA.FieldName = SC.Name
WHERE
CDA.TableName IS NOT NULL AND CDA.FieldName IS NOT NULL AND SC.OBJECT_ID IS NULL


--No actions can be configured for non-comparable tables
SELECT @Error = @Error + N'Invalid action for table ' + CDA.TableName + N'. Table is not comparable.' + @CRLF

FROM
Configuration_Default_Actions CDA
INNER JOIN Configuration_Tables CT ON CDA.TableName = CT.TableName
WHERE
CT.CompareMode = 0


--Check presence/absence of OriginId field
SELECT @Error = @Error +
CASE WHEN CT.CompareMode = 0 THEN
N'Table ' + CT.TableName + N' contains an OriginId field but is configured to not be compared.'
ELSE
N'Table ' + CT.TableName + N' is configured to be compared but not contains an OriginId field.'
END + @CRLF

FROM
Configuration_Tables CT
LEFT JOIN sys.columns SC ON CT.TableName = OBJECT_NAME(sc.object_id) AND SC.NAME='OriginId'
WHERE
CT.TableName NOT IN (
'Origins'
) AND (
(CT.CompareMode = 0 AND SC.Name IS NOT NULL)
OR
(CT.CompareMode = 1 AND SC.Name IS NULL)
)


--Tables configured to be compared must have at least one alphanumeric field into its PK
SELECT @Error = @Error + N'Table ' + CT.TableName + N' is configured to be compared but its primary key field ' + CTPK.ColumnName + ' is not alphanumeric.' + @CRLF

FROM
Configuration_Tables CT
CROSS APPLY (
SELECT sc.name ColumnName
FROM
sys.indexes i
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
INNER JOIN sys.columns sc ON ic.object_id = sc.object_id AND sc.column_id = ic.column_id
INNER JOIN sys.types st on sc.system_type_id = st.system_type_id and st.system_type_id = st.user_type_id
WHERE
OBJECT_NAME(i.object_id) = CT.TableName
AND i.is_primary_key = 1
AND ic.key_ordinal = 1
AND st.name NOT IN ('nvarchar','uniqueidentifier')
) CTPK
WHERE
CT.CompareMode = 1




--Check that all defaults have a proper name
SELECT @Error = @Error + N'Default constraint ' + CONVERT(NVARCHAR(MAX),name) + N' is system named. Must have a proper name.'+@CRLF
FROM
sys.default_constraints
WHERE
is_system_named = 1

SELECT @Err

pNet_CreateDatabase_CheckData Stored

or = @Error + N'Check constraint ' + CONVERT(NVARCHAR(MAX),name) + N' is system named. Must have a proper name.'+@CRLF
FROM
sys.check_constraints
WHERE
is_system_named = 1

SELECT @Error = @Error + N'Key constraint ' + CONVERT(NVARCHAR(MAX),kc.name) + N' is system named. Must have a proper name.'+@CRLF
FROM
sys.key_constraints kc
INNER JOIN sys.objects so ON kc.parent_object_id = so.object_id
WHERE
kc.is_system_named = 1
AND kc.is_ms_shipped = 0
AND NOT (
so.name='__RefactorLog' AND so.type = 'U' --SSDT exception
)

SELECT @Error = @Error + N'Foreign key constraint ' + CONVERT(NVARCHAR(MAX),name) + N' is system named. Must have a proper name.'+@CRLF
FROM
sys.foreign_keys
WHERE
is_system_named = 1

--Checks for wrong origin id in tables
Declare @SQLSentence nvarchar(max)
declare @CurrentOriginId nvarchar(2)

set @CurrentOriginId=convert(varchar(2),(select Originid from Origins where Active=1))

;WITH vOrigins AS (
select 'select count(*) as OriginCount,'''+o.name+''' as TableName from ['+o.name+'] where OriginId>'+@CurrentOriginId as OriginsTest, o.name as TableName from sysobjects o
inner join syscolumns c on c.id=o.id and c.name='OriginId'
where o.type='U' and (o.name not like '%zVersion_%' and o.name <> 'Origins')
)
Select
@SQLSentence=replace(replace('select @xml = (select OriginCount,TableName from ('+substring((
Select 'UNION '+ST1.OriginsTest AS [text()]
From vOrigins ST1
ORDER BY ST1.OriginsTest
For XML PATH ('')
),7,100000000000000)+') A where a.OriginCount>0 for xml path('''') )' ,'&gt;','>'),'&lt;','<')


declare @xmlout xml
DECLARE @ParmDefinition nvarchar(500);

exec sp_executesql @SQLSentence, N'@xml xml OUTPUT' ,@XML=@XMLout OUTPUT

if not @XMLOut is null BEGIN

declare @ErrorString nvarchar(max)
SELECT @ErrorString='Database contains registers with OriginId greater than '+@CurrentOriginId+':' + @CRLF + replace(replace(replace(replace(convert(nvarchar(max),@XMLout),'<originCount>',''),'</originCount>',' '),'<TableName>',''),'</TableName>',@CRLF)

set @Error += @ErrorString + @CRLF

END

--END Checks for wrong origin id in tables

IF @Error IS NULL BEGIN --@Error must be '', if it's NULL is because some queries are wrong
RAISERROR('Error checking install data. Please review pNet_CreateDatabase_CheckData',12,1)
END

IF LEN(ISNULL(@Error,N''))>0 BEGIN
RAISERROR(@Error,12,1)
END

RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateDatabase_CopyConfData Stored

CREATE PROCEDURE [dbo].[pNet_CreateDatabase_CopyConfData]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateDatabase_CopyConfData
--#CREATION
-- 12/09/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Generates and fills the zVersion_[TableName] tables in the moment of the install
--#PARAMETERS

--#OBSERVATIONS
--
--#CHANGES
-- 28/08/2017-JJR-First version
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @TableName NVARCHAR(1000)
DECLARE @CopyTable NVARCHAR(1000)
DECLARE @SQL NVARCHAR(MAX)

DECLARE curTables CURSOR FOR

SELECT
TableName
FROM
Configuration_Tables
WHERE
CompareMode = 1

OPEN curTables
FETCH NEXT FROM curTables INTO @TableName
WHILE @@FETCH_STATUS <> -1 BEGIN

SET @CopyTable = N'zVersion_' + @TableName

SET @SQL =N'IF EXISTS(SELECT 1 FROM sys.tables WHERE name = ''' + @CopyTable + ''') DROP TABLE ' + QUOTENAME(@CopyTable) + ';'

SET @SQL += N'SELECT * INTO ' + QUOTENAME(@CopyTable ) + N' FROM ' + QUOTENAME(@TableName) + N' WHERE OriginId IN (0,1)'

--print @sql

EXEC sp_executesql @SQL

SET @SQL = N'IF EXISTS(SELECT * FROM ' + @TableName + N' WHERE OriginId IN (0,1) EXCEPT SELECT * FROM zVersion_' + @TableName + N') RAISERROR(''Error populating mirror tables'',12,1)'

EXEC sp_executesql @SQL

FETCH NEXT FROM curTables INTO @TableName
END

CLOSE curTables
DEALLOCATE curTables

RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateObject Stored


CREATE PROCEDURE [dbo].[pNet_CreateObject](
@ObjectName T_ObjectName,
@CollectionName T_ObjectName,
@ObjectDescrip nvarchar(255),
@CollectionDescrip nvarchar(255),
@ObjectParsedDescrip nvarchar(255),
@ConnectionStringId T_connStringId,
@OriginName nvarchar(255),
@NewOriginName nvarchar(255),
@ViewKeys nvarchar(255),
@ObjectIconName T_IconName,
@CollectionIconName T_IconName,
@Offline BIT,
@AppName nvarchar(100)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateObject
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates entries in objects Table using stored procedure parameter info
--#PARAMETERS
-- @ObjectName: Object Name
-- @CollectionName: collection name
-- @ObjectDescrip: Object description
-- @CollectionDescrip: collection Description
-- @ObjectParsedDescrip: Object Parseable description
-- @ConnectionStringId: Database connection string Id
-- @OriginName: Table or View name
-- @ViewKeys: View primary Keys
-- @ObjectIconName: Object Icon Name
-- @CollectionIconName: Collection Icon Name

--#OBSERVATIONS
-- Creates EntityObject and Entitycollection entries in object Table
--#CHANGES
-- 07/06/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRANSACTION

IF @Offline = 1
BEGIN
DECLARE @OfflinePrefix AS NVARCHAR(20) = 'Offline_'
SET @ObjectName = @OfflinePrefix + @ObjectName
SET @CollectionName = @OfflinePrefix + @CollectionName
END

--Object
INSERT INTO [dbo].[Objects] ([ObjectName],[Iscollection],[ObjectChildName],[TableName],[ConfigDB] ,[Descrip],[IconName],[ParsedDescrip],[ViewKeys],[ConnStringID],[Active],[Offline])
VALUES(@ObjectName,0,null,isnull(@OriginName,@NewOriginName),Case when @ConnectionStringId='ConfConnectionString' then 1 else 0 end,@ObjectDescrip,@ObjectIconName,@ObjectParsedDescrip,@ViewKeys,@ConnectionStringId,1,@Offline)

--Collection
INSERT INTO [dbo].[Objects] ([ObjectName],[Iscollection],[ObjectChildName],[TableName],[ConfigDB] ,[Descrip],[IconName],[ParsedDescrip],[ViewKeys],[ConnStringID],[Active],[Offline])
VALUES(@CollectionName,1,@ObjectName,isnull(@OriginName,@NewOriginName),Case when @ConnectionStringId='ConfConnectionString' then 1 else 0 end,@CollectionDescrip,@CollectionIconName,@CollectionDescrip,@ViewKeys,@ConnectionStringId,1,@Offline)

IF @Offline = 1 AND @AppName IS NOT NULL
BEGIN
/*Assign object to app*/
INSERT INTO [dbo].[Offline_Objects]
([AppName]
,[ObjectName])
VALUES
(@AppName
,@ObjectName)
/*Enable object on the webapi*/
INSERT INTO [dbo].[WebAPI_Objects]
([ObjectName]
,[CanView]
,[CanViewCollection]
,[CanInsert]
,[CanEdit]
,[CanDelete]
,[CanPrint])
VALUES
(@ObjectName
,1
,1
,0
,0
,0
,0)


DECLARE @IconCss NVARCHAR(200) = (select CSSClass from Icons where IconName=@ObjectIconName)
DECLARE @DefaultListTemplate NVARCHAR(MAX)
SET @DefaultListTemplate='
<ion-item lines="full" onclick="flexygo.nav.goView('''+@ObjectName+''','''+@ObjectName + '_View'',''{{objIdent|JS}}'')">
<ion-chip color="primary" >
<i class="'+ISNULL(@IconCss,'')+'" ></i>
</ion-chip>
<ion-label>
<h2>'+ISNULL(@ObjectParsedDescrip,'Field1')+'</h2>
<h3><i class="ion-color-medium flx-icon icon-phone" ></i> TODO: Field 2</h3>
</ion-label>
</ion-item>'

DECLARE @DefaultViewTemplate NVARCHAR(MAX)
SET @DefaultViewTemplate='
<ion-card>
<ion-grid>
<ion-row>
<ion-col size="3">
<ion-chip color="medium" >
<i class="'+ISNULL(@IconCss,'')+' icon-lg" ></i>
</ion-chip>
</ion-col>
<ion-col size="9">
<ion-list>

pNet_CreateObject Stored

<h5>'+ISNULL(@ObjectParsedDescrip,'Field1')+'</h5>
<p><i class="flx-icon icon-digger" ></i> {{Field1}}</p>
<p><i class="flx-icon icon-vcalendar" ></i> {{Field2}}</p>
</ion-list>
</ion-col>
</ion-row>
<ion-row >
<ion-col>
<ion-list>
<ion-list-header>
Descripción
</ion-list-header>
<ion-note>{{Descrip}}</ion-note>
</ion-list>
</ion-col>
</ion-row>
</ion-grid>
</ion-card>'

DECLARE @DefaultViewFooter NVARCHAR(MAX)
set @DefaultViewFooter='<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button onclick="flexygo.nav.goEdit('''+@ObjectName+''',null,''{{objIdent|JS}}'')">
<ion-icon name="create-outline"></ion-icon>
</ion-fab-button>
</ion-fab>'

DECLARE @DefaultListFooter NVARCHAR(MAX)
set @DefaultListFooter='<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button onclick="flexygo.nav.goInsert('''+@ObjectName+''')">
<ion-icon name="add"></ion-icon>
</ion-fab-button>
</ion-fab>'

/*Default list and view page*/
INSERT INTO [dbo].[Offline_Pages]
([AppName]
,[PageName]
,[ObjectName]
,[TypeId]
,[Title]
,[Body]
,[Header]
,[Footer]
,[Empty]
,[SQLSentence]
,[ShowSearchBar]
,[IsDefault])
VALUES
(
@AppName
,@ObjectName + '_List'
,@ObjectName
,'list'
,@CollectionDescrip
,@DefaultListTemplate
,NULL
,@DefaultListFooter
,NULL
,NULL
,1
,1
),
(
@AppName
,@ObjectName + '_View'
,@ObjectName
,'view'
,@ObjectParsedDescrip
,@DefaultViewTemplate
,NULL
,@DefaultViewFooter
,NULL
,NULL
,0
,1
)
END

SELECT @ObjectName AS objectname, @CollectionName AS collectionname

COMMIT TRANSACTION
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateObjectProperties_Conection Stored

CREATE PROCEDURE pNet_CreateObjectProperties_Conection
@ObjectName T_ObjectName,
@DBConection Varchar(255),
@ConectionType Varchar (255) ='DataConection'

-- =============================================
-- #AUTOR:
-- Carmen

-- #NAME:
--- PNet_CreateObjectProperties_Conection
-- #CREATION:
-- 07/02/2017/
-- #CLASIFICATION:
--
--010-GENERAL
-- #DESCRIPTION:
-- Inserta las propiedades del objeto @Objectname en la tabla Objects_propierties
-- #PARAMETERS:
-- @ObjectName: Objeto del que queremos crear las propiedades
-- @DbConection: Base de datos del que procede el objeto
-- @ConectionType: Tipo de Conexion puede tener como valores válidos los indicados en la tabla 'DbConnectionStrings'
-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
--
--EXEC pNet_CreateObjectProperties_conection 'Pedido', 'Tiendacore','DataConnectionString'
--EXEC pNet_CreateObjectProperties_conection 'sysProcess_Process', 'Tiendacore_Ic','confConnectionString'

-- =============================================

AS
DECLARE
@Msg_err varchar(500),
@TableName Varchar(500),
@Lsql nvarchar(max),
@ParmDefinition nvarchar(500),
@Name varchar(500)

CREATE TABLE #Objects (ObjectName Varchar(100) )

BEGIN TRY
--- VALIDACION DE PARAMETROS
IF @DBConection IS NULL BEGIN

RAISERROR ('Debe Indicar El tipo de conexión. Acción cancelada', 12,1)
RETURN 0
END

IF NOT EXISTS (SELECT * FROM DbConnectionStrings WHERE ConnStringId =@ConectionType ) BEGIN
SELECT @Msg_err ='El tipo de conexion ' + @ConectionType + ' No es Válido. Acción cancelada'
RAISERROR (@Msg_err, 12,1)
RETURN 0
END


IF @ObjectName IS NOT NULL BEGIN
SELECT @TableName =TableName FROM Objects where ObjectName =@ObjectName AND Iscollection =0
IF @TableName IS NULL BEGIN
SELECT @Msg_err ='No se encuentra el nombre de la tabla asociado al objeto ' + CAST (@ObjectName AS VARCHAR ) + ' o puede que el objeto pasado sea una coleccion. Acción Cancelada '
RAISERROR (@Msg_err, 12,1 )
RETURN 0
END
END

---Comprobamos que la tabla exista en la base de datos @Dbconection
SET @ParmDefinition = N'@nameOUT varchar(500) OUTPUT';
SELECT @Lsql =N'SELECT @NameOut= name FROM ' + @DBConection +'..Sysobjects WHERE xtype=''U'' AND Name ='''+ @TableName + ''''
EXECUTE sp_executesql @lsql, @ParmDefinition, @NameOut=@Name OUTPUT;
IF @Name IS NULL BEGIN
SELECT @Msg_err ='No se encuentra la tabla ' + @TableName + '. Acción Cancelada '
RAISERROR (@Msg_err, 12,1 )
RETURN 0

END
--- FIN VALIDACION

SELECT @lsql =''

SELECT @lsql=';
WITH ColumnasSP AS (
SELECT o.name AS ObjectName
,stb.name TipoSql
,p.colid
,p.name AS PropertyName
,TYPE_NAME(P.xusertype ) AS parameter_type
,p.length
,p.prec
,p.scale
FROM ' + @DBConection + '..sysobjects AS O
INNER JOIN ' + @DBConection + '..syscolumns AS P ON O.id = P.id
INNER JOIN ' + @DBConection + '..systypes STB On P.xtype = STB.xtype And P.xtype = STB.xusertype
WHERE O.XTYPE =''U'' AND O.name = '''+ @TableName + '''
)
, TableFields AS (
SELECT
''' + @ObjectName + ''' ObjectName,
PropertyName,
PropertyName Label,
Datos.TipoPropiedad TypeId ,
Datos.DecimalPlaces,
1 Width,
1 Height,
0 positionX,
Row_Number() OVER (ORDER BY PropertyName, P.colid) PositionY
FROM ColumnasSP P
INNER JOIN
(VALUES
(''int'', ''number'', 0),
(''smallint'', ''number'', 0),
(''tinyint'', ''number'', 0),
(''smalldatetime'',''Date'',Null),
(''DateTime'',''Datetime'',Null),
(''bit'',''check'',0),
(''decimal'',''decimal'',2),
(''varchar'',''text'',Null),
(''nvarchar'', ''text'',Null)
) AS Datos (tipoSql, Tipopropiedad, DecimalPlaces) ON P.Ti

pNet_CreateObjectProperties_Conection Stored

poSql=Datos.tipoSql
)

INSERT INTO Objects_Properties (ObjectName , PropertyName , Label , Hide ,TypeId,ConnStringId, Width,Height , PositionX , PositionY, DecimalPlaces )
SELECT K.ObjectName , K.PropertyName , K.Label ,0, K.TypeId, ''' +@ConectionType +''' ,K.Width,K.Height , K.PositionX , K.PositionY , K.DecimalPlaces
FROM TableFields K
LEFT JOIN Objects_Properties P ON K.Objectname collate Modern_Spanish_CI_AS=P.ObjectName AND K.PropertyName collate Modern_Spanish_CI_AS=P.PropertyName
WHERE P.ObjectName IS NULL '

--SELECT @Lsql
EXECUTE sp_executesql @lsql
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateOrUpdateDatabase Stored

CREATE PROCEDURE [dbo].[pNet_CreateOrUpdateDatabase]
@Database NVARCHAR(255) = NULL,
@Version NVARCHAR(255) = NULL
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateOrUpdateDatabase
--#CREATION
-- 28/08/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Finishes the installation of the database application, or updates the current database with the data provided by the @Database parameter
--#PARAMETERS
-- @DatabaseName: If parameter value is empty or equals current database name, the procedure performs the default install.
-- If parameter value is diffent, the procedure imports the user data from the specified database into the current database
-- @Version: Version number of the database being deployed
--#OBSERVATIONS
--
--#CHANGES
-- 28/08/2017-JJR-First version
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN

IF ISNULL(@Database,'')='' OR ISNULL(@Database,'')=DB_NAME() BEGIN -- Version INSTALL

PRINT 'Checking database data'

EXEC pNet_CreateDatabase_CheckData

INSERT INTO Versions(VersionNumber,InstallDate,IsUpdate,OriginDatabase)
SELECT @Version,GETDATE(),0,@Database

PRINT 'Mirroring data'

EXEC pNet_CreateDatabase_CopyConfData

END ELSE BEGIN -- Version UPGRADE


INSERT INTO Versions(VersionNumber,InstallDate,IsUpdate,OriginDatabase)
SELECT @Version,GETDATE(),1,@Database

PRINT 'Mirroring version data'
--Generate zVersion_ tables with version data, updated by the post deployment scripts

EXEC pNet_CreateDatabase_CopyConfData

PRINT 'Checking differences'

--Compare and apply defined user changes
--WARNING!!! THIS MUST BE RUN AFTER pNet_CreateDatabase_CopyConfData, to store version data until next update
EXEC pNet_UpdateDatabase_FindChanges @Database, @Version

PRINT 'Applying user differences'

EXEC pNet_UpdateDatabase_ApplyUserChanges @Version, 1


END

COMMIT TRAN

RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateParamsProcess Stored

CREATE PROCEDURE pNet_CreateParamsProcess
@ProcessName T_ProcessName,
@DBConection Varchar(255)

-- =============================================
-- #AUTOR:
-- Carmen

-- #NAME:
--- PNet_CreateParamsProcess
-- #CREATION:
-- 07/02/2017/
-- #CLASIFICATION:
--
--010-GENERAL
-- #DESCRIPTION:
-- Inserta los parámetros del proceso almacenado en la tabla processes_params
-- #PARAMETERS:
-- @ProcessId: identificador del proceso en la tabla Processes, debe tener el campo storedName relleno sino dará un error
-- @ProcessName: si pasamos el nombre del procedimiento almacenado busca todos los proceso de la tabla processes que lo contenga y rellena los parámetros en todos, sino encuentra ninguno devolverá un error
-- @DbConection: Base de datos en la que se almacena el procedmiento almacenado. si no lo encuentra en la Db dará error.
-- #OBSERVATIONS:
--
-- #CHANGES:
-- 2018-02-01- Carmen - Se había cambiado la tabla y no se había modificado esta sp. y no funcionaba. Ya funciona
-- #EXAMPLE:
-- EXEC PNet_CreateParamsProcess 4, null, 'tiendacore' -- creará los parámetros si no existen ya del proceso=4
-- EXEC PNet_CreateParamsProcess null, 'PAlbaranes_Cli_PreparaDatosMasivo', 'tiendacore' -- creará los parámetros de todos los procesos que llamen a esta stored

-- =============================================

AS
DECLARE
@Msg_err varchar(500),
@Lsql as nvarchar(max),
@ParmDefinition nvarchar(500),
@Name varchar(500),
@ProcessNameSP nvarchar(255)


BEGIN TRY
-- VALIDACION DE DATOS

IF NOT EXISTS (SELECT * FROM sys.databases WHERE Name=@DBConection ) BEGIN
SELECT @Msg_err ='No se encuentra la base de datos ' + @DBConection + '. Accion cancelada'
RAISERROR (@Msg_Err,12,1)
RETURN 0
END
--Los procesos encontrados los guardamos en la tabla #Process
IF Object_ID('Tempdb..#Process') IS NOT NULL DROP TABLE #Process
CREATE TABLE #Process (ProcessName T_ProcessName)

IF EXISTS (SELECT * FROM PROCESSES WHERE ProcessName= @ProcessName ) BEGIN -- Es un proceso y buscamos el procedimiento almacenado para encontrar los parámertos

SELECT @ProcessNameSP =StoredName FROM Processes where ProcessName=@ProcessName
IF @ProcessNameSP IS NULL BEGIN
SELECT @Msg_err ='No se encuentra el procedimiento almacenado asociado al proceso ' + @ProcessName + '. Acción Cancelada '
RAISERROR (@Msg_err, 12,1 )
RETURN 0
END

INSERT INTO #Process (ProcessName )
SELECT @ProcessName

END ELSE BEGIN --- Miramos si lo que nos han pasado es un SP

IF EXISTS (SELECT * FROM PROCESSES WHERE StoredName = @ProcessName ) BEGIN
--- buscmos los procesos que contienen la sp
INSERT INTO #Process (ProcessName )
SELECT ProcessName FROM Processes P WHERE StoredName =@ProcessName
SELECT @ProcessNameSP =@ProcessName
IF NOT EXISTS ( SELECT * FROM #Process) BEGIN
SELECT @Msg_err ='No se encuentran procesos que contengan el procedimiento almacenado ' + @ProcessName + '. Acción Cancelada '
RAISERROR (@Msg_err, 12,1)
RETURN 0
END


END ELSE BEGIN
SELECT @Msg_err ='No se encuentra el procedimiento almacenado . Acción Cancelada '
RAISERROR (@Msg_err , 12,1)
RETURN 0
END
END

SET @ParmDefinition = N'@nameOUT varchar(500) OUTPUT';
SELECT @Lsql =N'SELECT @NameOut= name FROM ' + @DBConection +'..Sysobjects WHERE xtype=''P'' AND Name ='''+ @ProcessNameSP + ''''
EXECUTE sp_executesql @lsql, @ParmDefinition, @NameOut=@Name OUTPUT;
IF @Name IS NULL BEGIN
SELECT @Msg_err ='No se encuentra el procedimiento almacenado ' + @ProcessNameSp + '. Acción Cancelada '
RAISERROR (@Msg_err, 12,1 )
RETURN 0

END
--- FIN VALIDACION
SELECT @lsql =''

SELECT @lsql='
; WITH ColumnasSP AS (

SELECT o.name AS object_name
,stb.name TipoSql
,p.colid parameter_id
,p.name AS parameter_name
,T

pNet_CreateParamsProcess Stored

YPE_NAME(P.xusertype ) AS parameter_type
,p.length
,p.prec
,p.scale
,IIF(p.isoutparam<>0,''IO'',''II'') IOtype
FROM ' + @DBConection + '..sysobjects AS O
INNER JOIN ' + @DBConection + '..syscolumns AS P ON O.id = P.id
INNER JOIN ' + @DBConection + '..systypes STB On P.xtype = STB.xtype And P.xtype = STB.xusertype
WHERE o.XTYPE=''P'' AND o.name = '''+ @ProcessNameSP + '''
)
, ParamProcess AS (
SELECT
T.ProcessName,
REPLACE (parameter_name, ''@'','''' ) ParamName,
REPLACE (parameter_name, ''@'','''' ) Label,
Datos.TipoPropiedad TypeId ,
Datos.TipoParametro ParamTypeId ,
1 Width,
1 Height,
0 positionX,
IOType,
Row_Number() OVER (ORDER BY object_name, P.parameter_id) PositionY
FROM ColumnasSP P
INNER JOIN
(VALUES (''int'', ''number'', ''Integer''),
(''smallint'', ''number'', ''Integer''),
(''tinyint'', ''number'', ''Integer''),
(''smalldatetime'',''date'',''DateTime''),
(''DateTime'',''Datetime'',''DateTime''),
(''bit'',''check'',''Boolean''),
(''decimal'',''decimal'',''Decimal''),
(''varchar'',''text'',''String''),
(''nvarchar'', ''text'',''String'')
) AS Datos (tipoSql, Tipopropiedad, Tipoparametro) ON P.TipoSql=Datos.tipoSql
CROSS APPLY #Process T )

INSERT INTO Processes_Params (ProcessName , ParamName , Label , TypeId,ParamTypeId,Width,Height , PositionX , PositionY , IOtypeId)
SELECT K.ProcessName , K.ParamName , K.Label , K.TypeId,K.ParamTypeId,K.Width,K.Height , K.PositionX , K.PositionY , K.IOType
FROM ParamProcess K
LEFT JOIN Processes_Params P ON K.ProcessName=P.ProcessName AND K.ParamName collate Modern_Spanish_CI_AS=P.ParamName
WHERE P.ProcessName IS NULL '

--SELECT @Lsql
EXECUTE sp_executesql @lsql
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateProcessPropPlaceHolder Stored



CREATE PROCEDURE [dbo].[pNet_CreateProcessPropPlaceHolder]( @ProcessName T_ProcessName,@ParamName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateProcessPropPlaceHolder
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates separator entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ProcessName: Name of process
-- @ParamName: Property to take position as reference
-- @Above: Separator is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017 - Rubén Pardo
-- 27/02/2019- Carmen Change how to calculate the next number of placeholder from the last number that was given and not depending on the number of placeholder there.
----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
DECLARE @PosY as int

SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (ParamName , LEN(ParamName)-LEN('placeholder') ) as int)),0)+1
FROM Processes_Params
WHERE ProcessName=@ProcessName and typeid='placeholder' and ParamName like 'placeholder%'
AND Isnumeric(RIGHT (ParamName , LEN(ParamName )-LEN('placeholder') ))<>0

--select @sepCount=count(typeid) +1 from Processes_Params where ProcessName=@ProcessName and typeid='placeholder'
select @PosY=PositionY from Processes_Params where ProcessName=@ProcessName and ParamName=@ParamName

begin Transaction

update Processes_Params set PositionY=PositionY+1 where PositionY>=@PosY and ProcessName=@ProcessName

INSERT INTO [dbo].Processes_Params([ProcessName],[ParamName],[ParamTypeId],[PositionY],[PositionX],Width,[Label] ,TypeId )
Values (@ProcessName, 'placeholder' +convert(varchar,@sepCount) ,'String', @PosY,0,12,'Place Holder ' + convert(varchar,@sepCount),'placeholder')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateProcessPropSeparator Stored



CREATE PROCEDURE [dbo].[pNet_CreateProcessPropSeparator]( @ProcessName T_ProcessName,@ParamName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateProcessPropSeparator
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates separator entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ProcessName: Name of process
-- @ParamName: Property to take position as reference
-- @Above: Separator is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017 - Rubén Pardo
-- 27/02/2019 Carmen Change how to calculate the next number of separator from the last number that was given and not depending on the number of separators there.
----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
DECLARE @PosY as int

SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (ParamName , LEN(ParamName)-LEN('Separator') ) as int)),0)+1
FROM Processes_Params
WHERE ProcessName=@ProcessName and typeid='separator' and ParamName like 'separator%'
AND Isnumeric(RIGHT (ParamName , LEN(ParamName )-LEN('Separator') ))<>0

--select @sepCount=count(typeid) +1 from Processes_Params where ProcessName=@ProcessName and typeid='separator'
select @PosY=PositionY from Processes_Params where ProcessName=@ProcessName and ParamName=@ParamName

begin Transaction

update Processes_Params set PositionY=PositionY+1 where PositionY>=@PosY and ProcessName=@ProcessName

INSERT INTO [dbo].Processes_Params([ProcessName],[ParamName],[ParamTypeId],[PositionY],[PositionX],Width,[Label] ,TypeId )
Values (@ProcessName, 'separator' +CONVERT(VARCHAR,@sepCount) ,'String',@PosY,0,12,'Separator ' + CONVERT(VARCHAR,@sepCount),'separator')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreatePropertyPlaceHolder Stored




CREATE PROCEDURE [dbo].[pNet_CreatePropertyPlaceHolder]( @ObjectName T_ObjectName,@PropertyName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreatePropertyPlaceHolder
--#CREATION
-- 07/08/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates place holder entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ObjectName: Name of object
-- @PropertyName: Property to take position as reference
-- @Above: PlaceHolder is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 26/05/2017- David Miralpeix
-- 27/02/2019- Carmen Change how to calculate the next number of placeholder from the last number that was given and not depending on the number of placeholder there.
----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
DECLARE @PosY as int

SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (Propertyname , LEN(PropertyName)-LEN('placeHolder') ) as int)),0)+1
FROM Objects_Properties
WHERE objectname=@objectname and typeid='placeHolder' and PropertyName like 'placeHolder%'
AND Isnumeric(RIGHT (Propertyname , LEN(PropertyName)-LEN('placeHolder') ))<>0

--select @sepCount=count(typeid) +1 from Objects_Properties where objectname=@objectname and typeid='placeHolder'
select @PosY=PositionY from Objects_Properties where objectname=@objectname and Propertyname=@PropertyName

begin Transaction

update [Objects_Properties] set PositionY=PositionY+1 where PositionY>=@PosY and objectname=@objectname

INSERT INTO [dbo].[Objects_Properties]([ObjectName],[PropertyName],[PositionY],[PositionX],Width,[DetachedFromDB],[Label] ,TypeId )
Values (@ObjectName, 'placeHolder' + CONVERT(VARCHAR,@sepCount) ,@PosY,0,12,1,'Place Holder ' + CONVERT(VARCHAR,@sepCount),'placeholder')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreatePropertySeparator Stored



CREATE PROCEDURE [dbo].[pNet_CreatePropertySeparator]( @ObjectName T_ObjectName,@PropertyName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreatePropertySeparator
--#CREATION
-- 07/08/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates separator entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ObjectName: Name of object
-- @PropertyName: Property to take position as reference
-- @Above: Separator is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 07/08/2016- David Miralpeix
-- 27/02/2019- Carmen Change how to calculate the next number of separator from the last number that was given and not depending on the number of separators there.
----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
DECLARE @PosY as int

--select @sepCount=count(typeid) +1 from Objects_Properties where objectname=@objectname and typeid='separator'
SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (Propertyname , LEN(PropertyName)-LEN('Separator') ) as int)),0)+1
FROM Objects_Properties
WHERE objectname=@objectname and typeid='separator' and PropertyName like 'separator%'
AND Isnumeric(RIGHT (Propertyname , LEN(PropertyName)-LEN('Separator') ))<>0



select @PosY=PositionY from Objects_Properties where objectname=@objectname and Propertyname=@PropertyName

begin Transaction

update [Objects_Properties] set PositionY=PositionY+1 where PositionY>=@PosY and objectname=@objectname

INSERT INTO [dbo].[Objects_Properties]([ObjectName],[PropertyName],[PositionY],[PositionX],Width,[DetachedFromDB],[Label] ,TypeId )
Values (@ObjectName, 'separator' + convert(varchar,@sepCount) ,@PosY,0,12,1,'Separator ' + convert(varchar,@sepCount),'separator')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateReportPropPlaceHolder Stored



CREATE PROCEDURE [dbo].[pNet_CreateReportPropPlaceHolder]( @ReportName T_ReportName,@ParamName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateReportPropPlaceHolder
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates separator entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ReportName: Name of report.
-- @ParamName: Property to take position as reference
-- @Above: Separator is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017 - Rubén Pardó
-- 27/02/2019- Carmen Change how to calculate the next number of placeholder from the last number that was given and not depending on the number of placeholder there.

----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
DECLARE @PosY as int

SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (ParamName , LEN(ParamName)-LEN('placeholder') ) as int)),0)+1
FROM Reports_Params
WHERE ReportName=@ReportName and typeid='placeholder' and ParamName like 'placeholder%'
AND Isnumeric(RIGHT (ParamName , LEN(ParamName )-LEN('placeholder') ))<>0
--select @sepCount=count(typeid) +1 from Reports_Params where ReportName=@ReportName and typeid='placeholder'
select @PosY=PositionY from Reports_Params where ReportName=@ReportName and ParamName=@ParamName

begin Transaction

update Reports_Params set PositionY=PositionY+1 where PositionY>=@PosY and ParamName=@ParamName

INSERT INTO [dbo].Reports_Params([ReportName],[ParamName],[PositionY],[PositionX],Width,[Label] ,TypeId )
Values (@ParamName, 'placeholder' +CONVERT(VARCHAR(50),@sepCount) ,@PosY,0,12,'Place Holder ' + CONVERT(VARCHAR(50),@sepCount),'placeholder')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateReportPropSeparator Stored



CREATE PROCEDURE [dbo].[pNet_CreateReportPropSeparator]( @ReportName T_ReportName,@ParamName T_propertyname,@Above bit)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CreateReportPropSeparator
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates separator entry in objects_properties Table based on curent
-- property position
--#PARAMETERS
-- @ReportName: Name of report.
-- @ParamName: Property to take position as reference
-- @Above: Separator is inserted above or below
--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017 - Rubén Pardo
-- 27/02/2019 Carmen Change how to calculate the next number of separator from the last number that was given and not depending on the number of separators there.
----------------------------------------------------------------------------------

BEGIN TRY

declare @sepCount int
declare @PosY as int
SELECT @sepCount=ISNULL(MAX(CAST(RIGHT (ParamName , LEN(ParamName)-LEN('Separator') ) as int)),0)+1
FROM Reports_Params
WHERE ReportName=@ReportName and typeid='separator' and ParamName like 'separator%'
AND Isnumeric(RIGHT (ParamName , LEN(ParamName )-LEN('Separator') ))<>0

--select @sepCount=count(typeid) +1 from Reports_Params where ReportName=@ReportName and typeid='separator'
select @PosY=PositionY from Reports_Params where ReportName=@ReportName and ParamName=@ParamName

begin Transaction

update Reports_Params set PositionY=PositionY+1 where PositionY>=@PosY and ParamName=@ParamName

INSERT INTO [dbo].Reports_Params([ReportName],[ParamName],[PositionY],[PositionX],Width,[Label] ,TypeId )
Values (@ParamName, 'separator' + CONVERT(VARCHAR,@sepCount) ,@PosY,0,12,'Separator ' + CONVERT(VARCHAR,@sepCount),'separator')

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_CreateWorkflowFromGraphic Stored

CREATE PROCEDURE [dbo].[pNet_CreateWorkflowFromGraphic]
@WorkflowId T_ProcessName,
@Version SMALLINT
-- =============================================
-- #AUTOR:
-- ceesi\jjrodriguez

-- #NAME:
--- pNet_CreateWorkflowGromGraphic
-- #CREATION:
-- 05/02/2018
-- #CLASIFICATION:
-- -010-GENERAL
-- #DESCRIPTION:
-- Creates workflows from a workflow graphic
-- #PARAMETERS:
-- @WorkflowId: Workflow graphic id
-- @Version: Workflow version
-- #OBSERVATIONS:
--
-- #CHANGES: Carmen 27/02/2019--Add the process to the WorkFlow area if it does not exist.
--
-- #EXAMPLE:
--
-- =============================================
AS
BEGIN TRY

DECLARE @Data XML
DECLARE @InitialId INT
DECLARE @MenuId NVARCHAR(50)
DECLARE @Descrip NVARCHAR(1000)
DECLARE @InitialSourceId INT


CREATE TABLE #Nodes (Id INT,FgId NVARCHAR(1000) COLLATE DATABASE_DEFAULT,NEdge BIT,NSource INT,NTarget INT,NTypeId SMALLINT,NType NVARCHAR(1000) COLLATE DATABASE_DEFAULT,Label NVARCHAR(1000) COLLATE DATABASE_DEFAULT,NodeId UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY CLUSTERED(Id))

CREATE TABLE #Relations (ChildId INT,ParentId INT,NType NVARCHAR(50) COLLATE DATABASE_DEFAULT,ParamName NVARCHAR(255) COLLATE DATABASE_DEFAULT, ParentParamName NVARCHAR(255) COLLATE DATABASE_DEFAULT, ParamValue NVARCHAR(1000) COLLATE DATABASE_DEFAULT PRIMARY KEY CLUSTERED(ChildId,ParamName))

-- Check workflowId
IF NOT EXISTS(
SELECT 1 FROM Workflows WHERE WorkflowId = @WorkflowId AND Version = @Version
) RAISERROR('ERROR. Invalid workflow/version.',12,1)


SELECT @Data = WorkflowData,@Descrip = Descrip FROM Workflows WHERE WorkflowId = @WorkflowId AND Version = @Version


INSERT INTO #Nodes(Id,FgId,NEdge,NSource,NTarget,NTypeId,NType,Label)
SELECT
N.V.value('../@id', 'int'),
N.V.value('../@fgid', 'NVARCHAR(1000)'),
ISNULL(N.V.value('@edge','bit'),0),
N.V.value('@source', 'int'),
N.V.value('@target', 'int'),
WNT.WorkflowNodeTypeId,
N.V.value('local-name(..)', 'NVARCHAR(1000)'),
N.V.value('../@label', 'NVARCHAR(1000)')
FROM
@Data.nodes('//mxCell') AS N(V)
OUTER APPLY (
SELECT WorkflowNodeTypeId
FROM Workflows_Nodes_Types
WHERE Descrip = N.V.value('local-name(..)', 'NVARCHAR(1000)')
) WNT
WHERE
N.V.value('local-name(..)', 'varchar(max)') NOT IN ('Layer')
--AND N.V.value('@id', 'varchar(max)') <> 1


INSERT INTO #Relations(ChildId,ParentId,ParamName,NType,ParentParamName,ParamValue)
SELECT
N.V.value('../@id', 'int'),
N.V.value('@parent', 'int'),
N.V.value('@childparam', 'NVARCHAR(1000)'),
N.V.value('@type', 'NVARCHAR(1000)'),
N.V.value('@parentparam', 'NVARCHAR(1000)'),
N.V.value('@defaultvalue', 'NVARCHAR(1000)')
FROM
@Data.nodes('//Parameter') AS N(V)

--select 'n',* from #nodes
--select 'r',* from #Relations

-- Checks

-- All vertex must have an Flexygo Id
IF EXISTS(
SELECT 1 FROM #Nodes WHERE NEdge = 0 AND FgId IS NULL AND NTypeId <> 6
) RAISERROR('ERROR. All vertex nodes have to been assigned to a process or an object.',12,1)

--All edges must have a source and a target
IF EXISTS(
SELECT 1 FROM #Nodes WHERE NEdge = 1 AND (Nsource IS NULL OR NTarget IS NULL)
) RAISERROR('ERROR. All edges must be connected.',12,1)

--Child workflows
IF EXISTS(
SELECT 1
FROM #Nodes N
LEFT JOIN Processes P ON N.FgId = P.ProcessName AND P.TypeId = 11
WHERE
N.Id <> 0 AND N.NEdge = 0 AND N.NType = 'Workflow'
AND P.ProcessName IS NULL
) RAISERROR('ERROR. Invalid workflow.',12,1)

--Child processes
IF EXISTS(
SELECT 1
FROM #Nodes N
LEFT JOIN Processes P ON N.FgId = P.ProcessName AND P.TypeId NOT IN (11,12)
WHERE
N.Id <> 0 AND N.NEdge = 0 AND N.NType = 'Process'
AND P.ProcessName IS NULL
) RAISERROR('ERROR. Invalid process.',12,1)


--Child decission
IF EXISTS(
SELECT 1
FROM #Nodes N
LEFT JOIN Processes P ON N.Fg

pNet_CreateWorkflowFromGraphic Stored

Id = P.ProcessName AND P.TypeId = 12
WHERE
N.Id <> 0 AND N.NEdge = 0 AND N.NType = 'Decission'
AND P.ProcessName IS NULL
) RAISERROR('ERROR. Invalid decission.',12,1)


--Double vertes onto same nodes (A->B + B->A)
IF EXISTS(
SELECT N.NSource,N.NTarget,NS.NSource,NS.NTarget
FROM
#Nodes N
INNER JOIN #Nodes NS ON N.NTarget = NS.NSource AND N.NSource = NS.NTarget

WHERE
N.NEdge = 1

) RAISERROR('ERROR. Two nodes only can have one relation.',12,1)

--Check initial node


SELECT @InitialId = MIN(N.Id)
FROM
#Nodes N
LEFT JOIN #Nodes NN ON N.NSource = NN.NTarget
WHERE
N.NSource IS NOT NULL
AND NN.NTarget IS NULL
GROUP BY
N.Id
HAVING
MIN(N.Id)=MAX(N.Id)

IF @InitialId IS NULL BEGIN
RAISERROR('ERROR. Initial node not found.',12,1)
END


BEGIN TRAN

--Create process if not exists
IF NOT EXISTS(
SELECT 1 FROM Processes WHERE ProcessName = @WorkflowId
) BEGIN

INSERT INTO Processes(ProcessName,TypeId,ClassId,ProcessDescrip,TargetId,Auditable)
SELECT @WorkflowId,11,'product',@Descrip,'current',1

END

--Add Process-Area
IF NOT EXISTS(
SELECT 1 FROM Workflows W
INNER JOIN Processes_Workflows_Areas A ON W.WorkflowId =A.ProcessName AND W.AreaId =A.WorkflowAreaId
WHERE W.WorkflowId = @WorkflowId AND W.AreaId IS NOT NULL
) BEGIN
INSERT INTO Processes_Workflows_Areas (WorkflowAreaId , ProcessName )
SELECT W.AreaId , W.WorkflowId FROM Workflows W
LEFT JOIN Processes_Workflows_Areas A ON W.WorkflowId =A.ProcessName AND W.AreaId =A.WorkflowAreaId
WHERE W.WorkflowId = @WorkflowId AND WorkflowAreaId IS NULL AND W.AreaId IS NOT NULL

END
--- End Add Process-Area


--Create Object-Process relation if initial node is object and relation does not exists
SELECT @InitialSourceId = NSource FROM #Nodes where Id = @InitialId



IF EXISTS(
SELECT 1 FROM #Nodes WHERE Id = @InitialSourceId AND NType = 'Object'
) BEGIN

IF NOT EXISTS(
SELECT 1
FROM #Nodes N
INNER JOIN Objects_Processes OP ON N.FgId = OP.ObjectName AND OP.ProcessName = @WorkflowId
WHERE
N.Id = @InitialSourceId
) BEGIN

SELECT TOP 1 @MenuId = MenuId FROM Menus
WHERE Descrip = (SELECT Descrip FROM Workflows WHERE WorkflowId = @WorkflowId AND Version=@Version)

IF @MenuId IS NULL BEGIN

SELECT @MenuId = NEWID()

INSERT INTO Menus(MenuId,Descrip,IconName)
SELECT @MenuId,LEFT(@Descrip,50),'noicon'

END

INSERT INTO Objects_Processes(ObjectName,ProcessName,MenuId,[Order],Active)
SELECT N.FgId,@WorkflowId,@MenuId,0,1
FROM #Nodes N
WHERE N.Id = @InitialSourceId


END
END


DELETE WRP
FROM Workflows_Relations_Parameters WRP
INNER JOIN Workflows_Relations WR ON WRP.RelationId = WR.RelationId
WHERE
WR.WorkflowName = @WorkflowId AND WR.Version = @Version

DELETE FROM Workflows_Nodes WHERE WorkflowName = @WorkflowId AND Version = @Version
DELETE FROM Workflows_Relations WHERE WorkflowName = @WorkflowId AND Version = @Version


INSERT INTO Workflows_Nodes(NodeId,WorkflowName,Version,NodeType,GraphId,ProcessName,ObjectName,EventName,ContinueAfterFail,InitialNode,NodeLabel)
SELECT
N.NodeId,
@WorkflowId,
@Version,
N.NTypeId,
N.Id,
CASE WHEN N.NType IN ('Process','Decission','Workflow') THEN N.FgId ELSE NULL END,
CASE WHEN N.NType IN ('Object') THEN N.FgId ELSE NULL END,
CASE WHEN N.NType IN ('Event') THEN N.FgId ELSE NULL END,
0,
CASE WHEN @InitialSourceId = N.Id THEN 1 ELSE 0 END,
N.Label
FROM #Nodes N

WHERE
N.NEdge = 0




INSERT INTO Workflows_Relations(RelationId,WorkflowName,Version,GraphId,ParentGuid,ChildGuid,ParentValue)
SELECT
N.NodeId,
@WorkflowId,
@Version,
N.Id,
NP.NodeId,
NC.NodeId,
CASE WHEN NP.NTypeId = 3 THEN N.Label ELSE NULL END

FROM
#Nodes N
INNER JOIN #Nodes NP ON N.NSource = NP.Id
INNER JOIN #Nodes NC ON

pNet_CreateWorkflowFromGraphic Stored

N.NTarget = NC.Id
WHERE
N.NEdge = 1


INSERT INTO Workflows_Relations_Parameters(RelationId,ChildParamName,ParentType,ParentNode,ParentParamName,DefaultValue)
SELECT
N.NodeId,R.ParamName,R.NType,
CASE R.NType WHEN 'Workflow' THEN @WorkflowId ELSE CONVERT(NVARCHAR(50),NP.NodeId) END,
R.ParentParamName,R.ParamValue
FROM
#Relations R
INNER JOIN #Nodes N ON R.ChildId = N.Id
INNER JOIN #Nodes NP ON R.ParentId = NP.Id



COMMIT TRAN


--SELECT * FROM #Nodes

DROP TABLE #Nodes

RETURN -1


END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_DeleteDependencies Stored

CREATE PROCEDURE [dbo].[pNet_DeleteDependencies](
@ObjectName T_ObjectName,
@PropertyName T_PropertyName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_DeleteDependencies
--#CREATION
-- 10/06/2021
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Delete the dependencies of a single property.
--#PARAMETERS
-- @ObjectName: The object name.
-- @PropertyName: The property name.

--#OBSERVATIONS
--
--#CHANGES
-- 10/06/2021- Fernando Fernández
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction

delete Objects_Properties_Dependencies where ObjectName=@ObjectName and PropertyName=@PropertyName

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_DeleteEmail Stored


CREATE PROCEDURE [dbo].[pNet_DeleteEmail]
@MessageId [dbo].[T_MailID]
AS

DELETE Mails_Objects Where Mails_Objects.MessageId = @MessageId
DELETE Mails Where Mails.MessageId = @MessageId


RETURN 1

pNet_DeleteLinkEmail Stored


CREATE PROCEDURE [dbo].[pNet_DeleteLinkEmail]
@MessageId NVARCHAR (250),
@ObjectName [dbo].[T_ObjectName],
@ObjectId NVARCHAR (250)
AS

DELETE Mails_Objects Where Mails_Objects.MessageId = @MessageId AND Mails_Objects.ObjectName = @ObjectName AND Mails_Objects.ObjectId = @ObjectId

RETURN 1

pNet_deleteNode Stored


CREATE PROCEDURE [dbo].[pNet_deleteNode]
@NodeId VARCHAR(50)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_deleteNode]
--#CREATION
-- 08/06/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Delete node from table Navigation_Nodes
--#PARAMETERS
-- @NodeId: The NodeId to delete
--#OBSERVATIONS
--
--#CHANGES
-- 08/06/2017- jjrodriguez
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @ChildrenId VARCHAR(50)

CREATE TABLE #Children(NodeId VARCHAR(50))

INSERT INTO #Children(NodeId)
SELECT NodeId FROM Navigation_Nodes WHERE ParentNodeId = @NodeId

WHILE EXISTS(
SELECT 1 FROM #Children
) BEGIN

SELECT TOP 1 @ChildrenId = NodeId FROM #Children

EXEC pNet_deleteNode @ChildrenId

DELETE FROM #Children WHERE NodeId = @ChildrenId

END

DELETE FROM Navigation_Nodes WHERE NodeId = @NodeId

RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_DeleteOfflineMenu Stored

CREATE PROCEDURE [dbo].[pNet_DeleteOfflineMenu]
@MenuId VARCHAR(50)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_DeleteOfflineMenu]
--#CREATION
-- 08/06/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Delete menu from table Offline_Menus
--#PARAMETERS
-- @MenuId: The MenuId to delete
--#OBSERVATIONS
--
--#CHANGES
-- 08/10/2019- Dmiralpeix
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @ChildrenId VARCHAR(50)

CREATE TABLE #Children(MenuId VARCHAR(50))

INSERT INTO #Children(MenuId)
SELECT MenuId FROM Offline_Menus WHERE ParentMenuId = @MenuId

WHILE EXISTS(
SELECT 1 FROM #Children
) BEGIN

SELECT TOP 1 @ChildrenId = MenuId FROM #Children

EXEC pNet_DeleteOfflineMenu @ChildrenId

DELETE FROM #Children WHERE MenuId = @ChildrenId

END

DELETE FROM Offline_Menus WHERE MenuId = @MenuId

RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_DeleteProcessDependencies Stored

CREATE PROCEDURE [dbo].[pNet_DeleteProcessDependencies](
@ProcessName T_ProcessName,
@PropertyName T_PropertyName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_DeleteDependencies
--#CREATION
-- 10/06/2021
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Delete the dependencies of a single property.
--#PARAMETERS
-- @ObjectName: The object name.
-- @PropertyName: The property name.

--#OBSERVATIONS
--
--#CHANGES
-- 10/06/2021- Fernando Fernández
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction

delete Processes_Params_Dependencies where ProcessName=@ProcessName and ParamName=@PropertyName

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_DeleteReportDependencies Stored

CREATE PROCEDURE [dbo].[pNet_DeleteReportDependencies](
@ReportName T_ReportName,
@PropertyName T_PropertyName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_DeleteDependencies
--#CREATION
-- 10/06/2021
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Delete the dependencies of a single property.
--#PARAMETERS
-- @ObjectName: The object name.
-- @PropertyName: The property name.

--#OBSERVATIONS
--
--#CHANGES
-- 10/06/2021- Fernando Fernández
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction

delete Reports_Params_Dependencies where ReportName=@ReportName and ParamName=@PropertyName

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_EnableMailSettings Stored

CREATE PROCEDURE [dbo].[pNet_EnableMailSettings]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_EnableMailSettings
--#CREATION
-- 01/01/2020
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Enables Mail navigation Node and Mail notification Cron
--#PARAMETERS

--#OBSERVATIONS
--
--#CHANGES
-- 01/01/2020- David MiralpeiX
----------------------------------------------------------------------------------

BEGIN TRY

begin Tran

update Navigation_Nodes set Enabled=-1 where NodeId='CF0DB1F2-FA16-49C4-ADDD-81A3D173081C'

Update Jobs set Enabled=-1 where Jobs.JobName='UpdateMailNoticeBadge'


commit
RETURN 1

END TRY

BEGIN CATCH

Rollback
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ERPAhoraIntegration Stored

CREATE PROCEDURE [dbo].[pNet_ERPAhoraIntegration]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_ERPAhoraIntegration]
--#CREATION
-- 07/08/2018 - rpardo
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Update config database to integrate with Ahora ERP Freeware
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY
IF (select [SettingValue] from Settings WHERE [SettingName]='AfterLoginProcess') = 'AfterLoginERPAhoraFreeware' BEGIN
RAISERROR('The integration has already been made',12,1)
END ELSE BEGIN

BEGIN TRAN
update aspnetusers set Reference='0',SubReference='0' where username='admin'

UPDATE [Documents_Objects_Config_Types] SET active=1 WHERE [TypeId]='ahoraerp'
UPDATE [Root_Path_Types] SET [Active] = 1 WHERE [TypeId]='FullPath'

update Objects set Active=1 where ObjectName in ('AHORA_Documento','AHORA_Documento_Documento','AHORA_Documento_Tabla','AHORA_Imagen','AHORA_Documentos','AHORA_Documentos_Documento','AHORA_Documentos_Tablas','AHORA_Imagenes')

UPDATE [Settings] SET [Active]=1, [SettingValue]='AfterLoginERPAhoraFreeware' WHERE [SettingName]='AfterLoginProcess'
-- Avoid deleting ahora_sesion
--UPDATE [Settings] SET [Active]=1, [SettingValue]='AfterLogoffERPAhoraFreeware' WHERE [SettingName]='AfterLogoffProcess'

update Objects_Properties
set TypeId='dbcombo',
Label='Empleado',
SQLSentence='SELECT IdEmpleado,Nombre FROM VCombo_Empleados_Activos ORDER BY Nombre',
SQLValueField='IdEmpleado',
SQLDisplayField='Nombre',
IsRequired=1,
ConnStringId='DataConnectionString',
PositionY=-1,
LabelStyle='font-weight:bold'
where ObjectName='sysUser' and PropertyName='Reference'

update Objects_Properties
set TypeId='dbcombo',
Label='Delegación',
SQLSentence='Select IdDelegacion,Nombre from Delegaciones order by Nombre',
SQLValueField='IdDelegacion',
SQLDisplayField='Nombre',
IsRequired=1,
ConnStringId='DataConnectionString',
PositionY=-1,
LabelStyle='font-weight:bold'
where ObjectName='sysUser' and PropertyName='SubReference'

update Objects_Properties
set PositionY=-2
where ObjectName='sysUser' and PropertyName='separator5'

update Objects_Properties set PositionY=PositionY+2 where ObjectName='sysUser'

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='Email') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'Email',2,1,N'Cargar Email del empleado',N'select E_Mail from Empleados_Datos where convert(varchar(50),IdEmpleado)=''{{Reference}}''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'DataConnectionString')
END

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='Name') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'Name',3,1,N'Cargar Nombre del empleado',N'select Nombre from Empleados_Datos where convert(varchar(50),IdEmpleado)=''{{Reference}}''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL

pNet_ERPAhoraIntegration Stored

,N'DataConnectionString')
END

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='NickName') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'NickName',5,1,N'Cargar Nombre del empleado',N'select Nombre from Empleados_Datos where convert(varchar(50),IdEmpleado)=''{{Reference}}''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'DataConnectionString')
END

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='PhoneNumber') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'PhoneNumber',6,1,N'Cargar teléfono del empleado',N'select TelefonoTrabajo from Empleados_Datos where convert(varchar(50),IdEmpleado)=''{{Reference}}''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'DataConnectionString')
END

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='SubReference') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'SubReference',1,1,N'Filtrar delegación por el empleado seleccionado.',NULL,N'Select Delegaciones.IdDelegacion,Delegaciones.Nombre from Delegaciones inner join Empresas_Empleados E on Delegaciones.IdDelegacion=E.IdDelegacion and Delegaciones.IdEmpresa=E.IdEmpresa where E.IdEmpleado={{Reference}} order by Nombre',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'DataConnectionString')
END

if not exists(Select 1 from [Objects_Properties_Dependencies] where [ObjectName]='sysUser' and [PropertyName] = 'Reference' and [DependingPropertyName]='SurName') BEGIN
INSERT INTO [Objects_Properties_Dependencies]([ObjectName],[PropertyName],[DependingPropertyName],[Order],[Active],[Descrip],[SQLValue],[SQLComboSentence],[SQLComboFilter],[SQLEnabled],[EnabledValues],[DisabledValues],[SQLVisible],[VisibleValues],[HiddenValues],[SQLClass],[SQLRequired],[RequiredValues],[NotRequiredValues],[ConnStringId])
VALUES(N'sysUser',N'Reference',N'SurName',4,1,N'Cargar Apellidos del empleado',N'select Apellidos from Empleados_Datos where convert(varchar(50),IdEmpleado)=''{{Reference}}''',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'DataConnectionString')
END
COMMIT

select 'Please, check that ERP database contains <b>pCRM_CreaAhoraSesion</b> and <b>pCRM_EliminaAhoraSesion</b> procedures' as WarningMessage

END

RETURN -1

END TRY
BEGIN CATCH

IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_FinishDocument Stored

CREATE PROCEDURE [dbo].[pNet_FinishDocument]
@DocumentId nvarchar(250)
AS

UPDATE [dbo].[Documents_Versions] SET InProgress = 0 WHERE DocGuid=@DocumentId


RETURN 1

pNet_GenerateCultureEntries Stored


CREATE PROCEDURE [dbo].[pNet_GenerateCultureEntries](
@CultureId nvarchar(8),
@Origin int
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_GenerateCultureEntries
--#CREATION
-- 07/05/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Builds translation entries for given culture
-- Allows to establish origin to only translate system or project objects
-- Use origin=-1 to translate all
--#PARAMETERS
-- @CultureId: Culture
-- @Origin: Origin. Use -1 for all

--#OBSERVATIONS
--
--#CHANGES
-- 07/05/2017- David Miralpeix
-- 24/05/2018- David Miralpeix
-- 27/11/2018- David Miralpeix
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction


--Properties
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Properties' as Area, label,'' from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='Properties' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Properties' as Area, placeholder,'' from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='Properties' WHERE len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Properties' as Area, IsRequiredMessage,'' from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='Properties' WHERE len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Properties' as Area, RegExpText,'' from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='Properties' WHERE len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Properties' as Area, Label,'' from Objects_Templates_Groups t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='Properties' WHERE len(t.Label) >0 and tr.Original is null and t.OriginId=@Origin


--Objects
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Objects' as Area,Descrip ,'' from Objects t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Objects' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Objects' as Area,ParsedDescrip ,'' from Objects t left join Translate tr on tr.CultureId=@CultureId and t.ParsedDescrip=tr.Original AND tr.Area ='Objects' where len(t.ParsedDescrip) >0 and tr.Original is null and t.OriginId=@Origin

--Nodes
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
SELECT DISTINCT @CultureId, 'Nodes' AS Area,title ,'' FROM navigation_Nodes t LEFT JOIN Translate tr ON tr.CultureId=@CultureId AND t.title=tr.Original AND tr.Area ='Nodes' where len(t.title) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Nodes' as Area,Descrip ,'' from Master_Tables t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Nodes' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

--Offline navigation Menus
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @C

pNet_GenerateCultureEntries Stored

ultureId, 'Nodes' as Area,Descrip ,'' from Offline_Menus t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Nodes' WHERE len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Nodes' as Area,Title ,'' from Offline_Menus t left join Translate tr on tr.CultureId=@CultureId and t.Title=tr.Original AND tr.Area ='Nodes' WHERE len(t.Title) >0 and tr.Original is null and t.OriginId=@Origin

--Menus
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Menus' as Area,Descrip ,'' from Menus t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Menus' WHERE len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

--Modules
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Modules' as Area,Title ,'' from Modules t LEFT join Translate tr on tr.CultureId=@CultureId and t.title=tr.Original AND tr.Area ='Modules' where len(t.title) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Modules' as Area,Descrip ,'' from Modules t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Modules' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

--Page Titles
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Modules' as Area,Title ,'' from Offline_Pages t LEFT join Translate tr on tr.CultureId=@CultureId and t.title=tr.Original AND tr.Area ='Modules' where len(t.title) >0 and tr.Original is null and t.OriginId=@Origin

--Buttons
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Buttons' as Area,t.[Text] ,'' from Toolbars_Buttons t left join Translate tr on tr.CultureId=@CultureId and t.[Text]=tr.Original AND tr.Area ='Buttons' WHERE len(t.[Text]) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Buttons' as Area,Tooltip ,'' from Toolbars_Buttons t left join Translate tr on tr.CultureId=@CultureId and t.Tooltip=tr.Original AND tr.Area ='Buttons' where len(t.Tooltip) >0 and tr.Original is null and t.OriginId=@Origin

--Reports
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Reports' as Area,t.ReportDescrip ,'' from Reports t left join Translate tr on tr.CultureId=@CultureId and t.[ReportDescrip]=tr.Original AND tr.Area ='Reports' where len(t.[ReportDescrip]) >0 and tr.Original is null and t.OriginId=@Origin

--Process
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Process' as Area,t.ConfirmText ,'' from Processes t left join Translate tr on tr.CultureId=@CultureId and t.ConfirmText=tr.Original AND tr.Area ='Process' where len(t.ConfirmText) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Process' as Area,t.ProcessDescrip ,'' from Processes t left join Translate tr on tr.CultureId=@CultureId and t.ProcessDescrip=tr.Original AND tr.Area ='Process' where len(t.ProcessDescrip) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
select Distinct @CultureId, 'Process' as Area,t.RunButtonText ,'' from Processes t left join Translate tr on tr.CultureId=@CultureId and t.RunButtonText=tr.Original AND tr.Area ='Process' where len(t.RunButtonText) >0 and tr.Original is null and t.OriginId=@Origin


--Process Params
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])

pNet_GenerateCultureEntries Stored

Select Distinct @CultureId, 'ProcessParams' as Area, label,'' from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='ProcessParams' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ProcessParams' as Area, placeholder,'' from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='ProcessParams' where len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ProcessParams' as Area, IsRequiredMessage,'' from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='ProcessParams' where len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ProcessParams' as Area, RegExpText,'' from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='ProcessParams' where len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin


-- Report Params
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ReportsParams' as Area, label,'' from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='ReportsParams' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ReportsParams' as Area, placeholder,'' from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='ReportsParams' where len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ReportsParams' as Area, IsRequiredMessage,'' from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='ReportsParams' where len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'ReportsParams' as Area, RegExpText,'' from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='ReportsParams' where len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin

-- Filter Names
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'FilterNames' as Area, Name,'' from Objects_Search t left join Translate tr on tr.CultureId=@CultureId and t.Name=tr.Original AND tr.Area ='FilterNames' where len(t.Name) >0 and tr.Original is null and t.OriginId=@Origin

INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'FilterNames' as Area, Title,'' from Objects_Presets t left join Translate tr on tr.CultureId=@CultureId and t.Title=tr.Original AND tr.Area ='FilterNames' where len(t.Title) >0 and tr.Original is null and t.OriginId=@Origin


-- Template Names
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'TemplateNames' as Area, Descrip,'' from Objects_Templates t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='TemplateNames' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'TemplateNames' as Area, Descrip,'' from Objects_Templates t left join Translate tr on tr.CultureI

pNet_GenerateCultureEntries Stored

d=@CultureId and t.Descrip=tr.Original AND tr.Area ='TemplateNames' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

-- Templates and Offline Pages
exec PNet_GenerateCultureEntries_Templates @Origin,@cultureId

-- Exceptions
INSERT INTO [dbo].[Translate] ([CultureId],[Area],[Original],[Text])
Select Distinct @CultureId, 'Exceptions' as Area, MSG,'' from Exceptions t left join Translate tr on tr.CultureId=@CultureId and t.MSG=tr.Original AND tr.Area ='Exceptions' where len(t.MSG) >0 and tr.Original is null and t.OriginId=@Origin

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

PNet_GenerateCultureEntries_Templates Stored

CREATE PROCEDURE PNet_GenerateCultureEntries_Templates
@OriginID int,
@CultureId T_CultureId
AS
BEGIN TRY
----------------------------------------------------------------------------------
--#NAME
-- PNet_GenerateCultureEntries_Templates
--#CREATION
-- 24/01/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
--- Create translation entries for a specific culture of the object templates of a given originId
-- If the originId=-1
--#PARAMETERS
-- @CultureId: Culture
-- @Origin: Origin. Use -1 for all

--#OBSERVATIONS
-- Find the words enclosed between {{translate | Y }}
--#CHANGES
--
-- 24/01/2019- Carmen
--#EXAMPLE
--DECLARE @OriginID int=1, @CultureId T_CultureId ='es-Es'
--EXEC PNet_GenerateCultureEntries_Templates @OriginID,@CultureId

----------------------------------------------------------------------------------



INSERT INTO Translate (CultureId , Area, Original , Text )
SELECT DISTINCT T1.CultureId , T1.Area, T1.descrip ,''
FROM [fNet_TestCultureEntries_Templates] (@OriginId,@cultureid )T1
LEFT JOIN Translate T2 ON T1.Descrip =T2.Original AND T2.CultureId =T1.CultureId AND T2.Area =T1.Area
WHERE T2.Original IS NULL






RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_GetExternalToken Stored

CREATE PROCEDURE [dbo].[pNet_GetExternalToken]
(
@TokenType nvarchar(128),
@AppName nvarchar(512)
)
AS

Select ExternalUrl from Flexygo_Connectors where AppName=@AppName

select top 1 Id,TokenType,AccessToken,RefreshToken,RefreshData,Scope,ExpiryDate,InsertedDate,AppName from AspNetUsers_Tokens
where TokenType=@TokenType and AppName=@AppName and ExpiryDate > getdate()
Order By InsertedDate Desc

RETURN 1

pNet_getNotificationBadgeCount Stored

CREATE PROCEDURE [dbo].[pNet_getNotificationBadgeCount]
@UserId T_userId ,
@currentReference nvarchar(50)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_getNotificationBadgeCount
--#CREATION
-- 12/12/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Gest active notification count for given user
--#PARAMETERS
-- @UserId: Sets read for that user if it is a notice for all Users using UserId
-- @currentReference Sets read for that user if it is a notice for all Users using Reference
--#OBSERVATIONS
--
--#CHANGES
--30/04/2019 David Miralpeix Añadido opción de filtrar por current Reference
---------------------------------------------------------------------------------
BEGIN TRY


BEGIN


select Count(N.NoticeId)
from Notices N
left join Notices_Users U on N.NoticeId=U.NoticeId and (u.UserId=@UserId or U.CurrentReference=@currentReference)
where ((N.AllUsers=1 and U.NoticeId is null ) OR ( U.UserId=@UserId and IsRead=0) OR( U.CurrentReference=@currentReference and IsRead=0))
and N.ReminderTime < getdate() and N.ExpiryTime>getdate()

END

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_GetPendingPushMessages Stored


CREATE PROCEDURE [dbo].[pNet_GetPendingPushMessages]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_GetPendingPushMessages
--#CREATION
-- 12/12/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Check message as Sent
--#PARAMETERS
-- @UserId: Sets read for that user if it is a notice for all Users using UserId
-- @currentReference Sets read for that user if it is a notice for all Users using Reference
--#OBSERVATIONS
--
--#CHANGES
---------------------------------------------------------------------------------
BEGIN TRY


BEGIN


Select Notices.*,
AspNetUsers_Devices.UserId, AspNetUsers.Reference as CurrentReference, AspNetUsers_Devices.[Platform], AspNetUsers_Devices.DeviceToken, Notices_Users.Id as NoticeUserId
from Notices
inner join Notices_Users on Notices.NoticeId = Notices_Users.NoticeId and IsSent=0 and Notices_Users.Error=0
inner join AspNetUsers_Devices on Notices_Users.UserId = AspNetUsers_Devices.UserId and
(
(Notices.MethodName='pushweb' and AspNetUsers_Devices.[Platform] = 'Web') OR
(Notices.MethodName='pushmobile' and AspNetUsers_Devices.[Platform] in ('ios','android')) OR
(Notices.MethodName='push')
)
inner join AspNetUsers on AspNetUsers_Devices.UserId=AspNetUsers.Id
where AllUsers=0 and Notices.MethodName in ('pushweb','pushmobile','push')
and GETDATE() between Notices.ReminderTime and Notices.ExpiryTime
UNION
Select Notices.*,
AspNetUsers_Devices.UserId, AspNetUsers.Reference as CurrentReference, AspNetUsers_Devices.[Platform], AspNetUsers_Devices.DeviceToken , null as NoticeUserId
from Notices
inner join AspNetUsers_Devices on
(
(Notices.MethodName='pushweb' and AspNetUsers_Devices.[Platform] = 'Web') OR
(Notices.MethodName='pushmobile' and AspNetUsers_Devices.[Platform] in ('ios','android')) OR
(Notices.MethodName='push')
)
inner join AspNetUsers on AspNetUsers_Devices.UserId=AspNetUsers.Id
where AllUsers=1 and AllUsersIsSent=0 and Notices.MethodName in ('pushweb','pushmobile','push')
and GETDATE() between Notices.ReminderTime and Notices.ExpiryTime and Notices.Error=0


END

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_GetTokens Stored

CREATE PROCEDURE [dbo].[pNet_GetTokens]
AS
select Id,TokenType,AccessToken,RefreshToken,RefreshData,Scope,ExpiryDate,InsertedDate,AppName from AspNetUsers_Tokens where TokenType='flexygo'
RETURN 1

pNet_GetWebHookOrigins Stored

CREATE PROCEDURE [dbo].[pNet_GetWebHookOrigins]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CheckWebHook
--#CREATION
-- 16/11/2020
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Check if an wenhook is authorized and returns it to controller
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

select Origin from WebHooks

RETURN 1
END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_getWorkflowStyle Stored

CREATE PROCEDURE [dbo].[pNet_getWorkflowStyle]
@WorkflowId [dbo].[T_ProcessName],
@Version SMALLINT
-- =============================================
-- #AUTOR:
-- ceesi\jjrodriguez
-- #NAME:
--- pNet_getWorkflowStyle
-- #CREATION:
-- 20/02/2018
-- #CLASIFICATION:
-- -010-GENERAL
-- #DESCRIPTION:
-- Set the style to be used in the graphical representation for a set of nodes of a workflow
-- #PARAMETERS:
-- @WorkflowId: Workflow graphic id
-- @Version: Workflow version
-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
--
-- =============================================
AS
BEGIN TRY

DECLARE @Data XML

CREATE TABLE #Nodes (Id INT,FgId NVARCHAR(1000) COLLATE DATABASE_DEFAULT,NEdge BIT,NSource INT,NTarget INT,NType NVARCHAR(1000) COLLATE DATABASE_DEFAULT,Style NVARCHAR(1000) COLLATE DATABASE_DEFAULT PRIMARY KEY CLUSTERED(Id))

SELECT @Data = WorkflowData FROM Workflows WHERE WorkflowId = @WorkflowId AND Version = @Version

INSERT INTO #Nodes(Id,FgId,NEdge,NSource,NTarget,NType,Style)
SELECT
N.V.value('@id', 'int'),
N.V.value('@fgid', 'NVARCHAR(1000)'),
ISNULL(N.V.value('@edge', 'bit'),0),
N.V.value('@source', 'int'),
N.V.value('@target', 'int'),
N.V.value('local-name(.)', 'NVARCHAR(1000)'),
C.V.value('@style', 'NVARCHAR(1000)')
FROM
@Data.nodes('/mxGraphModel/root//*') AS N(V)
OUTER APPLY N.V.nodes('mxCell') C(V)
WHERE
N.V.value('local-name(.)', 'varchar(max)') NOT IN ('mxCell','mxGeometry','Label')
AND N.V.value('@id', 'varchar(max)') <> 1

--SELECT 'N1',* FROM #NODES

UPDATE N SET N.Style =
CASE WHEN ACT.Version <> STD.Version THEN
'customized-workflow'
ELSE
N.Style
END
FROM
#Nodes N
CROSS APPLY (--Active workflows
SELECT TOP 1 Version
FROM Workflows
WHERE WorkflowId = N.FgId AND Active = 1
) ACT
CROSS APPLY (--Standard workflows
SELECT TOP 1 Version
FROM Workflows
WHERE WorkflowId = N.FgId AND OriginId < 2
) STD
WHERE
N.NType ='Workflow'



--SELECT 'N2',* FROM #Nodes

SELECT FgId WorkflowId,Style
FROM #Nodes

DROP TABLE #Nodes

RETURN -1


END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

PNet_Gipe_CopyWorkFlows Stored

CREATE PROCEDURE [dbo].[PNet_Gipe_CopyWorkFlows]
@ProcessNameO T_ProcessName ,
@ProcessNameD T_ProcessName,
@WorkFlowAreaId nvarchar(50)=NULL,
@Description nvarchar(max) ,
@WordSearch nvarchar(50) =NULL,
@WordRpl nvarchar(50)=NULL,
@CopyParams bit=0
-- =============================================
-- #AUTOR:
-- Carmen

-- #NAME:
--- PNet_Gipe_CopyWorkFlows
-- #CREATION:
-- 17/08/2018
-- #CLASIFICATION:
-- -010-GENERAL
-- #DESCRIPTION:
-- Copy the Workflow from the processnameO to processnameD , if the processnameD not exists en processes table, we copy the processnameO to processnameD and their parameters
-- #PARAMETERS:
-- @ProcessnameO: WorkFlowId and Processname Source
-- @ProcessnameD: WorkFlowId and Processname target
-- @WorkFlowAreaId: Area Code
-- @Description: Description of the workflow target
-- @WordSearch: Can be null, when we want replace a word inside WorkflowData this parameter is the word of search
-- @WordRpl: Can be null, when we want replace a word inside WorkflowData this parameter is the word of replace
-- @CopyParams: If we want copy the process params source to process target
-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
--
/*@ProcessNameO T_ProcessName='EM_Customers_Invoices_Lines_Block' ,
@ProcessNameD T_ProcessName ='EM_Customers_Invoices_Lines_Cancel',
@WorkFlowAreaId nvarchar(50)='002.002.005',
@Description nvarchar(max) ='Customes ->Invoices Lines ->Cancel',
@WordSearch nvarchar(50) ='Block',
@WordRpl nvarchar(50)='Cancel',
@CopyParams bit=0
EXEC PNet_Gipe_CopyWorkFlows @processnameO,@ProcessnameD, @WorkFlowAreaId,@Description,@WordSearch, @WordRpl,@CopyParams

*/
--
-- =============================================
AS
BEGIN TRY
DECLARE @sqlInsert nvarchar(max), @sql nvarchar(max), @Graphic xml ,@WorkData nvarchar(max)
IF NOT EXISTS (SELECT * FROM Workflows WHERE WorkflowId =@ProcessNameO )
RAISERROR ('The source process isn''t exist',12,1)


IF @WordSearch is null BEGIN
SELECT @Graphic =WorkflowData FROM Workflows WHERE WorkflowId =@ProcessNameO

SELECT TOP 1 V.Z.value('@description','nvarchar(max)') , V.Z.value('@fgid','nvarchar(max)')
FROM @Graphic.nodes('mxGraphModel/root/Workflow') V(Z)


SET @Graphic.modify('
replace value of ( mxGraphModel/root/Workflow/@description)[1]
with sql:variable ("@description")

');


SET @Graphic.modify('
replace value of ( mxGraphModel/root/Workflow/@fgid)[1]
with sql:variable ("@ProcessNameD")

');

SELECT @WorkData =CAST( @graphic as nvarchar(max))
END ELSE BEGIN
SELECT @WorkData =RePLACE (WorkflowData,@WordSearch, @WordRpl) FROM Workflows WHERE WorkflowId =@ProcessNameO

END

BEGIN TRAN

IF NOT EXISTS (SELECT * FROM Workflows WHERE WorkflowId =@ProcessNameD ) BEGIN
IF NOT EXISTS (SELECT * FROM Processes WHERE ProcessName =@ProcessNameD ) BEGIN
EXEC PNet_CopyProcessToNew @ProcessNameO ,@ProcessNameD

END ELSE BEGIN

IF @CopyParams <>0 BEGIN

EXEC pNet_CopyProcessParamsToDestProcess @ProcessNameO,@ProcessNameD
END
SELECT @sqlInsert = FieldsString FROM dbo.fNet_ReturnTableFieldsToString ('WorkFlows', 'WorkFlowId,AreaId,Descrip,WorkFlowData')
SELECT @sql ='INSERT INTO WorkFlows (WorkFlowId,AreaId,Descrip,WorkFlowData,'+ @sqlInsert +')
SELECT '''+ @ProcessNameD +''','''+ @WorkFlowAreaId +''','''+ @description +''', '''+ @WorkData +''','+ @sqlInsert + '
FROM Workflows WHERE WorkflowId =''' + @ProcessNameO +''''

EXEC (@sql)

END
END ELSE BEGIN

UPDATE Workflows SET WorkflowData =@WorkData, Descrip =@description
WHERE WorkflowId =@ProcessNameD
END


COMMIT TRAN
RETURN -1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)

PNet_Gipe_CopyWorkFlows Stored


SET @CatchError=dbo.funPrintError (ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN

END CATCH

PNet_Gipe_Processes_Areas_Associate Stored


CREATE PROCEDURE [dbo].[PNet_Gipe_Processes_Areas_Associate](
@WorkFlowAreaId nvarchar(50),
@ProcessName T_Processname
)
AS
----------------------------------------------------------------------------------
--#NAME
-- PNet_Gipe_Processes_Areas_Associate
--#CREATION
-- 17/09/2018 - Admin Admin
--#CLASIFICATION
-- Flexygo/MyStoreds
--#DESCRIPTION
-- Associates the selected area with the process
--#PARAMETERS
-- @WorkFlowAreaId:Area Identifier in Workflow_Areas
-- @ProcessName: Process Name
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN

IF ISNULL(@WorkFlowAreaId,'')<>'' BEGIN
INSERT INTO Processes_Workflows_Areas (ProcessName, WorkFlowAreaId)
SELECT K.Processname , K.WorkFlowAreaId
FROM (Values (@ProcessName, @WorkFlowAreaId )) AS K(Processname, WorkFlowAreaId)
LEFT JOIN Processes_Workflows_Areas T ON K.ProcessName=T.ProcessName and K.WorkFlowAreaId =T.WorkFlowAreaId
WHERE T.WorkflowAreaId IS NULL

END

COMMIT

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ImportMailChimpContacts Stored

CREATE PROCEDURE [dbo].[pNet_ImportMailChimpContacts](
@Contacts [Tbl_MailChimp_Contacts] readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ImportMailChimpContacts
--#CREATION
-- 12/11/2020
--#CLASIFICATION
-- Flexygo/MailChimp
--#DESCRIPTION
-- A collection of contacts from MailChimp is saved in MailChimp_Contacts
--#PARAMETERS
-- @Contacts: contacts data obtained from MailChimp
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------

BEGIN TRY
UPDATE MailChimp_Contacts SET
Fname=c.Fname ,LName=c.LName,Addr1=c.Addr1,Addr2=c.Addr2,City=c.City,State=c.State,Zip=c.Zip,Country=c.Country,Status=c.Status,Language=c.Language,Vip=c.Vip
FROM @Contacts c INNER JOIN MailChimp_Contacts mc ON c.EmailAddress =mc.EmailAddress
WHERE mc.Fname<>c.Fname OR mc.LName<>c.LName OR mc.Addr1<>c.Addr1 OR mc.Addr2<>c.Addr2 OR
mc.City<>c.City OR mc.state<>c.State OR mc.Zip<>c.Zip OR mc.Country<>c.Country OR mc.Status<>c.Status OR mc.Language<>c.Language OR mc.Vip<>c.Vip

INSERT INTO MailChimp_Contacts (EmailAddress,ObjectName,ObjectId,Fname,LName,Addr1,Addr2,City,State,Zip,Country,Status,Language,Vip,IsUpload)
SELECT C.EmailAddress,NULL,NULL,C.Fname,C.LName,C.Addr1,C.Addr2,C.City,C.State,C.Zip,C.Country,C.Status,C.Language,C.Vip,1
FROM @Contacts C
LEFT JOIN MailChimp_Contacts ON MailChimp_Contacts.EmailAddress = C.EmailAddress
WHERE MailChimp_Contacts.EmailAddress IS NULL

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ImportSecurityRole Stored

CREATE PROCEDURE [dbo].[pNet_ImportSecurityRole] (
@OriginRoleId AS T_RoleId,
@DestinationRoleId AS T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CloneSecurityRole
--#CREATION
-- 14/03/2019
--#CLASIFICATION
-- Framework/systemSecurity
--#DESCRIPTION
-- Clone Security Role
--#PARAMETERS
-- @OriginRoleId Origin Role,
-- @DestinationRoleId Destination Role
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY
BEGIN TRAN

DECLARE @Count int = 0

INSERT INTO [dbo].[Security_Master_Tables_Roles] ([TableName], [RoleId], [CanView], [CanUpdate], [CanDelete], [CanInsert], [CanPrint])
SELECT [Origin].[TableName], @DestinationRoleId, [Origin].[CanView], [Origin].[CanUpdate], [Origin].[CanDelete], [Origin].[CanInsert], [Origin].[CanPrint]
FROM (SELECT [TableName], [CanView], [CanUpdate], [CanDelete], [CanInsert], [CanPrint] FROM [dbo].[Security_Master_Tables_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [TableName] FROM [dbo].[Security_Master_Tables_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[TableName] = [Destination].[TableName]
WHERE [Destination].[TableName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Modules_Roles] ([ModuleName], [RoleId], [CanView], [ViewFilter])
SELECT [Origin].[ModuleName], @DestinationRoleId, [Origin].[CanView], [Origin].[ViewFilter]
FROM (SELECT [ModuleName], [CanView], [ViewFilter] FROM [dbo].[Security_Modules_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [ModuleName] FROM [dbo].[Security_Modules_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[ModuleName] = [Destination].[ModuleName]
WHERE [Destination].[ModuleName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Navigation_Nodes_Roles] ([NodeId], [RoleId], [CanView])
SELECT [Origin].[NodeId], @DestinationRoleId, [Origin].[CanView]
FROM (SELECT [NodeId], [CanView] FROM [dbo].[Security_Navigation_Nodes_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [NodeId] FROM [dbo].[Security_Navigation_Nodes_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[NodeId] = [Destination].[NodeId]
WHERE [Destination].[NodeId] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Processes_Roles] ([ObjectName], [ProcessName], [RoleId], [CanView], [ViewFilter])
SELECT [Origin].[ObjectName], [Origin].[ProcessName], @DestinationRoleId, [Origin].[CanView], [Origin].[ViewFilter]
FROM (SELECT [ObjectName], [ProcessName], [CanView], [ViewFilter] FROM [dbo].[Security_Objects_Processes_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [ObjectName],[ProcessName] FROM [dbo].[Security_Objects_Processes_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName] AND [Origin].[ProcessName] = [Destination].[ProcessName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Properties_Roles] ([ObjectName], [PropertyName], [RoleId], [CanView], [CanEdit])
SELECT [Origin].[ObjectName], [Origin].[PropertyName], @DestinationRoleId, [Origin].[CanView], [Origin].[CanEdit]
FROM (SELECT [ObjectName], [PropertyName], [CanView], [CanEdit] FROM [dbo].[Security_Objects_Properties_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [ObjectName],[PropertyName] FROM [dbo].[Security_Objects_Properties_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName] AND [Origin].[PropertyName] = [Destination].[PropertyName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [

pNet_ImportSecurityRole Stored

dbo].[Security_Objects_Roles] ([ObjectName], [RoleId], [CanView], [ViewFilter], [CanViewCollection], [ViewFilterCollection], [CanInsert], [InsertFilter], [CanEdit], [EditFilter], [CanDelete], [DeleteFilter], [CanPrint])
SELECT [Origin].[ObjectName], @DestinationRoleId, [Origin].[CanView], [Origin].[ViewFilter], [Origin].[CanViewCollection], [Origin].[ViewFilterCollection], [Origin].[CanInsert], [Origin].[InsertFilter], [Origin].[CanEdit], [Origin].[EditFilter], [Origin].[CanDelete], [Origin].[DeleteFilter], [Origin].[CanPrint]
FROM (SELECT [ObjectName], [CanView], [ViewFilter], [CanViewCollection], [ViewFilterCollection], [CanInsert], [InsertFilter], [CanEdit], [EditFilter], [CanDelete], [DeleteFilter], [CanPrint] FROM [dbo].[Security_Objects_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [ObjectName] FROM [dbo].[Security_Objects_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Templates_Roles] ([TemplateId], [RoleId], [CanView])
SELECT [Origin].[TemplateId], @DestinationRoleId, [Origin].[CanView]
FROM (SELECT [TemplateId], [CanView] FROM [dbo].[Security_Objects_Templates_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [TemplateId] FROM [dbo].[Security_Objects_Templates_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[TemplateId] = [Destination].[TemplateId]
WHERE [Destination].[TemplateId] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Pages_Modules_Roles] ([PageName], [ModuleName], [RoleId], [CanView])
SELECT [Origin].[PageName], [Origin].[ModuleName], @DestinationRoleId, [Origin].[CanView]
FROM (SELECT [PageName],[ModuleName], [CanView] FROM [dbo].[Security_Pages_Modules_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [PageName],[ModuleName] FROM [dbo].[Security_Pages_Modules_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[PageName] = [Destination].[PageName] AND [Origin].[ModuleName] = [Destination].[ModuleName]
WHERE [Destination].[PageName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Pages_Roles] ([PageName], [RoleId], [Canview])
SELECT [Origin].[PageName], @DestinationRoleId, [Origin].[CanView]
FROM (SELECT [PageName], [CanView] FROM [dbo].[Security_Pages_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [PageName] FROM [dbo].[Security_Pages_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[PageName] = [Destination].[PageName]
WHERE [Destination].[PageName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Reports_Roles] ([ReportName], [RoleId], [CanPrint])
SELECT [Origin].[ReportName], @DestinationRoleId, [Origin].[CanPrint]
FROM (SELECT [ReportName], [CanPrint] FROM [dbo].[Security_Reports_Roles] WHERE [RoleId] = @OriginRoleId) AS [Origin]
LEFT JOIN (SELECT [ReportName] FROM [dbo].[Security_Reports_Roles] WHERE [RoleId] = @DestinationRoleId) AS [Destination] ON [Origin].[ReportName] = [Destination].[ReportName]
WHERE [Destination].[ReportName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

IF NOT EXISTS (SELECT 1 FROM [dbo].[WebAPI_Roles] WHERE [RoleId] = @DestinationRoleId)
BEGIN
INSERT INTO [dbo].[WebAPI_Roles] ([RoleId], [isAuthorized])
SELECT @DestinationRoleId, [isAuthorized] FROM [dbo].[WebAPI_Roles] WHERE [RoleId] = @OriginRoleId
SELECT @Count = @Count + @@ROWCOUNT
END

IF NOT EXISTS (SELECT 1 FROM [dbo].[Security_Offline_Menus_Roles] WHERE [RoleId] = @DestinationRoleId)
BEGIN
INSERT INTO [dbo].[Security_Offline_Menus_Roles] ([MenuId],[RoleId], [CanView])
SELECT [MenuId],@DestinationRoleId, [CanView] FROM [dbo].[Security_Offline_Menus_Roles] WHERE [RoleId] = @Origin

pNet_ImportSecurityRole Stored

RoleId
SELECT @Count = @Count + @@ROWCOUNT
END

SELECT CAST(@Count AS nvarchar) + ' records have been imported' + IIF(@Count <> 0, ' correctly', '') + '.' AS SuccessMessage

COMMIT TRAN
RETURN 1
END TRY
BEGIN CATCH
ROLLBACK TRAN
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)
RETURN 0
END CATCH

pNet_ImportSecurityUser Stored

CREATE PROCEDURE [dbo].[pNet_ImportSecurityUser] (
@OriginUserId AS T_UserId,
@DestinationUserId AS T_UserId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_CloneSecurityUser
--#CREATION
-- 14/03/2019
--#CLASIFICATION
-- Framework/systemSecurity
--#DESCRIPTION
-- Clone Security User
--#PARAMETERS
-- @OriginUserId Origin User,
-- @DestinationUserId Destination User
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY
BEGIN TRAN

DECLARE @Count int = 0

INSERT INTO [dbo].[Security_Master_Tables_Users] ([TableName], [UserId], [CanView], [CanUpdate], [CanDelete], [CanInsert], [CanPrint])
SELECT [Origin].[TableName], @DestinationUserId, [Origin].[CanView], [Origin].[CanUpdate], [Origin].[CanDelete], [Origin].[CanInsert], [Origin].[CanPrint]
FROM (SELECT [TableName], [CanView], [CanUpdate], [CanDelete], [CanInsert], [CanPrint] FROM [dbo].[Security_Master_Tables_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [TableName] FROM [dbo].[Security_Master_Tables_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[TableName] = [Destination].[TableName]
WHERE [Destination].[TableName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Modules_Users] ([ModuleName], [UserId], [CanView], [ViewFilter])
SELECT [Origin].[ModuleName], @DestinationUserId, [Origin].[CanView], [Origin].[ViewFilter]
FROM (SELECT [ModuleName], [CanView], [ViewFilter] FROM [dbo].[Security_Modules_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [ModuleName] FROM [dbo].[Security_Modules_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[ModuleName] = [Destination].[ModuleName]
WHERE [Destination].[ModuleName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Navigation_Nodes_Users] ([NodeId], [UserId], [CanView])
SELECT [Origin].[NodeId], @DestinationUserId, [Origin].[CanView]
FROM (SELECT [NodeId], [CanView] FROM [dbo].[Security_Navigation_Nodes_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [NodeId] FROM [dbo].[Security_Navigation_Nodes_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[NodeId] = [Destination].[NodeId]
WHERE [Destination].[NodeId] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Processes_Users] ([ObjectName], [ProcessName], [UserId], [CanView], [ViewFilter])
SELECT [Origin].[ObjectName], [Origin].[ProcessName], @DestinationUserId, [Origin].[CanView], [Origin].[ViewFilter]
FROM (SELECT [ObjectName], [ProcessName], [CanView], [ViewFilter] FROM [dbo].[Security_Objects_Processes_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [ObjectName],[ProcessName] FROM [dbo].[Security_Objects_Processes_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName] AND [Origin].[ProcessName] = [Destination].[ProcessName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Properties_Users] ([ObjectName], [PropertyName], [UserId], [CanView], [CanEdit])
SELECT [Origin].[ObjectName], [Origin].[PropertyName], @DestinationUserId, [Origin].[CanView], [Origin].[CanEdit]
FROM (SELECT [ObjectName], [PropertyName], [CanView], [CanEdit] FROM [dbo].[Security_Objects_Properties_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [ObjectName],[PropertyName] FROM [dbo].[Security_Objects_Properties_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName] AND [Origin].[PropertyName] = [Destination].[PropertyName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT IN

pNet_ImportSecurityUser Stored

TO [dbo].[Security_Objects_Users] ([ObjectName], [UserId], [CanView], [ViewFilter], [CanViewCollection], [ViewFilterCollection], [CanInsert], [InsertFilter], [CanEdit], [EditFilter], [CanDelete], [DeleteFilter], [CanPrint])
SELECT [Origin].[ObjectName], @DestinationUserId, [Origin].[CanView], [Origin].[ViewFilter], [Origin].[CanViewCollection], [Origin].[ViewFilterCollection], [Origin].[CanInsert], [Origin].[InsertFilter], [Origin].[CanEdit], [Origin].[EditFilter], [Origin].[CanDelete], [Origin].[DeleteFilter], [Origin].[CanPrint]
FROM (SELECT [ObjectName], [CanView], [ViewFilter], [CanViewCollection], [ViewFilterCollection], [CanInsert], [InsertFilter], [CanEdit], [EditFilter], [CanDelete], [DeleteFilter], [CanPrint] FROM [dbo].[Security_Objects_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [ObjectName] FROM [dbo].[Security_Objects_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[ObjectName] = [Destination].[ObjectName]
WHERE [Destination].[ObjectName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Objects_Templates_Users] ([TemplateId], [UserId], [CanView])
SELECT [Origin].[TemplateId], @DestinationUserId, [Origin].[CanView]
FROM (SELECT [TemplateId], [CanView] FROM [dbo].[Security_Objects_Templates_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [TemplateId] FROM [dbo].[Security_Objects_Templates_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[TemplateId] = [Destination].[TemplateId]
WHERE [Destination].[TemplateId] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Pages_Modules_Users] ([PageName], [ModuleName], [UserId], [CanView])
SELECT [Origin].[PageName], [Origin].[ModuleName], @DestinationUserId, [Origin].[CanView]
FROM (SELECT [PageName],[ModuleName], [CanView] FROM [dbo].[Security_Pages_Modules_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [PageName],[ModuleName] FROM [dbo].[Security_Pages_Modules_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[PageName] = [Destination].[PageName] AND [Origin].[ModuleName] = [Destination].[ModuleName]
WHERE [Destination].[PageName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Pages_Users] ([PageName], [UserId], [Canview])
SELECT [Origin].[PageName], @DestinationUserId, [Origin].[CanView]
FROM (SELECT [PageName], [CanView] FROM [dbo].[Security_Pages_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [PageName] FROM [dbo].[Security_Pages_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[PageName] = [Destination].[PageName]
WHERE [Destination].[PageName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

INSERT INTO [dbo].[Security_Reports_Users] ([ReportName], [UserId], [CanPrint])
SELECT [Origin].[ReportName], @DestinationUserId, [Origin].[CanPrint]
FROM (SELECT [ReportName], [CanPrint] FROM [dbo].[Security_Reports_Users] WHERE [UserId] = @OriginUserId) AS [Origin]
LEFT JOIN (SELECT [ReportName] FROM [dbo].[Security_Reports_Users] WHERE [UserId] = @DestinationUserId) AS [Destination] ON [Origin].[ReportName] = [Destination].[ReportName]
WHERE [Destination].[ReportName] IS NULL
SELECT @Count = @Count + @@ROWCOUNT

IF NOT EXISTS (SELECT 1 FROM [dbo].[WebAPI_Users] WHERE [UserId] = @DestinationUserId)
BEGIN
INSERT INTO [dbo].[WebAPI_Users] ([UserId], [isAuthorized])
SELECT @DestinationUserId, [isAuthorized] FROM [dbo].[WebAPI_Users] WHERE [UserId] = @OriginUserId
SELECT @Count = @Count + @@ROWCOUNT
END

SELECT CAST(@Count AS nvarchar) + ' records have been imported' + IIF(@Count <> 0, ' correctly', '') + '.' AS SuccessMessage

COMMIT TRAN
RETURN 1
END TRY
BEGIN CATCH
ROLLBACK TRAN
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDUR

pNet_ImportSecurityUser Stored

E(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)
RETURN 0
END CATCH

pNet_InsertAspNetUserToken Stored

CREATE PROCEDURE [dbo].[pNet_InsertAspNetUserToken](
@Id [T_UserId],
@TokenType T_ObjectName,
@AccessToken nvarchar(max),
@RefreshToken nvarchar(max),
@Scope nvarchar(max),
@ExpiryDate smalldatetime
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_InsertAspNetUserToken
--#CREATION
-- 23/09/2020
--#CLASIFICATION
-- Framework/MailChimp
--#DESCRIPTION
-- Creates or updates entries in AspNetUsers_Tokens Table using stored procedure parameter info
--#PARAMETERS
-- @Id: AspNetUser id
-- @TokenType: Token type
-- @AccessToken: Access token
-- @RefreshToken: Refresh token
-- @Scope: Office api scope
-- @ExpiryDate: Expiry date
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRANSACTION
IF NOT EXISTS(SELECT Id FROM AspNetUsers_Tokens WHERE Id=@Id AND TokenType=@TokenType)
INSERT INTO AspNetUsers_Tokens(Id,TokenType,AccessToken,RefreshToken,Scope,ExpiryDate,InsertedDate)
VALUES (@Id,@TokenType,@AccessToken,@RefreshToken,@Scope,@ExpiryDate,GETDATE())
ELSE
UPDATE AspNetUsers_Tokens SET Id=@Id,TokenType=@TokenType,AccessToken=@AccessToken,RefreshToken=@RefreshToken,Scope=@Scope,ExpiryDate=@ExpiryDate,InsertedDate=GETDATE()
WHERE Id=@Id AND TokenType=@TokenType

COMMIT TRANSACTION
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_InsertMailChimpCampaignsContacts Stored

CREATE PROCEDURE [dbo].[pNet_InsertMailChimpCampaignsContacts](
@Data [Tbl_MailChimp_Campaigns_Contacts] readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_InsertMailChimpCampaignsContacts
--#CREATION
-- 15/11/2020
--#CLASIFICATION
-- Flexygo/MailChimp
--#DESCRIPTION
-- Info about campaign recipients is saved in MailChimp_Campaigns_Contacts
--#PARAMETERS
-- @Data: recipients by campaign
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------

BEGIN TRY

DELETE MailChimp_Campaigns_Contacts WHERE CampaignId = (SELECT TOP 1 CampaignId FROM @Data)

INSERT INTO MailChimp_Campaigns_Contacts (CampaignId, EmailAddress)
SELECT D.CampaignId, D.EmailAddress
FROM @Data D

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_InsertMailChimpContact Stored

CREATE PROCEDURE [dbo].[pNet_InsertMailChimpContact](
@EmailAddress nvarchar(255),
@ObjectName T_ObjectName,
@ObjectId nvarchar(255),
@Fname nvarchar(255),
@LName nvarchar(255),
@Addr1 nvarchar(255),
@Addr2 nvarchar(255),
@City nvarchar(255),
@State nvarchar(255),
@Zip nvarchar(50),
@Country nvarchar(255),
@Status nvarchar(50),
@Language nvarchar(50),
@Vip bit
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_InsertMailChimpContact
--#CREATION
-- 20/04/2020
--#CLASIFICATION
-- Framework/MailChimp
--#DESCRIPTION
-- Creates or updates entries in MailChimp_Contacts Table using stored procedure parameter info
--#PARAMETERS
-- @EmailAddress: Email address
-- @ObjectName: Object name
-- @ObjectId: Object id
-- @Fname: First name
-- @LName: Last name
-- @Addr1: Address
-- @Addr2: Address continuation
-- @City: City
-- @State: State or province
-- @Zip: Postal code
-- @Country: Country
-- @Status: Contact status
-- @Language: Contact language
-- @Vip: Vip member
--#OBSERVATIONS
--
--#CHANGES
-- 20/04/2020 - Javier Alcolea
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRANSACTION
IF NOT EXISTS(SELECT EmailAddress FROM MailChimp_Contacts WHERE (ObjectName=@ObjectName AND ObjectId=@ObjectId) OR EmailAddress=@EmailAddress)
INSERT INTO MailChimp_Contacts(EmailAddress,ObjectName,ObjectId,Fname,LName,Addr1,Addr2,City,State,Zip,Country,Status,Language,Vip)
VALUES (@EmailAddress,@ObjectName,@ObjectId,@Fname,@LName,@Addr1,@Addr2,@City,@State,@Zip,@Country,@Status,@Language,@Vip)
ELSE
UPDATE MailChimp_Contacts SET EmailAddress=@EmailAddress,ObjectName=@ObjectName,ObjectId=@ObjectId,
Fname=@Fname,LName=@LName,Addr1=@Addr1,Addr2=@Addr2,City=@City,State=@State,Zip=@Zip,Country=@Country,Status=@Status,Language=@Language,Vip=@Vip
WHERE ObjectName=@ObjectName AND ObjectId=@ObjectId

COMMIT TRANSACTION
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_LinkEmail Stored

CREATE PROCEDURE [dbo].[pNet_LinkEmail]
@MessageId [T_MailID],
@ObjectName [dbo].[T_ObjectName],
@ObjectId NVARCHAR (250),
@FolderId NVARCHAR (50)
AS

IF NOT EXISTS(SELECT 1 FROM Mails_Objects WHERE MessageId=@MessageId AND ObjectName=@ObjectName AND ObjectId=@ObjectId) BEGIN
INSERT INTO Mails_Objects(MessageId,ObjectName,ObjectId,FolderId) VALUES (@MessageId,@ObjectName,@ObjectId,@FolderId)
Update Mails set IsLinked=1 where MessageId=@MessageId
END

RETURN 1

pNet_LoadAreaNodes Stored

CREATE PROCEDURE [dbo].[pNet_LoadAreaNodes](
@AreaId VARCHAR(50),
@Debug BIT = 0
)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadAreaNodes]
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Child Navigation nodes given a Node Id
-- Loads from table Workflow_areas
-- Also loads parent node
--#PARAMETERS
-- @AreaId: The init area identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/03/2018- David Miralpeix
-- 27/03/2018- jjrodriguez -Added nodes/edges information for network visualization
----------------------------------------------------------------------------------

BEGIN TRY


DECLARE @N NVARCHAR(MAX)=N''
DECLARE @E NVARCHAR(MAX)=N''
DECLARE @J NVARCHAR(MAX)=N''

DECLARE @ObjectCount INT
DECLARE @ColsPerRow INT
DECLARE @BlocksPerCol INT
DECLARE @Row INT
DECLARE @Col INT
DECLARE @SourceObject NVARCHAR(100)
DECLARE @TargetObject NVARCHAR(100)

DECLARE @SourceIcon NVARCHAR(1000)
DECLARE @SourceIconFace NVARCHAR(1000)
DECLARE @SourceLabel NVARCHAR(1000)

DECLARE @TargetLabel NVARCHAR(1000)
DECLARE @TargetIcon NVARCHAR(1000)
DECLARE @TargetIconFace NVARCHAR(1000)


DECLARE @NumProcess INT
DECLARE @OBJECT_COLOR NVARCHAR(100)=N'#036c81'
DECLARE @PROCESS_COLOR NVARCHAR(100)=N'#97C2FC'
DECLARE @EDGE_COLOR NVARCHAR(100)=N'#4F98A7'
DECLARE @SourceObjectId INT
DECLARE @ProcessCountId INT
DECLARE @TargetObjectId INT

CREATE TABLE #Objects(SourceObject NVARCHAR(100),SourceObjectDescrip NVARCHAR(1000),SourceIconFace NVARCHAR(1000),SourceObjectIcon NVARCHAR(1000),NumProcesses INT,TargetObject NVARCHAR(100),TargetObjectDescrip NVARCHAR(1000),TargetIconFace NVARCHAR(1000),TargetObjectIcon NVARCHAR(1000),ObjectId INT PRIMARY KEY(SourceObject,TargetObject))

CREATE TABLE #Nodes(Id INT IDENTITY,PosX INT,PosY INT,Shape NVARCHAR(1000),Label NVARCHAR(1000),Icon NVARCHAR(1000),Face NVARCHAR(1000),Color NVARCHAR(1000),Expandable BIT,Title NVARCHAR(1000),InfoSource NVARCHAR(1000),InfoTarget NVARCHAR(1000),IsObject BIT)

CREATE TABLE #Edges(NodeFrom INT ,NodeTo INT,Color NVARCHAR(1000))


INSERT INTO #Objects(SourceObject,SourceObjectDescrip,SourceIconFace,SourceObjectIcon,TargetObject,TargetObjectDescrip,TargetIconFace,TargetObjectIcon,NumProcesses,ObjectId)
SELECT
O.ObjectName,
O.Descrip,
CASE WHEN SOI.Classification ='flexygo' THEN 'Flexygo-Icons' ELSE 'FontAwesome' END,
SOI.CSSClass,
ISNULL(TOO.ObjectName,O.ObjectName),
ISNULL(TOO.Descrip,O.Descrip),
CASE WHEN ISNULL(TOI.Classification,SOI.Classification) ='flexygo' THEN 'Flexygo-Icons' ELSE 'FontAwesome' END,
ISNULL(TOI.CSSClass,SOI.CSSClass),
SUM( CASE WHEN OP.ProcessName IS NULL THEN 1 ELSE OP.Active END) ProcessCount,
DENSE_RANK() OVER (ORDER BY O.ObjectName)
FROM
Objects_Workflows_Areas OWA
INNER JOIN Objects O ON OWA.ObjectName = O.ObjectName
INNER JOIN Icons SOI ON O.IconName = SOI.IconName
LEFT JOIN Objects_Processes OP ON O.ObjectName = OP.ObjectName
LEFT JOIN Processes_Objects PO ON OP.ProcessName = PO.ProcessName
LEFT JOIN Objects TOO ON PO.ObjectName = TOO.ObjectName
LEFT JOIN Icons TOI ON TOO.IconName = TOI.IconName
WHERE
O.Iscollection = 0 --Temporal
AND OWA.WorkflowAreaId = @AreaId

GROUP BY
O.ObjectName,
O.Descrip,
SOI.CSSClass,
SOI.CLassification,
ISNULL(TOO.ObjectName,O.ObjectName),
ISNULL(TOO.Descrip,O.Descrip),
ISNULL(TOI.Classification,SOI.Classification),
ISNULL(TOI.CSSClass,SOI.CSSClass)


SELECT @ObjectCount=COUNT(1)
FROM
#Objects



SELECT @ColsPerRow=CEILING(SQRT(@ObjectCount))

IF @DEBUG=1 SELECT @OBJECTCOUNT OBJECTCOUNT,@COLSPERROW COLSPERROW,* FROM #OBJECTS


SELECT @Row = 0, @Col =0

WHILE EXISTS(
SELECT 1 FROM #Objects
) BEGIN

SELECT TOP 1
@SourceObject = Source

pNet_LoadAreaNodes Stored

Object, @TargetObject = TargetObject,
@SourceIcon = SourceObjectIcon, @SourceIconFace = SourceIconFace, @SourceLabel = SourceObjectDescrip,
@TargetIcon = TargetObjectIcon, @TargetIconFace = TargetIconFace, @TargetLabel = TargetObjectDescrip,
@NumProcess = NumProcesses
FROM #Objects
ORDER BY
SourceObject,CASE WHEN SourceObject = TargetObject THEN 1 ELSE 2 END,TargetObject

--Source node
INSERT INTO #Nodes(PosX,PosY,Shape,Label,Icon,Face,Color,Expandable,IsObject)
SELECT
@Col + 4,
@Row + 4,
'icon',
@SourceLabel,
@SourceIcon,
@SourceIconFace,
@OBJECT_COLOR,
0,1

SELECT @SourceObjectId = SCOPE_IDENTITY()


IF @SourceObject <> @TargetObject BEGIN

--Process counter
INSERT INTO #Nodes(PosX,PosY,Shape,Label,Icon,Face,Color,Title,InfoSource,InfoTarget,Expandable,IsObject)
SELECT
@Col + 8,
@Row + 4,
'circle',
@NumProcess,
NULL,
NULL,
@PROCESS_COLOR,
CASE WHEN @NumProcess = 0 THEN 'flxarea.noprocesses' ELSE 'flxarea.clickexpand' END,
@SourceObject,
@TargetObject,
CASE WHEN @NumProcess = 0 THEN 0 ELSE 1 END,0



SELECT @ProcessCountId = SCOPE_IDENTITY()



INSERT INTO #Edges(NodeFrom,NodeTo,Color)
SELECT @SourceObjectId,@ProcessCountId,@EDGE_COLOR


--Target object
INSERT INTO #Nodes(PosX,PosY,Shape,Label,Icon,Face,Color,Expandable,IsObject)
SELECT
@Col + 12,
@Row+4,
'icon',
@TargetLabel,
@TargetIcon,
@TargetIconFace,
@OBJECT_COLOR,0,1

SELECT @TargetObjectId = SCOPE_IDENTITY()

INSERT INTO #Edges(NodeFrom,NodeTo,Color)
SELECT @ProcessCountId,@TargetObjectId,@EDGE_COLOR


END


--Same object processes
IF (@SourceObject = @TargetObject)
OR
EXISTS(
SELECT 1 FROM #Objects WHERE SourceObject = TargetObject AND SourceObject = @SourceObject AND (@SourceObject<>@TargetObject)
) BEGIN

SELECT @NumProcess = NumProcesses FROM #Objects WHERE SourceObject = TargetObject AND SourceObject = @SourceObject

--Process counter
INSERT INTO #Nodes(PosX,PosY,Shape,Label,Icon,Face,Color,Title,InfoSource,InfoTarget,Expandable,IsObject)
SELECT
@Col + 3,
@Row+3,
'circle',
@NumProcess,
NULL,
NULL,
@PROCESS_COLOR,
CASE WHEN @NumProcess = 0 THEN 'flxarea.noprocesses' ELSE 'flxarea.clickexpand' END,
CASE WHEN @NumProcess = 0 THEN NULL ELSE @SourceObject END,
CASE WHEN @NumProcess = 0 THEN NULL ELSE @SourceObject END,
CASE WHEN @NumProcess = 0 THEN 0 ELSE 1 END,0

IF @SourceObject<>@TargetObject DELETE FROM #Objects WHERE SourceObject = TargetObject AND SourceObject = @SourceObject

END

DELETE FROM #Objects WHERE SourceObject = @SourceObject AND TargetObject = @TargetObject

SELECT @Col=@Col+16
IF (@Col/16) >= @ColsPerRow BEGIN
SELECT @Row=@Row+8,@Col=0
END

END


UPDATE #Nodes SET PosX=PosX*25,PosY=PosY*25

IF @Debug=1 BEGIN

SELECT 'N',* FROM #Nodes
SELECT 'E',* FROM #Edges

END

SELECT @N = (SELECT * FROM #Nodes FOR JSON PATH)

SELECT @E = (SELECT * FROM #Edges FOR JSON PATH)


SELECT @J = N'{"Nodes":' + ISNULL(@N,N'[]') + N',"Edges":' + ISNULL(@E,N'[]') + N'}'

SELECT
A.* ,i.CSSClass as IconClass ,i.ImagePath,childnodes,@J AS NetworkNodes
FROM
Workflows_Areas A
INNER JOIN Icons i on A.IconName =i.IconName
LEFT JOIN ( SELECT count(*) as childnodes, ParentAreaId FROM Workflows_Areas Group by ParentAreaId) AA ON A.WorkflowAreaId=AA.ParentAreaId
WHERE
A.WorkflowAreaId=@AreaId
UNION
SELECT
A.* ,i.CSSClass as IconClass ,i.ImagePath,childnodes,null as NetworkNodes
FROM
Workflows_Areas A
INNER JOIN Icons i on A.IconName =i.IconName
LEFT JOIN ( SELECT count(*) as childnodes, ParentAreaId FROM Workflows_Areas Group by ParentAreaId) AA ON A.WorkflowAreaId=AA.ParentAreaId
WHERE
A.ParentAreaId=@AreaId ORDER BY A.WorkflowArea

pNet_LoadAreaNodes Stored

Id

RETURN -1


END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_LoadAreaProcess Stored

CREATE PROCEDURE [dbo].[pNet_LoadAreaProcess](
@AreaId VARCHAR(50),
@Source T_ObjectName,
@Target T_ObjectName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadAreaProcess]
--#CREATION
-- 27/03/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading processes associadted to and from an object, within an area
--#PARAMETERS
-- @AreaId: The area identifier.
-- @Source: The source object (readed from Objects_Processes)
-- @AreaId: The target object (readed from Processes_Objects)

--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY

DECLARE @PROCESS_COLOR NVARCHAR(100)=N'#036c81'
DECLARE @EDGE_COLOR NVARCHAR(100)=N'#4F98A7'

SELECT
P.ProcessName,
P.ProcessDescrip,
CASE WHEN MI.Classification ='flexygo' THEN 'Flexygo-Icons' ELSE 'FontAwesome' END AS IconFace,
MI.CSSClass AS Icon,
@PROCESS_COLOR AS Color,
@EDGE_COLOR AS EdgeColor,
CASE WHEN WF.WorkflowId IS NOT NULL THEN 'sysWorkflow' ELSE 'sysProcess' END ObjectName,
CASE WHEN WF.WorkflowId IS NOT NULL THEN
'workflowId=''' + p.processName + ''' AND Active=1'
ELSE
'processName=''' + p.processname + ''''
END ObjectWhere

FROM
Objects_Workflows_Areas OWA
INNER JOIN Objects O ON OWA.ObjectName = O.ObjectName
INNER JOIN Objects_Processes OP ON O.ObjectName = OP.ObjectName
INNER JOIN Processes P ON OP.ProcessName = P.ProcessName
OUTER APPLY (
SELECT TOP 1 WorkflowId FROM Workflows WHERE WorkflowId = P.ProcessName AND P.TypeId = 11
) WF
LEFT JOIN Menus M ON OP.MenuId = M.MenuId
LEFT JOIN Icons MI ON M.IconName = MI.IconName
LEFT JOIN Processes_Objects PO ON OP.ProcessName = PO.ProcessName
LEFT JOIN Objects TOO ON PO.ObjectName = TOO.ObjectName

WHERE
O.Iscollection = 0 --Temporal
AND OWA.WorkflowAreaId = @AreaId
AND O.ObjectName = @Source
AND ISNULL(TOO.ObjectName,O.ObjectName)=@Target
AND OP.Active = 1

RETURN -1


END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_LoadContextVars Stored


CREATE PROCEDURE [dbo].[pNet_LoadContextVars]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadContextVars
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Loads ContextVars to be used in Framework
--#PARAMETERS
-- None
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
select * from ContextVars Order By [Order]
Return -1
END

pNet_LoadDefaultTemplateTypes Stored

CREATE PROCEDURE [dbo].[pNet_LoadDefaultTemplateTypes]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadDefaultTemplateTypes
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading default template Definition from objects_Forms_Templates_Types Table
-- into Framework
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
select * from Objects_Templates_Types
return -1
END

pNet_LoadFilters Stored




CREATE PROCEDURE [dbo].[pNet_LoadFilters](
@CollectionName as t_ObjectName,
@UserId as T_UserId,
@Generic bit = 0,
@NonGeneric bit = 0
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadFilters
--#CREATION
-- 17/01/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load filters for a module.
--#PARAMETERS
-- @CollectionName the collection name
-- @UserId user id for personal filters
--#OBSERVATIONS
--
--#CHANGES
-- 30/10/17-Add generic and nongeneric parameters
----------------------------------------------------------------------------------
BEGIN

--Filters
select os.* from Objects_Search os
where os.ObjectName=@CollectionName
AND (
(@Generic = 1 AND os.Generic=1)
OR
(@NonGeneric = 1 AND OS.Generic=0)
)

--Filter_Properties
select osp.*,t.WebComponent,t.DefaultSize,isnull(osp.Label,p.Label) as Label from Objects_Search os
inner join Objects_Search_Properties osp on osp.SearchId=os.SearchId
inner join Objects_search_Properties_Types t on osp.PropertySearchType=t.PropertySearchType
inner join Objects_Properties p on p.ObjectName=osp.ObjectName and p.PropertyName=osp.PropertyName
where os.ObjectName=@CollectionName
AND (
(@Generic = 1 AND os.Generic=1)
OR
(@NonGeneric = 1 AND OS.Generic=0)
)
order by [order]

Return -1
END

pNet_LoadHelpPages Stored


CREATE PROCEDURE [dbo].[pNet_LoadHelpPages](@HelpId NVARCHAR(50))
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadHelpPages
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading HelpPages
-- If given Id the will only loadt that page
--#PARAMETERS
-- @HelpId: The Help Id.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

if @HelpId is null
begin
select help.*, i.CSSClass, I.ImagePath From Help inner join icons i on help.iconname=i.iconname
end
else
begin
select help.*, i.CSSClass, I.ImagePath From Help inner join icons i on help.iconname=i.iconname where HelpId=@HelpId order by [Order]
end
Return -1
END

pNet_LoadInterfaceJS Stored

CREATE PROCEDURE [dbo].[pNet_LoadInterfaceJS](@InterfaceType int)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadInterfaceJS
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading interfaces JS for a given InterfaceName
--#PARAMETERS
-- @InterfaceName: The Interface Id.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 22/05/2019 - David Miralpeix cambiado para compatibilidad con interf type all
----------------------------------------------------------------------------------
BEGIN

select js.*
From Interfaces I inner join interfaces_Types t on i.TypeId=t.TypeId inner join Interfaces_Types_JS js on t.TypeId=js.typeid
where t.TypeId=@InterfaceType or t.TypeId=-1

order by [Order], [Filepath]

Return -1
END

pNet_LoadJobs Stored



CREATE PROCEDURE [dbo].[pNet_LoadJobs]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadJobs
--#CREATION
-- 19/12/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load new jobs to schedule it.
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

select JobName,JobGroup,Descrip,FirstExecutionDate,LastExecutionDate,TriggerExpression,ExecuteInmediatlyAfterMisfire,ObjectName,ObjectWhere,UserName,ProcessName,Params FROM jobs
left join Jobs_Qrtz_Job_Details dt on dt.Job_Name=jobs.JobName --and dt.Job_Group=dt.Job_Group
WHERE [enabled]=1 and dt.Job_Name is null
AND (LastExecutionDate IS NULL OR LastExecutionDate>=getdate())


RETURN -1
END

pNet_LoadKanbanSettings Stored

CREATE PROCEDURE [dbo].[pNet_LoadKanbanSettings](
@KanbanSettingsName nvarchar(100)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadKanbanSettings
--#CREATION
-- 04/04/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load kanban settings
--#PARAMETERS
-- KanbanSettingsName - Setting name to load configuration
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

select KanbanSettingsName, BoardTitleTemplate, BoardDescripTemplate, BoardObjectName, ColumnViewName, ColumnDescripField, ColumnIdField,
ColumnCssClassField, ColumnIconIdField, CardObjectName, CardViewName, CardIdField, CardColumnIdField, CardDescripField,
CardContentTemplate, onChangeColumnProcess, onCardClick, EndBoxLastState, EndBoxProcess, EndBoxText, i.CSSClass as EndBoxIconName, EndBoxCssClass
from Kanban_Settings KS
left join Icons I on Ks.EndBoxIconName=I.IconName
Where KanbanSettingsName=@KanbanSettingsName

RETURN -1
END

pNet_LoadLinkedServer Stored

CREATE PROCEDURE [dbo].[pNet_LoadLinkedServer]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadLinkedServer
--#CREATION
-- 03/03/2021
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Linked server definition
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 03/03/2020 - Rubén Pardo - Stored created
----------------------------------------------------------------------------------
BEGIN

SELECT [ConnStringId], [ChildConnStringId], [ServerName]
FROM DbConnectionStrings_LinkedServers
ORDER BY ConnStringId ASC, ChildConnStringId ASC

RETURN -1
END

pNet_LoadMailAccount Stored



CREATE PROCEDURE [dbo].[pNet_LoadMailAccount]( @MailAccountId nvarchar(100))
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadMailAccount
--#CREATION
-- 11/02/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Mail Account information into Framework
--#PARAMETERS
-- @MailAccountId: Use sysUser Mail Account Id to take all de Mail Account Settings if exists.
--#OBSERVATIONS
--
--#CHANGES
-- 11/02/2019- Cristina Gómez
----------------------------------------------------------------------------------
BEGIN

SELECT [MailAccountId],[Account],[UserName],[VisibleName],[PopImapHost],[SMTPHost],[MailPassword],[SMTPPort],[PopImapPort],[UseSSL],[UseTLS]
from Mail_Accounts
where MailAccountId=@MailAccountId

Return -1
END

pNet_LoadMasterTableSecurity Stored

CREATE PROCEDURE [dbo].pNet_LoadMasterTableSecurity(
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadMasterTableSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading MasterTables Security definition from Security_Master_Tables_Roles and
-- Security_Master_Tables_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

select * from Security_Master_Tables_Roles where RoleId =@RoleId
select * from Security_Master_Tables_Users where UserId =@UserId

Return -1
END

pNet_LoadModulePagersDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadModulePagersDefinition](
@PagerId as T_PagerId)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadModulePagersDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Module pagers Definition from Module_Pager_types Table
-- into Framework
--#PARAMETERS
-- @PagerId optional @PagerId
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

if @PagerId is null
BEGIN
select * from modules_Pager_Types

END
else
BEGIN
select * from modules_Pager_Types where PagerId=@PagerId

END
Return -1
END

pNet_LoadModulesDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadModulesDefinition](
@ModuleName T_ModuleName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadModulesDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Modules Definition from Module Table and Module Containers
-- and Modules_Classification into Framework
--#PARAMETERS
-- @ModuleName optional ModuleName
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 20/10/2016- David Miralpeix Added Page Module wherfilter
----------------------------------------------------------------------------------
BEGIN

if @ModuleName is null
BEGIN
select m.*, mc.TemplateHtml as ContainerTemplate, i.CSSClass as IconClass, mc.CssClass as ContainerClass from modules m
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Classification mcl on m.ClassId=mcl.ClassId
inner join icons i on mcl.IconName=i.IconName

select modulename,PageName,RelationWhere from Pages_Modules
END
else
BEGIN
select m.*, mc.TemplateHtml as ContainerTemplate, i.CSSClass as IconClass, mc.CssClass as ContainerClass from modules m
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Classification mcl on m.ClassId=mcl.ClassId
inner join icons i on mcl.IconName=i.IconName where m.ModuleName=@ModuleName

select modulename,PageName,RelationWhere from Pages_Modules where ModuleName=@ModuleName
END
Return -1
END

pNet_LoadModulesSecurity Stored




CREATE PROCEDURE [dbo].[pNet_LoadModulesSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadModulesSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Modules Security definition from Security_Modules_Roles and
-- Security_Modules_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 16/01/2017- David Miralpeix (added vNet_AllRestrictedModuleSecurity)
----------------------------------------------------------------------------------

BEGIN

if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all modules overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedModuleSecurity Rest
left join (select * from Security_Modules_Roles where RoleId='allUsers') AllU on allU.ModuleName=Rest.ModuleName
left join (select * from Security_Modules_Roles where RoleId='notRegistered') NotReg on Rest.ModuleName=NotReg.ModuleName
where NotReg.ModuleName is null and AllU.ModuleName is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Modules_Roles where RoleId='allUsers') AllU
left join (select * from Security_Modules_Roles where RoleId='notRegistered') NotReg on allU.ModuleName=NotReg.ModuleName
where NotReg.ModuleName is null
UNION

-- Load NotRegisterd security
select * from Security_Modules_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Modules_Roles where RoleId='allUsers') AllU
left join (select * from Security_Modules_Roles where RoleId='Registered') NotReg on allU.ModuleName=NotReg.ModuleName
left join (select * from Security_Modules_Roles where RoleId=@RoleId) mySec on allU.ModuleName=mySec.ModuleName
where NotReg.ModuleName is null and mySec.ModuleName is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Modules_Roles where RoleId='Registered') NotReg
left join (select * from Security_Modules_Roles where RoleId=@roleid) mySec on NotReg.ModuleName=mySec.ModuleName
where mySec.ModuleName is null
UNION

-- Load Actual Role Group Security
select * from Security_Modules_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Modules_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Modules_Faculties Inner join AspNetUsers_Faculties a on Security_Modules_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ModuleName

end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Modules_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Modules_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Modules_Faculties Inner join AspNetUsers_Faculties a on Security_Modules_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ModuleName

END


Return -1


END

pNet_LoadNetworkGraphic Stored

CREATE PROCEDURE [dbo].[pNet_LoadNetworkGraphic](
@ObjectName T_ObjectName,
@ObjectWhere NVARCHAR(1000),
@MaxId INT
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadNetworGraphic
--#CREATION
-- 05/01/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Loads the data for a network graphic
--#PARAMETERS
-- @ObjectName: The object name.
-- @ObjectWhere: The object name.
-- @MaxId: Max Id used in tree
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @SQL NVARCHAR(MAX)=N''

DECLARE @Data TABLE(Descrip VARCHAR(1000), IconName VARCHAR(1000), TableName VARCHAR(1000), ObjectName VARCHAR(1000), ObjectWhere VARCHAR(1000), ObjectChildName VARCHAR(1000), ObjectDefaults VARCHAR(1000), [Rows] INT, Id INT IDENTITY)

DECLARE @Name VARCHAR(1000)

DECLARE @Table VARCHAR(1000)

SELECT @Name = CASE WHEN IsCollection=1 then ObjectChildName ELSE ObjectName END
FROM
Objects
WHERE
ObjectName = @ObjectName

--Translate the paremters to obtain object info, only for initial node
IF ISNULL(@MaxId,0)=0 AND (@Name <> 'sysObject') BEGIN

SELECT @ObjectName = 'sysObject',@ObjectWhere = 'ObjectName='''+@Name+''''

SELECT @Name=@ObjectName


END

SELECT @Table=TableName FROM Objects WHERE ObjectName=@Name

SELECT @SQL=N''


--Main node
IF ISNULL(@MaxId,0)=0 BEGIN

SELECT
@SQL=@SQL+CAST(
'SELECT [Objects].Descrip,I.CSSClass,''' + @Table+ ''','''+@ObjectName+''',''' + REPLACE(@ObjectWhere,'''','''''') + ''',NULL,NULL,1
FROM
[Objects]
LEFT JOIN Icons I ON [Objects].IconName = I.IconName
WHERE
' + @ObjectWhere
AS NVARCHAR(MAX))


INSERT INTO @data(Descrip,IconName,TableName,ObjectName,ObjectWhere,ObjectChildName,ObjectDefaults,Rows)
EXEC(@SQL)

END ELSE BEGIN

INSERT INTO @data(Descrip,IconName,TableName,ObjectName,ObjectWhere,ObjectChildName,ObjectDefaults,Rows)
SELECT
O.Descrip,I.CSSClass,O.TableName,O.ObjectName,@ObjectWhere,NULL,NULL,1
FROM
Objects O
LEFT JOIN Icons I ON O.IconName = I.IconName
WHERE
O.ObjectName = @Name



END


SELECT @SQL=N''

SELECT
@SQL = @SQL + CAST(
'SELECT ''' + O.Descrip + ''' Descrip,''' + I.CSSClass + ''' IconName,''' + O.TableName +''' TableName,' +
'''' + O.ObjectName + ''' AS ObjectName,''' + REPLACE(@ObjectWhere,'''','''''') + ''' AS ObjectWhere,' +
'''' + O.ObjectChildName + ''' AS ObjectChildName,''' + DEF.V + ''' AS ObjectDefaults,COUNT(1) Rows FROM ' +
O.TableName

+ ' WHERE EXISTS (' +

+ ' SELECT 1 '
+ ' FROM ' + @Table +
+ ' WHERE ' + @ObjectWhere +
+ COL.V
+ ')'

AS NVARCHAR(MAX))
FROM
objects_objects FK
INNER JOIN Objects O ON fk.childcollection = o.objectname AND O.Active=1
LEFT JOIN Icons i ON o.IconName =i.IconName
CROSS APPLY ( --Parse object relation to obtain the WHERE subquery string
select

N' AND ' +
--Literal
CASE WHEN LEFT(substring(sub.rowvalue,1,charindex('=',sub.rowvalue)-1),1)=N'''' AND RIGHT(substring(sub.rowvalue,1,charindex('=',sub.rowvalue)-1),1)=N'''' THEN
substring(sub.rowvalue,1,charindex('=',sub.rowvalue)-1)
ELSE

po.tablename + N'.' + substring(sub.rowvalue,1,charindex('=',sub.rowvalue)-1)

END
+N'='+
CASE WHEN LEFT(substring(sub.rowvalue,charindex('=',sub.rowvalue)+1,LEN(sub.rowvalue)) ,1)=N'''' AND RIGHT(substring(sub.rowvalue,charindex('=',sub.rowvalue)+1,LEN(sub.rowvalue)) ,1)=N'''' THEN
substring(sub.rowvalue,charindex('=',sub.rowvalue)+1,LEN(sub.rowvalue))
ELSE
co.tablename+N'.'+substring(sub.rowvalue,charindex('=',sub.rowvalue)+1,LEN(sub.rowvalue))
END


from (
select oo.ObjectName,oo.childcollection,r.value rowvalue

pNet_LoadNetworkGraphic Stored


from
objects_objects oo
CROSS APPLY STRING_SPLIT(ObjectRelation,'|') r
where
oo.ObjectName =FK.ObjectName
and oo.ChildCollection = FK.ChildCollection
) sub
INNER JOIN Objects po on sub.ObjectName = po.ObjectName
INNER JOIN Objects co on sub.ChildCollection = co.ObjectName
FOR XML PATH('')
) COL(V)
CROSS APPLY ( --Return object defaults
select

N'{"' + REPLACE(substring(sub.rowvalue,1,charindex('=',sub.rowvalue)-1),N'''',N'''''')
+
N'":"{{' +

REPLACE(substring(sub.rowvalue,charindex('=',sub.rowvalue)+1,LEN(sub.rowvalue)),N'''',N'''''')

+ '}}"}'

from (
select oo.ObjectName,oo.childcollection,r.value rowvalue
from
objects_objects oo
CROSS APPLY STRING_SPLIT(ObjectDefaults,'|') r
where
oo.ObjectName =FK.ObjectName
and oo.ChildCollection = FK.ChildCollection
) sub
INNER JOIN Objects po on sub.ObjectName = po.ObjectName
INNER JOIN Objects co on sub.ChildCollection = co.ObjectName
FOR XML PATH('')
) DEF(V)
WHERE
FK.ObjectName=@name

--print @sql
INSERT INTO @DATA
EXEC(@SQL)


DELETE FROM @DATA WHERE ROWS=0


--Result (Nodes)

SELECT
@MaxId + Id as id,
Descrip + ' (' + CAST(Rows AS varchar(100)) + ')' AS label,
ObjectName as objectname,
ObjectWhere as objectwhere,
ObjectChildName as objectchildname,
iconname as objecticon,
ObjectDefaults as objectdefaults
FROM
@DATA


--Result (Edges)

SELECT @MaxId + 1 AS [from],@MaxId + ID AS [to]
FROM @DATA
WHERE ID<>1

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_LoadNodes Stored

CREATE PROCEDURE [dbo].[pNet_LoadNodes](@NodeId VARCHAR(50))
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadNodes]
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Child Navigation nodes given a Node Id
-- Loads from table Navigation_node
-- Also checks if node is has a reportName or a ProcessName to obtain
-- Number of parameters and Target for parameter form.
--#PARAMETERS
-- @NodeId: The init NodeId.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 12/04/2017- David Miralpeix AdminOnly
----------------------------------------------------------------------------------
BEGIN

SELECT
N.* ,i.CSSClass as IconClass ,i.ImagePath,
Pp.numParameters as ProcessNumParameters, PP.TargetId as Targetid,P.AdminOnly,
RP.numParameters as ReportNumParameters, RP.ParamsTargetId as ReportParamTargetid
FROM
Navigation_Nodes N
INNER JOIN fNet_LoadChidNodes(@NodeId) F on N.NodeId=F.NodeId
INNER JOIN Icons i on n.IconName =i.IconName
LEFT JOIN (
SELECT count(*) numParameters,r.ParamsTargetId,r.reportname
FROM
Reports_Params rp
INNER JOIN Reports r on rp.ReportName=r.ReportName
GROUP BY
r.ReportName,r.ParamsTargetId
) RP ON N.ReportName=RP.ReportName
LEFT JOIN (
Select count(*) numParameters,p.TargetId,p.ProcessName
FROM
Processes_Params pp
INNER JOIN processes p on pp.ProcessName=p.ProcessName
GROUP BY
p.ProcessName, p.TargetId
) PP on N.ProcessName=PP.ProcessName
LEFT JOIN Processes p on N.ProcessName = p.ProcessName

ORDER BY
N.[Order], N.Descrip

RETURN -1
END

pNet_LoadNodesSecurity Stored


CREATE PROCEDURE [dbo].[pNet_LoadNodesSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadNodesSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Nodes Security definition from Security_Navigation_Nodes_Roles and
-- Security_Navigation_Nodes_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 16/01/2017- David Miralpeix (added vNet_AllRestrictedNodeSecurity)
----------------------------------------------------------------------------------



BEGIN

if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all Nodes overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedNodeSecurity Rest
left join (select * from Security_Navigation_Nodes_Roles where RoleId='allUsers') AllU on allU.NodeId=Rest.NodeId
left join (select * from Security_Navigation_Nodes_Roles where RoleId='notRegistered') NotReg on Rest.NodeId=NotReg.NodeId
where NotReg.NodeId is null and AllU.NodeId is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Navigation_Nodes_Roles where RoleId='allUsers') AllU
left join (select * from Security_Navigation_Nodes_Roles where RoleId='notRegistered') NotReg on allU.NodeId=NotReg.NodeId
where NotReg.NodeId is null
UNION

-- Load NotRegisterd security
select * from Security_Navigation_Nodes_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Navigation_Nodes_Roles where RoleId='allUsers') AllU
left join (select * from Security_Navigation_Nodes_Roles where RoleId='Registered') NotReg on allU.NodeId=NotReg.NodeId
left join (select * from Security_Navigation_Nodes_Roles where RoleId=@RoleId) mySec on allU.NodeId=mySec.NodeId
where NotReg.NodeId is null and mySec.NodeId is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Navigation_Nodes_Roles where RoleId='Registered') NotReg
left join (select * from Security_Navigation_Nodes_Roles where RoleId=@roleid) mySec on NotReg.NodeId=mySec.NodeId
where mySec.NodeId is null
UNION

-- Load Actual Role Group Security
select * from Security_Navigation_Nodes_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Navigation_Nodes_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Navigation_Nodes_Faculties Inner join AspNetUsers_Faculties a on Security_Navigation_Nodes_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by NodeId


end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Navigation_Nodes_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Navigation_Nodes_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Navigation_Nodes_Faculties Inner join AspNetUsers_Faculties a on Security_Navigation_Nodes_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by NodeId


END


Return -1


END

pNet_LoadNoticeNode Stored

CREATE PROCEDURE [dbo].[pNet_LoadNoticeNode](@NoticeId VARCHAR(50))
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadNoticeNode]
--#CREATION
-- 01/01/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Navigation nodes given a NoticeId
-- Also checks if node is has a reportName or a ProcessName to obtain
-- Number of parameters and Target for parameter form.
--#PARAMETERS
-- @NoticeId: The NoticeId.
--#OBSERVATIONS
--
--#CHANGES
-- 01/01/2017- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

SELECT
N.* ,i.CSSClass as IconClass ,i.ImagePath,
Pp.numParameters as ProcessNumParameters, PP.TargetId as Targetid,P.AdminOnly,
RP.numParameters as ReportNumParameters, RP.ParamsTargetId as ReportParamTargetid
FROM
Notices N
INNER JOIN Notices_Methods nm on N.MethodName =nm.MethodName
INNER JOIN Icons i on nm.IconName =i.IconName
LEFT JOIN (
SELECT count(*) numParameters,r.ParamsTargetId,r.reportname
FROM
Reports_Params rp
INNER JOIN Reports r on rp.ReportName=r.ReportName
GROUP BY
r.ReportName,r.ParamsTargetId
) RP ON N.ReportName=RP.ReportName
LEFT JOIN (
Select count(*) numParameters,p.TargetId,p.ProcessName
FROM
Processes_Params pp
INNER JOIN processes p on pp.ProcessName=p.ProcessName
GROUP BY
p.ProcessName, p.TargetId
) PP on N.ProcessName=PP.ProcessName
LEFT JOIN Processes p on N.ProcessName = p.ProcessName

Where NoticeId=@NoticeId


RETURN -1
END

pNet_LoadObjectDataViewsCollection Stored



CREATE PROCEDURE [dbo].[pNet_LoadObjectDataViewsCollection]( @ObjectName nvarchar(255))
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectDataViewsCollection
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Dataviews from Objects_Views Table into Framework
--#PARAMETERS
-- @ObjectName: Object Name to use as filter
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 07/06/2017- Rubén Pardo - Add Objects_Views_Properties
-- 06/08/2018- Rubén Pardo - Add webapi security
----------------------------------------------------------------------------------
BEGIN

SELECT Objects_Views.*, isnull(WV.CanView,0) as WebAPI_CanView FROM Objects_Views
LEFT JOIN WebAPI_Views WV ON Objects_Views.ObjectName=WV.ObjectName AND Objects_Views.ViewName=WV.ViewName
WHERE Objects_Views.ObjectName=@ObjectName

select Objects_Views_Properties.* from Objects_Views_Properties WHERE ObjectName=@ObjectName

Return -1
END

pNet_LoadObjectDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectDefinition](
@InactiveObjOn bit,
@ObjectName T_ObjectName )
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Definition from objects Table and Objects_Additional_Tables
-- Table into Framework
--#PARAMETERS
-- @InactiveObjOn: bit that defines if we should also load inactive objects
-- @ObjectName: Object Name to use as filter. If null then loads definition for all objects
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 06/08/2018- Rubén Pardo - Add webapi security
----------------------------------------------------------------------------------
BEGIN

if @InactiveObjOn =0
if @ObjectName is null
BEGIN
select Objects.*, i.CSSClass as IconCssClass, i.ImagePath,
ISNULL(WO.CanView,0) as WebAPI_CanView, ISNULL(WO.CanViewCollection,0) as WebAPI_CanViewCollection, ISNULL(WO.CanInsert,0) as WebAPI_CanInsert, ISNULL(WO.CanEdit,0) as WebAPI_CanEdit, ISNULL(WO.CanDelete,0) as WebAPI_CanDelete, ISNULL(WO.CanPrint,0) as WebAPI_CanPrint
FROM Objects inner join icons i on Objects.IconName=i.IconName
LEFT JOIN WebAPI_Objects WO ON WO.ObjectName=Objects.ObjectName
WHERE Active<>0 ORDER BY Iscollection

SELECT Objects.ObjectName, at.[TableName], at.[KeyMap], at.[Descrip], at.[InsertType], at.[UpdateType], at.[DeleteType], at.[InsertProcessName], at.[UpdateProcessName], at.[DeleteProcessName], at.[ConnStringId]
from Objects_Additional_Tables at
INNER join Objects on (at.ObjectName =Objects.ObjectName OR at.ObjectName =Objects.ObjectChildName )
WHERE Active<>0

END
else
BEGIN
select Objects.*, i.CSSClass as IconCssClass, i.ImagePath,
ISNULL(WO.CanView,0) as WebAPI_CanView, ISNULL(WO.CanViewCollection,0) as WebAPI_CanViewCollection, ISNULL(WO.CanInsert,0) as WebAPI_CanInsert, ISNULL(WO.CanEdit,0) as WebAPI_CanEdit, ISNULL(WO.CanDelete,0) as WebAPI_CanDelete, ISNULL(WO.CanPrint,0) as WebAPI_CanPrint
from Objects
INNER join icons i on Objects.IconName=i.IconName
LEFT JOIN WebAPI_Objects WO ON WO.ObjectName=Objects.ObjectName
WHERE Active<>0 and Objects.ObjectName=@ObjectName Order By Iscollection

SELECT Objects.ObjectName, at.[TableName], at.[KeyMap], at.[Descrip], at.[InsertType], at.[UpdateType], at.[DeleteType], at.[InsertProcessName], at.[UpdateProcessName], at.[DeleteProcessName], at.[ConnStringId]
FROM Objects_Additional_Tables at
INNER JOIN Objects ON (at.ObjectName =Objects.ObjectName OR at.ObjectName =Objects.ObjectChildName )
WHERE Active<>0 AND Objects.ObjectName=@ObjectName

END
else
if @ObjectName is null
BEGIN
select Objects.*, i.CSSClass as IconCssClass, i.ImagePath ,
ISNULL(WO.CanView,0) as WebAPI_CanView, ISNULL(WO.CanViewCollection,0) as WebAPI_CanViewCollection, ISNULL(WO.CanInsert,0) as WebAPI_CanInsert, ISNULL(WO.CanEdit,0) as WebAPI_CanEdit, ISNULL(WO.CanDelete,0) as WebAPI_CanDelete, ISNULL(WO.CanPrint,0) as WebAPI_CanPrint
FROM Objects inner join icons i on Objects.IconName=i.IconName
LEFT JOIN WebAPI_Objects WO ON WO.ObjectName=Objects.ObjectName
ORDER By Iscollection

SELECT Objects.ObjectName, at.[TableName], at.[KeyMap], at.[Descrip], at.[InsertType], at.[UpdateType], at.[DeleteType], at.[InsertProcessName], at.[UpdateProcessName], at.[DeleteProcessName], at.[ConnStringId]
FROM Objects_Additional_Tables at
INNER JOIN Objects ON (at.ObjectName =Objects.ObjectName OR at.ObjectName =Objects.ObjectChildName )

END
else
BEGIN
select Objects.*, i.CSSClass as IconCssClass, i.ImagePath ,
ISNULL(WO.CanView,0) as WebAPI_CanView, ISNULL(WO.CanViewCollection,0) as WebAPI_CanViewCollection, ISNULL(WO.CanInsert,0) as WebAPI_CanInsert, ISNULL(WO.CanEdit,0) as WebAPI

pNet_LoadObjectDefinition Stored

_CanEdit, ISNULL(WO.CanDelete,0) as WebAPI_CanDelete, ISNULL(WO.CanPrint,0) as WebAPI_CanPrint
FROM Objects inner join icons i on Objects.IconName=i.IconName
LEFT JOIN WebAPI_Objects WO ON WO.ObjectName=Objects.ObjectName
WHERE Objects.ObjectName=@ObjectName Order By Iscollection

SELECT Objects.ObjectName, at.[TableName], at.[KeyMap], at.[Descrip], at.[InsertType], at.[UpdateType], at.[DeleteType], at.[InsertProcessName], at.[UpdateProcessName], at.[DeleteProcessName], at.[ConnStringId]
FROM Objects_Additional_Tables at
INNER JOIN Objects ON (at.ObjectName =Objects.ObjectName OR at.ObjectName =Objects.ObjectChildName )
WHERE Objects.ObjectName=@ObjectName

END

Return -1
END

pNet_LoadObjectProcessCollection Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectProcessCollection](@ObjectName T_ObjectName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectProcessCollection
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Process Collection definition from Objects_Processes and Process Tables into Framework
--#PARAMETERS
-- @ObjectName: Object Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 12/04/2017- Changed adminOnly to Process Table David Miralpeix
-- 08/08/2017- David Miralpeix Added ConfirmOnOkOption and CloseDialosOnOk
-- 20/09/2017- Rubén Pardo Added parent menu descrip and icons.
-- 23/03/2019- avid Miralpeix Added process defaults
-- 10/09/2019- Aitor Torres Added field ClearSelectionBag
----------------------------------------------------------------------------------
BEGIN

SELECT
op.*, p.[TypeId] ,p.[ClassId],p.[ConfirmText],p.[JSforParams],p.[TargetId] ,p.AdminOnly, ISNULL(ParamCount,0) AS ParamCount,p.Defaults,
Icons.CSSClass as IconCssClass, Icons.ImagePath as IconImagePath, menus.Descrip as MenuText,
menus.ParentId as ParentMenuId , pMenus.Descrip as ParentMenuText, pIcons.CSSClass as ParentIconCssClass,pIcons.ImagePath as ParentIconImagePath
,op.[Order], op.BagOnly ,op.ClearSelectionBag
FROM
Objects_Processes AS op
INNER JOIN Menus ON op.MenuId = Menus.MenuId
LEFT JOIN Menus pMenus ON menus.ParentId = pMenus.MenuId
LEFT JOIN Icons pIcons ON pIcons.IconName = pMenus.IconName
INNER JOIN Processes p on OP.ProcessName = P.ProcessName
LEFT JOIN Icons ON dbo.Menus.IconName = Icons.IconName
LEFT JOIN (
Select ProcessName, Count(ProcessName) As ParamCount
from Processes_Params
where hide=0
group by ProcessName
) rp On p.ProcessName = rp.ProcessName
WHERE
active <>0 and op.ObjectName=@ObjectName
ORDER BY
op.[Order]


Return -1
END

pNet_LoadObjectProcessSecurity Stored


CREATE PROCEDURE [dbo].[pNet_LoadObjectProcessSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectProcessSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Process Security definition from Security_Objects_Processes_Processes_Roles and
-- Security_Objects_Processes_Processes_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 16/01/2017- David Miralpeix (Added vNet_AllRestrictedObjectProcessSecurity)
----------------------------------------------------------------------------------


BEGIN

if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all objects Processes overwrite with allusers security and overwrite with NotRegisterd security
SELECT
Rest.*
FROM
vNet_AllRestrictedObjectProcessSecurity Rest
LEFT JOIN (
select * from Security_Objects_Processes_Roles
where RoleId='allUsers'
) AllU on allU.ObjectName=Rest.ObjectName and allU.ProcessName = Rest.ProcessName
LEFT JOIN (
select *
from Security_Objects_Processes_Roles
where RoleId='notRegistered'
) NotReg on Rest.ObjectName=NotReg.ObjectName and Rest.ProcessName = NotReg.ProcessName
WHERE
NotReg.ObjectName is null and AllU.ObjectName is null

UNION

-- Load allusers security and overwrite with NotRegisterd security
SELECT
AllU.*
FROM (
select * from Security_Objects_Processes_Roles where RoleId='allUsers'
) AllU
LEFT JOIN (
select * from Security_Objects_Processes_Roles where RoleId='notRegistered'
) NotReg on allU.ObjectName=NotReg.ObjectName and allU.ProcessName =NotReg.ProcessName
WHERE
NotReg.ObjectName is null

UNION

-- Load NotRegisterd security
select * from Security_Objects_Processes_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
SELECT
allU.*
FROM (
select * from Security_Objects_Processes_Roles where RoleId='allUsers'
) AllU
LEFT JOIN (
select * from Security_Objects_Processes_Roles where RoleId='Registered'
) NotReg on allU.ObjectName=NotReg.ObjectName and allU.ProcessName=NotReg.ProcessName
LEFT JOIN (
select * from Security_Objects_Processes_Roles where RoleId=@RoleId
) mySec on allU.ObjectName=mySec.ObjectName and allU.ProcessName =mySec.ProcessName
WHERE
NotReg.ObjectName is null and mySec.ObjectName is null

UNION

-- Load Registerd security and overwite with Actual Role Group
select
NotReg.*
FROM (
select * from Security_Objects_Processes_Roles where RoleId='Registered'
) NotReg
LEFT JOIN (
select * from Security_Objects_Processes_Roles where RoleId=@roleid
) mySec on NotReg.ObjectName=mySec.ObjectName and NotReg.ProcessName =mySec.ProcessName
WHERE
mySec.ObjectName is null

UNION

-- Load Actual Role Group Security
select * from Security_Objects_Processes_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Objects_Processes_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Processes_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Processes_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName, ProcessName

end

pNet_LoadObjectProcessSecurity Stored



END ELSE BEGIN
--User is administrator or designer.
select * from Security_Objects_Processes_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Objects_Processes_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Processes_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Processes_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName, ProcessName

END


Return -1


END

pNet_LoadObjectPropertyDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectPropertyDefinition]( @ObjectName t_objectName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectPropertyDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Properties definition from Objects_properties Table into Framework
-- If Property Type is custom (templateProperty) then it will load from Objects_Properties_Templates
--#PARAMETERS
-- @ObjectName: Object Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 02/05/2017- David Miralpeix Changed WHereSentence overrides template wheresentence
-- 22/05/2017- David Miralpeix Added Autoincrement Fields
-- 23/01/2018- Alberto Criado Andrés Added CascadeDependencies Fields
-- 04/04/2018- Carmen when the propertytype is custom and the propety template isn't detachedfromdb, it put the detachedfromdb value of the object property
-- 04/05/2018- Rubén Pardo Added UseRootSettingsPath Field
-- 05/10/2018- Alberto Criado Andrés Added RootPathType Field And Delete UseRootSettingsPath Field
-- 31/10/2018- David Miralpeix added pagesize property for dbcombos
-- 05/09/2019- Sergio Vera Added ImageCompressionType Field, ImageMaxWidth Field,ImageMaxHeight Field
----------------------------------------------------------------------------------
BEGIN
select op.[ObjectName] ,op.[PropertyName] ,op.PositionX,op.PositionY,op.Width,op.Height ,op.[Hide],op.ClientReadOnly,op.FormDisplay ,op.[TypeId] ,op.[Mask]
,op.[SQLEditSentence],op.[SQLFilter], op.[Autoselect] ,op.[SQLValueField] ,op.[SQLDisplayField],op.[SQLObjectName],op.[SQLViewName],op.[SQLOfflineSentence], op.[SQLOfflineOrderBy] ,op.[WhereSentence] ,op.[Label] ,op.[Locked] ,op.[DefaultValue] ,op.[PersistDefaultValue]
,op.[IgnoreDBDefaultValue],op.[DetachedFromDB] ,op.[SearchFunction] ,op.[SearchCollection],op.[SearchWhere],op.[SearchReturnFields] ,op.[SecurityObject]
,op.[AllowNew],op.[AllowNewFunction],op.[AllowNewReturnFields], op.[AllowNewDefaults] ,op.[ObjNameLink],op.[ObjWhereLink],op.[TargetIdLink],op.[Style],op.[CSSClass]
,op.[LabelStyle],op.[LabelCSSClass],op.[DecimalPlaces],op.[RootPath],op.[FormatString],op.[DirectTemplate] ,op.[Tag],op.[HelpId],op.Autoincrement,op.AutoincrementFunction
,op.[ConnStringId] ,op.[IsRequired],op.[IsRequiredMessage] ,op.[minValue],op.[minValueMessage],op.[maxValue],op.[maxValueMessage],op.[RegExp],op.[RegExpText],op.[SQLValidator],op.[ValidatorMessage]
,op.[OnChangeJsFunction],op.[OnChangeProcessName],op.[PlaceHolder],op.[Separator],op.[CascadeDependencies],op.[RootPathType],pt.[WebComponent],pt.[OfflineWebComponent],i.CSSClass AS IconClass, pt.SearchTypes,pt.DefaultSearchType,op.PageSize,op.[ImageCompressionType],op.[ImageMaxWidth],op.[ImageMaxHeight],op.[Offline],op.[ExtensionId],e.[Extensions]
,isnull(isnull(op.[SQlSentence],ovSQL.SQLSentence),'select '+op.SQLDisplayField+', '+op.SQLValueField+' from '+oSQL.TableName) as SQLSentence
from Objects_properties op inner join Objects_properties_types pt on op.TypeId=pt.TypeId
left join icons i on op.IconName=i.IconName
left join Extensions e ON op.ExtensionId = e.ExtensionId
left join objects_views ovSQL on op.SQLObjectName=ovSQL.ObjectName and op.SQLViewName=ovSQL.ViewName
left join objects oSQL on op.SQLObjectName=oSQL.ObjectName and op.SQLViewName is null
where op.ObjectName=@objectName and op.TypeId<>'custom'
UNION

select op.Objectname, op.PropertyName, op.PositionX,op.PositionY,isnull(op.Width,opt.width) as Width,isnull(op.Height,opt.height) as Height, op.[Hide] ,op.ClientReadOnly,op.FormDisplay ,opt.[TypeId] ,opt.[Mask]
,opt.[SQLEditSentence] ,opt.[SQLFilter], opt.[Autoselect], opt.[SQLValueField], opt.[SQLDisplayField], ISNULL(opt.[SQLObjectName],op.[SQLObjectName]) as [SQLObjectName], isnull(opt.[SQLViewNa

pNet_LoadObjectPropertyDefinition Stored

me],op.[SQLViewName]) as [SQLViewName], ISNULL(opt.[SQLOfflineSentence],op.[SQLOfflineSentence]) AS SQLOfflineSentence, ISNULL(opt.[SQLOfflineOrderBy],op.[SQLOfflineOrderBy]) AS SQLOfflineOrderBy, ISNULL(op.WhereSentence,opt.[WhereSentence]) as WhereSentence ,ISNULL(op.Label,opt.[Label]) ,op.[Locked] ,isnull(op.[DefaultValue],opt.[DefaultValue]) ,IIF(opt.[PersistDefaultValue]=0 , op.[PersistDefaultValue],opt.[PersistDefaultValue]) [PersistDefaultValue]
,IIF(opt.[IgnoreDBDefaultValue]=0 , op.[IgnoreDBDefaultValue],opt.[IgnoreDBDefaultValue]) [IgnoreDBDefaultValue],IIF(opt.[DetachedFromDB]=0 , op.[DetachedFromDb],opt.[DetachedFromDb]) DetachdeFromDb ,
isnull(op.[SearchFunction],opt.[SearchFunction]) as [SearchFunction], isnull(op.[SearchCollection],opt.[SearchCollection]) as [SearchCollection], isnull(op.[SearchWhere],opt.[SearchWhere]) as [SearchWhere], isnull(op.[SearchReturnFields],opt.[SearchReturnFields]) as [SearchReturnFields]
,opt.[SecurityObject]
,opt.[AllowNew],opt.[AllowNewFunction],opt.[AllowNewReturnFields], opt.[AllowNewDefaults] ,ISNULL(op.[ObjNameLink], opt.[ObjNameLink]),ISNULL(op.[ObjWhereLink], opt.[ObjWhereLink]),isnull(op.[TargetIdLink], opt.[TargetIdLink]),isnull(op.[Style],opt.[Style]),isnull(op.[CSSClass],opt.[CSSClass])
,isnull(op.[LabelStyle],opt.[LabelStyle]),isnull(op.[LabelCSSClass],opt.[LabelCSSClass]),opt.[DecimalPlaces],opt.[RootPath],opt.[FormatString],opt.[DirectTemplate] ,opt.[Tag],isnull(op.[HelpId],opt.[HelpId]) as [HelpId],op.Autoincrement,op.AutoincrementFunction
,isnull(op.[ConnStringId],opt.[ConnStringId]) AS [ConnStringId] ,case when opt.[IsRequired]=1 then 1 else op.IsRequired end as IsRequired , ISNULL(op.[IsRequiredMessage],opt.[IsRequiredMessage]) as [IsRequiredMessage] ,opt.[minValue],opt.[minValueMessage],opt.[maxValue],opt.[maxValueMessage],opt.[RegExp],opt.[RegExpText],opt.[SQLValidator],opt.[ValidatorMessage]
,opt.[OnChangeJsFunction],isnull(op.[OnChangeProcessName],opt.[OnChangeProcessName]) as [OnChangeProcessName],opt.[PlaceHolder],op.[Separator],op.[CascadeDependencies],op.[RootPathType],pt.[WebComponent],pt.[OfflineWebComponent] ,isnull(iop.CSSClass,iopt.CSSClass) AS IconClass, pt.SearchTypes,pt.DefaultSearchType,isnull(op.PageSize,opt.PageSize),op.[ImageCompressionType],op.[ImageMaxWidth],op.[ImageMaxHeight],op.[Offline],op.[ExtensionId],e.[Extensions]
,isnull(isnull(opt.[SQlSentence],ovSQL.SQLSentence),'select '+opt.SQLDisplayField+', '+opt.SQLValueField+' from '+oSQL.TableName) as SQLSentence
from Objects_properties op Inner join Objects_Properties_Templates opt on op.CustomPropName=opt.CustomPropName
and op.TypeId='custom' inner join Objects_properties_types pt on opt.TypeId=pt.TypeId
left join icons iop on op.IconName=iop.IconName
left join icons iopt on opt.IconName=iopt.IconName
left join Extensions e ON op.ExtensionId = e.ExtensionId
left join objects_views ovSQL on isnull(opt.[SQLObjectName],op.[SQLObjectName])=ovSQL.ObjectName and isnull(opt.[SQLViewName],op.[SQLViewName])=ovSQL.ViewName
left join objects oSQL on isnull(opt.[SQLObjectName],op.[SQLObjectName])=oSQL.ObjectName and isnull(opt.[SQLViewName],op.[SQLViewName]) is null
where op.ObjectName=@objectName

Order By PositionX,[PositionY]
Return -1
END

pNet_LoadObjectPropertyDependency Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectPropertyDependency](@ObjectName t_objectName )
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectPropertyDependency
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Property dependencies definition from Objects_Properties_Dependencies Table into Framework
--#PARAMETERS
-- @ObjectName: Object Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
select * from Objects_Properties_Dependencies where ObjectName=@objectName and Active <>0 Order By PropertyName, [Order]
Return -1
END

pNet_LoadObjectPropertySecurity Stored


CREATE PROCEDURE [dbo].[pNet_LoadObjectPropertySecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectPropertySecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Property Security definition from Security_Objects_Properties_Properties_Roles and
-- Security_Objects_Properties_Properties_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 01/01/2017- David Miralpeix (added vNet_AllRestrictedObjectPropertySecurity)
----------------------------------------------------------------------------------


BEGIN

if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all objects overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedObjectPropertySecurity Rest
left join (select * from Security_Objects_Properties_Roles where RoleId='allUsers') AllU on allU.ObjectName=Rest.ObjectName and allU.PropertyName=Rest.PropertyName
left join (select * from Security_Objects_Properties_Roles where RoleId='notRegistered') NotReg on Rest.ObjectName=NotReg.ObjectName and Rest.PropertyName=NotReg.PropertyName
where NotReg.ObjectName is null and AllU.ObjectName is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Objects_Properties_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Properties_Roles where RoleId='notRegistered') NotReg on allU.ObjectName=NotReg.ObjectName and allU.PropertyName=NotReg.PropertyName
where NotReg.ObjectName is null
UNION

-- Load NotRegisterd security
select * from Security_Objects_Properties_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Objects_Properties_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Properties_Roles where RoleId='Registered') NotReg on allU.ObjectName=NotReg.ObjectName and allU.PropertyName=NotReg.PropertyName
left join (select * from Security_Objects_Properties_Roles where RoleId=@RoleId) mySec on allU.ObjectName=mySec.ObjectName and allU.PropertyName=mySec.PropertyName
where NotReg.ObjectName is null and mySec.ObjectName is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Objects_Properties_Roles where RoleId='Registered') NotReg
left join (select * from Security_Objects_Properties_Roles where RoleId=@roleid) mySec on NotReg.ObjectName=mySec.ObjectName and NotReg.PropertyName=mySec.PropertyName
where mySec.ObjectName is null
UNION

-- Load Actual Role Group Security
select * from Security_Objects_Properties_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Objects_Properties_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Properties_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Properties_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName, PropertyName

end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Objects_Properties_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Objects_Proper

pNet_LoadObjectPropertySecurity Stored

ties_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Properties_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Properties_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName, PropertyName

END


Return -1
END

pNet_LoadObjectRelations Stored


CREATE PROCEDURE [dbo].[pNet_LoadObjectRelations](
@ChildName T_ObjectName,
@ObjectName T_ObjectName )
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectRelations
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Property dependencies from Objects_Objects Table into Framework
--#PARAMETERS
-- @ChildName: Used to load depending from.
-- @ObjectName: Used to load depending by.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
if @ChildName is null
select oo.* from Objects_Objects oo inner join Objects on oo.Childcollection =Objects.ObjectName
where Objects.Active<>0 and oo.ObjectName=@ObjectName order by [order]
else
select oo.* from Objects_Objects oo inner join Objects on oo.ChildCollection =Objects.ObjectName
where Objects.Active<>0 and oo.Childcollection=@ChildName order by [order]

Return -1
END

pNet_LoadObjectReportsCollection Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectReportsCollection](@ObjectName T_ObjectName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectReportsCollection
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Report definitons from Reports,Objects_Reports, Reports_Params
-- Icons,Toolbars and Reports_Params_Dependencies Table into Framework
--#PARAMETERS
-- @ObjectName: Object Name to use as filter.
--#OBSERVATIONS
-- Loas reports parameters and dependencies all in one
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 08/02/2018- Rubén Pardo - Add Enabled and Disabled values properties.
-- 16/06/2021- Fernando Fernández Load Reports without icon
----------------------------------------------------------------------------------
BEGIN

select Reports.*, obr.SqlEnabled, obr.SQLEnabled,obr.EnabledProperty,obr.EnabledValues,obr.DisabledValues, obr.Active,isnull(ParamCount,0) as ParamCount , Icons.CSSClass
From Reports inner join Objects_Reports obr on reports.ReportName=obr.ReportName
left Join (Select ReportName, Count(ReportName) As ParamCount
from Reports_Params group by ReportName ) rp On Reports.ReportName= rp.ReportName
left join Icons ON Reports.IconName = Icons.IconName
where obr.ObjectName=@ObjectName and obr.active <>0
Order By [Order]

SELECT rp.* ,i.CSSClass as iconClass,tb.ToolbarName
FROM Reports AS r INNER JOIN Reports_Params rp on r.ReportName=rp.ReportName
inner join Objects_Reports obr on r.ReportName=obr.ReportName
left join icons i on rp.IconName=i.IconName
left join toolbars tb on rp.toolbarName=tb.ToolbarName
where obr.active <>0 and obr.ObjectName=@ObjectName
Order By [Order]

SELECT pd.* ,obr.ObjectName
FROM reports AS r INNER JOIN Reports_Params rp on r.ReportName=rp.ReportName
inner join Objects_Reports obr on r.ReportName=obr.ReportName
inner join Reports_Params_Dependencies pd on pd.ReportName=rp.ReportName
where obr.active <>0 and obr.ObjectName=@ObjectName
Order By pd.ReportName,pd.[Order]


Return -1
END

pNet_LoadObjectSecurity Stored

CREATE PROCEDURE [dbo].[pNet_LoadObjectSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Security definition from Security_Objects_Roles and
-- Security_Objects_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all objects overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedObjectSecurity Rest
left join (select * from Security_Objects_Roles where RoleId='allUsers') AllU on allU.ObjectName=Rest.ObjectName
left join (select * from Security_Objects_Roles where RoleId='notRegistered') NotReg on Rest.ObjectName=NotReg.ObjectName
where NotReg.ObjectName is null and AllU.ObjectName is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Objects_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Roles where RoleId='notRegistered') NotReg on allU.ObjectName=NotReg.ObjectName
where NotReg.ObjectName is null
UNION

-- Load NotRegisterd security
select * from Security_Objects_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Objects_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Roles where RoleId='Registered') NotReg on allU.ObjectName=NotReg.ObjectName
left join (select * from Security_Objects_Roles where RoleId=@RoleId) mySec on allU.ObjectName=mySec.ObjectName
where NotReg.ObjectName is null and mySec.ObjectName is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Objects_Roles where RoleId='Registered') NotReg
left join (select * from Security_Objects_Roles where RoleId=@roleid) mySec on NotReg.ObjectName=mySec.ObjectName
where mySec.ObjectName is null
UNION

-- Load Actual Role Group Security
select * from Security_Objects_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Objects_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName

end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Objects_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Objects_Users where UserId =@UserId

-- Load Faculty security
Select * from Security_Objects_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ObjectName

END


Return -1
END

pNet_LoadObjectTemplatesCollection Stored



CREATE PROCEDURE [dbo].[pNet_LoadObjectTemplatesCollection]( @ObjectName T_ObjectName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadObjectTemplatesCollection
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Object Templates definition and Template Grouping fields from Objects_Templates
-- and Objects_Templates_Groups Tables into Framework
--#PARAMETERS
-- @ObjectName: Object Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

SELECT * FROM Objects_Templates WHERE ObjectName=@ObjectName AND Active<>0
SELECT og.* FROM Objects_Templates_Groups og inner join Objects_Templates ot on og.TemplateId=ot.TemplateId WHERE ObjectName=@ObjectName and ot.Active<>0 order by og.TemplateId,og.[order]

Return -1
END

pNet_LoadOffLineMenus Stored



CREATE PROCEDURE [dbo].[pNet_LoadOffLineMenus](@AppName VARCHAR(50))
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadOffLineMenus]
--#CREATION
-- 07/10/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Offline Menus given a AppName
-- Loads from table Offline_Menus
--#PARAMETERS
-- @AppName: The AppName.
--#OBSERVATIONS
--
--#CHANGES
-- 01/10/2019- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

SELECT
M.* ,i.CSSClass as IconClass ,i.ImagePath, MT.Descrip AS strType

FROM
Offline_Menus M
LEFT JOIN Icons i on M.IconName =i.IconName
LEFT JOIN Offline_Menus_Types MT ON M.TypeId = MT.TypeId
Where AppName=@AppName

ORDER BY
M.[Order], M.Descrip

RETURN -1
END

pNet_LoadPagesDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadPagesDefinition](
@PageType as nvarchar(50),
@ObjectName as t_ObjectName,
@PageName T_PageName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadPagesDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading page Definition from pages Table and Pages_Modules
-- Table into Framework. also includes Pages_Modules_Tabs definition
--#PARAMETERS
-- @PageType optional Page Type
-- @PageName optional page Id
-- @ObjectName optional ObjectName
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 01/11/2016- David Miralpeix Added tab options
-- 15/11/2016- David Miralpeix Added page module relation options
-- 11/04/2017- David Miralpeix Added ShowModule When new Options
-- 06/10/2017- JJR. Add module events
-- 08/02/2018- Sergio Vera Add page module ConnStringID
----------------------------------------------------------------------------------
BEGIN

declare @CollectionName as t_ObjectName

select @CollectionName=ObjectName from Objects where ObjectChildName=@objectName


if not @PageName is null
BEGIN

--Pages
select p.*, l.LayoutTemplate,i.CSSClass from Pages p inner join Layouts l on p.LayoutName=l.LayoutName inner join icons i on p.IconName=i.IconName where p.PageName=@PageName

--Modules
select pm.PageName,pm.Modulename,pm.LayoutPositionId,pm.RelationWhere,pm.[Order],pm.SQLEnabled,pm.SQLEnabledDescrip,pm.ConnStringID,
m.params,m.CollapsibleButton,m.FullscreenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,m.presetName,
mc.TemplateHTML as ContainerTemplate,mc.CSSClass as ContainerClass,
mt.webcomponent as WebComponent,pre.Title as PresetText,preI.CssClass as PresetIconName,
case when pm.Title is null then m.title else pm.Title end as Title,case when pm.HeaderClass is null then m.HeaderClass else pm.HeaderClass end as HeaderClass,case when pm.ModuleClass is null then m.ModuleClass else pm.ModuleClass end as ModuleClass,
case when pmi.IconName is null then Icons.IconName else pm.IconName end as IconName,case when pmi.IconName is null then Icons.CSSClass else pmi.CSSClass end as IconCssClass,case when pmi.IconName is null then Icons.ImagePath else pmi.ImagePath end as IconImagePath,
tabs.TabModuleName as TabName,tabs.[Order] as TabOrder, m.ObjectName, m.ManualInit
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Types mt on m.TypeId=mt.TypeId
inner join Icons on m.IconName=icons.IconName
Left Join vPages_Modules_Tabs tabs on pm.ModuleName=tabs.ModuleName and tabs.PageName=pm.PageName
left join Icons pmi on pm.IconName=pmi.IconName
left join Objects_Presets pre on m.PresetName=pre.PresetName
left join Icons preI on pre.IconName=preI.IconName
where pm.PageName=@PageName order by pm.[order]

--Events
select pm.PageName,pm.Modulename,pme.ModuleEventId,pme.EventClass,pme.EventType,pme.EventAction,pme.ProcessName,pme.ObjectFilter,pme.PropertyFilter,pme.ProcessFilter,pme.ModuleFilter,pme.PageFilter,pme.MethodFilter
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join modules_events pme on m.modulename=pme.modulename
where pm.PageName=@PageName order by pm.[order]


END
else If not @PageType is null and Not @ObjectName is null
BEGIN

--Pages
select p.*, l.LayoutTemplate,i.CSSClass from Pages p inner join Layouts l on p.LayoutName=l.LayoutName inner join icons i on p.IconName=i.IconName where (p.typeId=@PageType and objectName is null) or (p.typeId=@PageType and objectName =@ObjectName)

--Modules
select pm.PageName,pm.ModuleName,pm.LayoutPositionId,pm.RelationWhere,pm.[Order],pm.SQLEnabled,pm.SQLEnabledDescrip,pm.ConnStringID,
m.params,m.CollapsibleButton,m.Full

pNet_LoadPagesDefinition Stored

screenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,
m.params,m.CollapsibleButton,m.FullscreenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,m.presetName,
mc.TemplateHTML as ContainerTemplate,mc.CSSClass as ContainerClass,
mt.webcomponent as WebComponent,pre.Title as PresetText,preI.CssClass as PresetIconName,
case when pm.Title is null then m.title else pm.Title end as Title,case when pm.HeaderClass is null then m.HeaderClass else pm.HeaderClass end as HeaderClass,case when pm.ModuleClass is null then m.ModuleClass else pm.ModuleClass end as ModuleClass,
case when pmi.IconName is null then Icons.IconName else pm.IconName end as IconName,case when pmi.IconName is null then Icons.CSSClass else pmi.CSSClass end as IconCssClass,case when pmi.IconName is null then Icons.ImagePath else pmi.ImagePath end as IconImagePath,
tabs.TabModuleName as TabName,tabs.[Order] as TabOrder, m.ObjectName, m.ManualInit
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Types mt on m.TypeId=mt.TypeId
inner join Icons on m.IconName=icons.IconName
inner join pages p on p.PageName=pm.PageName
Left Join vPages_Modules_Tabs tabs on pm.ModuleName=tabs.ModuleName and tabs.PageName=pm.PageName
left join Icons pmi on pm.IconName=pmi.IconName
left join Objects_Presets pre on m.PresetName=pre.PresetName
left join Icons preI on pre.IconName=preI.IconName
where (p.TypeId=@PageType and p.objectName is null) or (p.typeId=@PageType and p.objectName =@ObjectName) order by pm.[order]

--Events
select pm.PageName,pm.Modulename,pme.ModuleEventId,pme.EventClass,pme.EventType,pme.EventAction,pme.ProcessName,pme.ObjectFilter,pme.PropertyFilter,pme.ProcessFilter,pme.ModuleFilter,pme.PageFilter,pme.MethodFilter
from Pages_Modules pm
inner join pages p on p.PageName=pm.PageName
inner join modules m on pm.ModuleName=m.ModuleName
inner join modules_events pme on m.modulename=pme.modulename
WHERE (p.TypeId=@PageType and p.objectName is null) or (p.typeId=@PageType and p.objectName =@ObjectName) order by pm.[order]

END
else If not @PageType is null
BEGIN

--Pages
select p.*, l.LayoutTemplate,i.CSSClass from Pages p inner join Layouts l on p.LayoutName=l.LayoutName inner join icons i on p.IconName=i.IconName where p.typeId=@PageType

--Modules
select pm.PageName,pm.ModuleName,pm.LayoutPositionId,pm.RelationWhere,pm.[Order],pm.SQLEnabled,pm.SQLEnabledDescrip,pm.ConnStringID,
m.params,m.CollapsibleButton,m.FullscreenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,m.presetName,
mc.TemplateHTML as ContainerTemplate,mc.CSSClass as ContainerClass,
mt.webcomponent as WebComponent,pre.Title as PresetText,preI.CssClass as PresetIconName,
case when pm.Title is null then m.title else pm.Title end as Title,case when pm.HeaderClass is null then m.HeaderClass else pm.HeaderClass end as HeaderClass,case when pm.ModuleClass is null then m.ModuleClass else pm.ModuleClass end as ModuleClass,
case when pmi.IconName is null then Icons.IconName else pm.IconName end as IconName,case when pmi.IconName is null then Icons.CSSClass else pmi.CSSClass end as IconCssClass,case when pmi.IconName is null then Icons.ImagePath else pmi.ImagePath end as IconImagePath,
tabs.TabModuleName as TabName,tabs.[Order] as TabOrder, m.ObjectName, m.ManualInit
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Types mt on m.TypeId=mt.TypeId
inner join Icons on m.IconName=icons.IconName
inner join pages p on p.PageName=pm.PageName
Left Join vPages_Modules_Tabs tabs on pm.ModuleName=tabs.ModuleName and tabs.PageName=pm.PageName
left join Icons pmi on pm.IconName=pmi.IconName
left join Objects_Presets pre on m.PresetName=pre.PresetName
left join Icons pr

pNet_LoadPagesDefinition Stored

eI on pre.IconName=preI.IconName
where p.TypeId=@PageType order by pm.[order]

--Events
select pm.PageName,pm.Modulename,pme.ModuleEventId,pme.EventClass,pme.EventType,pme.EventAction,pme.ProcessName,pme.ObjectFilter,pme.PropertyFilter,pme.ProcessFilter,pme.ModuleFilter,pme.PageFilter,pme.MethodFilter
from Pages_Modules pm
inner join pages p on p.PageName=pm.PageName
inner join modules m on pm.ModuleName=m.ModuleName
inner join modules_events pme on m.modulename=pme.modulename
WHERE p.TypeId=@PageType order by pm.[order]

END
else
BEGIN

--Pages
select p.*, l.LayoutTemplate, i.CSSClass from Pages p inner join Layouts l on p.LayoutName=l.LayoutName inner join icons i on p.IconName=i.IconName

--Modules
select pm.PageName,pm.ModuleName,pm.LayoutPositionId,pm.RelationWhere,pm.[Order],pm.SQLEnabled,pm.SQLEnabledDescrip,pm.ConnStringID,
m.params,m.CollapsibleButton,m.FullscreenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,m.presetName,
mc.TemplateHTML as ContainerTemplate,mc.CSSClass as ContainerClass,
mt.webcomponent as WebComponent,pre.Title as PresetText,preI.CssClass as PresetIconName,
case when pm.Title is null then m.title else pm.Title end as Title,case when pm.HeaderClass is null then m.HeaderClass else pm.HeaderClass end as HeaderClass,case when pm.ModuleClass is null then m.ModuleClass else pm.ModuleClass end as ModuleClass,
case when pmi.IconName is null then Icons.IconName else pm.IconName end as IconName,case when pmi.IconName is null then Icons.CSSClass else pmi.CSSClass end as IconCssClass,case when pmi.IconName is null then Icons.ImagePath else pmi.ImagePath end as IconImagePath,
tabs.TabModuleName as TabName,tabs.[Order] as TabOrder, m.ObjectName, m.ManualInit
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Types mt on m.TypeId=mt.TypeId
inner join Icons on m.IconName=icons.IconName
Left Join vPages_Modules_Tabs tabs on pm.ModuleName=tabs.ModuleName and tabs.PageName=pm.PageName
left join Icons pmi on pm.IconName=pmi.IconName
left join Objects_Presets pre on m.PresetName=pre.PresetName
left join Icons preI on pre.IconName=preI.IconName
order by pm.[order]

--Events
select pm.PageName,pm.Modulename,pme.ModuleEventId,pme.EventClass,pme.EventType,pme.EventAction,pme.ProcessName,pme.ObjectFilter,pme.PropertyFilter,pme.ProcessFilter,pme.ModuleFilter,pme.PageFilter,pme.MethodFilter
from Pages_Modules pm
inner join pages p on p.PageName=pm.PageName
inner join modules m on pm.ModuleName=m.ModuleName
inner join modules_events pme on m.modulename=pme.modulename
order by pm.[order]

END
Return -1
END

pNet_LoadPagesSecurity Stored


CREATE PROCEDURE [dbo].[pNet_LoadPagesSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS


----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadPagesSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Pages Security definition from Security_Pages_Roles and
-- Security_Pages_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 01/01/2017- David Miralpeix (added vNet_AllRestrictedPagesSecurity)
----------------------------------------------------------------------------------
BEGIN
if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all pages overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedPagesSecurity Rest
left join (select * from Security_Pages_Roles where RoleId='allUsers') AllU on allU.PageName=Rest.PageName
left join (select * from Security_Pages_Roles where RoleId='notRegistered') NotReg on Rest.PageName=NotReg.PageName
where NotReg.PageName is null and AllU.PageName is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Pages_Roles where RoleId='allUsers') AllU
left join (select * from Security_Pages_Roles where RoleId='notRegistered') NotReg on allU.PageName=NotReg.PageName
where NotReg.PageName is null
UNION

-- Load NotRegisterd security
select * from Security_Pages_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Pages_Roles where RoleId='allUsers') AllU
left join (select * from Security_Pages_Roles where RoleId='Registered') NotReg on allU.PageName=NotReg.PageName
left join (select * from Security_Pages_Roles where RoleId=@RoleId) mySec on allU.PageName=mySec.PageName
where NotReg.PageName is null and mySec.PageName is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Pages_Roles where RoleId='Registered') NotReg
left join (select * from Security_Pages_Roles where RoleId=@roleid) mySec on NotReg.PageName=mySec.PageName
where mySec.PageName is null
UNION

-- Load Actual Role Group Security
select * from Security_Pages_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Pages_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Pages_Faculties Inner join AspNetUsers_Faculties a on Security_Pages_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by PageName


end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Pages_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Pages_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Pages_Faculties Inner join AspNetUsers_Faculties a on Security_Pages_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by PageName


END


Return -1
END

pNet_LoadPendingDifferences Stored

CREATE PROCEDURE [dbo].[pNet_LoadPendingDifferences]
@Version NVARCHAR(50)

AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadPendingDifferences]
--#CREATION
-- 03/10/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Gets the pending of apply differences after version upgrade
--#PARAMETERS
-- @Version: The version of the difference
--#OBSERVATIONS
--
--#CHANGES
-- 03/10/2017 - JJR - Initial version
----------------------------------------------------------------------------------
BEGIN TRY


SELECT DifferenceId as DifId,TableName,FieldName,RowKey,SystemValue as OldValue,UserValue,CurrentValue as NewValue,ManualValue,[Action] AS ActionId,Revised
FROM
Versions_Differences
WHERE
VersionNumber = @Version AND Applied = 0


RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_LoadPendingOutboxMails Stored

CREATE PROCEDURE [dbo].[pNet_LoadPendingOutboxMails]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadPendingOutboxMails
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading pending mails and attachments from outbox
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/05/2018- David Miralpeix
-- 06/02/2020- Sergio Vera
-- 15/06/2021- Fernando Fernández
----------------------------------------------------------------------------------
BEGIN

DECLARE @Mails as table (Id nvarchar(100))
DECLARE @MailBufferSize AS INT

set @MailBufferSize = (select SettingValue from Settings where SettingName='MailBufferSize')

if isnull(@MailBufferSize,0) = 0 BEGIN
INSERT INTO @Mails
SELECT Mails_Outbox.id FROM Mails_Outbox WHERE Status=1 AND (SendDate IS NULL OR Senddate <= GETDATE()) order by SendDate,Id desc
end
else BEGIN
INSERT INTO @Mails
SELECT top (@MailBufferSize) Mails_Outbox.id FROM Mails_Outbox WHERE Status=1 AND (SendDate IS NULL OR Senddate <= GETDATE()) order by SendDate,Id desc
end


SELECT Mails_Outbox.*, u.reference FROM Mails_Outbox left join ASPNETusers u on Mails_Outbox.UserId=u.Id INNER JOIN @Mails m on m.Id=Mails_Outbox.id WHERE Status=1 AND (SendDate IS NULL OR Senddate <= GETDATE())

Select * from Mails_Outbox_Attachments inner join Mails_Outbox on Mails_Outbox.Id=Mails_Outbox_Attachments.MailId INNER JOIN @Mails m on m.Id=Mails_Outbox.id where Status=1 and (SendDate is null or Senddate <= GETDATE())

UPDATE Mails_Outbox SET [Status] = 3 From Mails_Outbox left join ASPNETusers u on Mails_Outbox.UserId=u.Id INNER JOIN @Mails m on m.Id=Mails_Outbox.id WHERE Status=1 AND (SendDate IS NULL OR Senddate <= GETDATE())

Return -1
END

pNet_LoadPlugins Stored

CREATE PROCEDURE [dbo].[pNet_LoadPlugins]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadPlugins
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Plugins on index page
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

select * from plugins where enabled=1 order by [order]

Return -1
END

pNet_LoadPresets Stored

CREATE PROCEDURE [dbo].[pNet_LoadPresets](
@CollectionName as t_ObjectName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadPresets
--#CREATION
-- 05/09/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load Presets for a Object.
--#PARAMETERS
-- @CollectionName the collection name
--#OBSERVATIONS
--
--#CHANGES

----------------------------------------------------------------------------------
BEGIN

SELECT Objects_Presets.*, Icons.CSSClass FROM Objects_Presets inner join Icons on Objects_Presets.IconName=Icons.Iconname where ObjectName=@CollectionName
order by [order]

Return -1
END

pNet_LoadProcessDefinition Stored

CREATE PROCEDURE [dbo].[pNet_LoadProcessDefinition](@ProcessName T_ProcessName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadProcessDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Process definition from Processes,
-- Process_params, process_params_dependencies, icons, toolbars and webcomponets Tables into Framework
--#PARAMETERS
-- @ProcessName: Process Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- Rubén Pardo
-- 12/04/2017- Changed adminOnly to Process Table David Miralpeix
-- 08/08/2017- David Miralpeix Added ConfirmOnOkOption and CloseDialosOnOk
-- 02/10/2017- David Miralpeix Added Defaults field for redirections
-- 10/10/2017- David Miralpeix. Fix for custom controls
-- 05/01/2018- Alberto Criado Andrés Added ProcessDescrip
-- 23/01/2018- Alberto Criado Andrés Added CascadeDependencies
-- 20/03/2018- jjrodriguez. Send paramtypeid field value as a new field
-- 04/05/2018- Rubén Pardo Added UseRootSettingsPath Field
-- 17/07/2018- David Miralpeix. Added Run button text
-- 06/08/2018- Rubén Pardo - Add webapi security
-- 05/10/2018- Alberto Criado Andrés Added RootPathType Field And Delete UseRootSettingsPath Field
-- 05/09/2019- Sergio Vera Added ImageCompressionType Field, ImageMaxWidth Field,ImageMaxHeight Field
----------------------------------------------------------------------------------
BEGIN

/*Process*/
SELECT
p.[ProcessName],p.[ProcessDescrip],p.[TypeId] ,p.[ClassId],p.[ConfirmText],p.[JSforParams],p.[File],p.[Class] AS ClassName,p.[Method] AS MethodName,p.[StoredName],p.AdminOnly,p.ConfirmOkText,p.CloseDialogOnOk,p.[Defaults],
[TimeOut],[ConnStringId],[ExternalUrl],Defaults,TargetId ,[Code], [PageTypeId],[PageName],[HelpId],[ObjectName],[ObjectWhere],
ISNULL(ParamCount,0) AS ParamCount,TargetId,p.processFlowText,p.Auditable, p.Refresh,p.RunButtonText, isnull(WP.CanView,0) AS WebAPI_CanView, p.LoadProcessName, p.GipeParams,
p.ReturnTableNames
FROM
Processes p LEFT JOIN (SELECT ProcessName, COUNT(ProcessName) AS ParamCount FROM Processes_Params WHERE hide=0 GROUP BY ProcessName) rp ON p.ProcessName = rp.ProcessName
LEFT JOIN WebAPI_Processes WP ON p.ProcessName=WP.ProcessName
WHERE
P.ProcessName = @ProcessName

/*Process parameters with posible customized parameter*/
SELECT pp.ProcessName, pp.ParamName, pp.Hide, pp.ParamTypeId, pp.ParamTypeId AS ProcessParamTypeId, pp.TableName, pp.ObjectName, pp.DefaultValue, pp.Label, pp.Locked, pp.IOTypeId, pp.PositionX, pp.PositionY, pp.Width, pp.Height, pp.TypeId, pp.Mask,
pp.SQLFilter, pp.Autoselect, pp.SQLValueField,pp.SQLDisplayField, pp.SQLObjectName,pp.SQLViewName, pp.[SQLOfflineSentence], pp.[SQLOfflineOrderBy], pp.WhereSentence,
pp.DetachedFromProcess,
pp.SearchFunction, pp.SearchCollection, pp.SearchWhere, pp.SearchReturnFields, pp.SecurityObject,
pp.AllowNew, pp.AllowNewFunction, pp.AllowNewReturnFields, pp.AllowNewDefaults , pp.ObjNameLink, pp.ObjWhereLink, pp.TargetIdLink, pp.Style, pp.CSSClass,
pp.LabelStyle, pp.LabelCSSClass, pp.DecimalPlaces, pp.RootPath, pp.FormatString, pp.DirectTemplate, pp.Tag, pp.HelpId,
pp.ConnStringId, pp.IsRequired, pp.IsRequiredMessage,pp.minValue, pp.minValueMessage, pp.maxValue, pp.maxValueMessage, pp.RegExp, pp.RegExpText, pp.SQLValidator, pp.ValidatorMessage,
pp.OnChangeJsFunction, pp.OnChangeProcessName, pp.PlaceHolder, pp.IconName, pp.Separator, pp.CascadeDependencies, pp.RootPathType, pp.ImageCompressionType, pp.ImageMaxWidth, pp.ImageMaxHeight, pp.ExtensionId, e.Extensions,
pt.WebComponent, pt.OfflineWebComponent ,i.CSSClass as IconClass,tb.ToolbarName
,isnull(isnull(pp.[SQlSentence],ovSQL.SQLSentence),'select '+pp.SQLDisplayField+', '+pp.SQLValueField+' from '+oSQL.TableName) as SQLSentence
FROM Processes_P

pNet_LoadProcessDefinition Stored

arams pp
inner join Objects_properties_types pt on pp.TypeId=pt.TypeId
left join icons i on pp.IconName=i.iconName
left join Extensions e ON pp.ExtensionId = e.ExtensionId
left join toolbars tb on pp.toolbarName=tb.ToolbarName
left join objects_views ovSQL on pp.SQLObjectName=ovSQL.ObjectName and pp.SQLViewName=ovSQL.ViewName
left join objects oSQL on pp.SQLObjectName=oSQL.ObjectName and pp.SQLViewName is null
WHERE
PP.ProcessName = @ProcessName and pp.TypeId<>'custom'

UNION
SELECT pp.ProcessName, pp.ParamName, pp.Hide, opt.TypeId as ParamTypeId, pp.ParamTypeId AS ProcessParamTypeId, pp.TableName, pp.ObjectName, pp.DefaultValue, pp.Label, pp.Locked, pp.IOTypeId, pp.PositionX, pp.PositionY, isnull(pp.Width,opt.width) as Width,isnull(pp.Height,opt.height) as Height, opt.[TypeId] ,opt.[Mask] ,
opt.[SQLFilter], opt.Autoselect, opt.[SQLValueField] ,opt.[SQLDisplayField], ISNULL(opt.[SQLObjectName],pp.[SQLObjectName]) as [SQLObjectName], isnull(opt.[SQLViewName],pp.[SQLViewName]) as [SQLViewName] ,ISNULL(opt.[SQLOfflineSentence],pp.[SQLOfflineSentence]) AS SQLOfflineSentence, ISNULL(opt.[SQLOfflineOrderBy],pp.[SQLOfflineOrderBy]) AS SQLOfflineOrderBy, CASE when len(pp.wheresentence)<=0 then opt.[WhereSentence] else pp.WhereSentence end as WhereSentence ,
opt.[DetachedFromDB] as DetachedFromProcess ,
isnull(pp.[SearchFunction],opt.[SearchFunction]) as [SearchFunction], isnull(pp.[SearchCollection],opt.[SearchCollection]) as [SearchCollection], isnull(pp.[SearchWhere],opt.[SearchWhere]) as [SearchWhere], isnull(pp.[SearchReturnFields],opt.[SearchReturnFields]) as [SearchReturnFields],
opt.[SecurityObject],
opt.[AllowNew],opt.[AllowNewFunction],opt.[AllowNewReturnFields], opt.[AllowNewDefaults] ,opt.[ObjNameLink],opt.[ObjWhereLink],opt.[TargetIdLink],isnull(pp.[Style],opt.[Style]) as Style,isnull(pp.[CSSClass],opt.[CSSClass]) as CSSClass,
isnull(pp.[LabelStyle],opt.[LabelStyle]) as LabelStyle,isnull(pp.[LabelCSSClass],opt.[LabelCSSClass]) as LabelCSSClass,opt.[DecimalPlaces],opt.RootPath, opt.FormatString, opt.DirectTemplate,opt.Tag, opt.HelpId,
isnull(pp.[ConnStringId],opt.[ConnStringId]) AS [ConnStringId] ,case when opt.[IsRequired]=1 then 1 else pp.IsRequired end as IsRequired , case when len(opt.[IsRequiredMessage])>0 then opt.[IsRequiredMessage] else pp.[IsRequiredMessage] end as [IsRequiredMessage] ,opt.[minValue],opt.[minValueMessage],opt.[maxValue],opt.[maxValueMessage],opt.[RegExp],opt.[RegExpText], opt.SQLValidator, opt.ValidatorMessage,
opt.[OnChangeJsFunction],isnull(pp.[OnChangeProcessName],opt.[OnChangeProcessName]) as [OnChangeProcessName],opt.[PlaceHolder],pp.IconName,pp.separator,pp.CascadeDependencies, pp.RootPathType, pp.ImageCompressionType, pp.ImageMaxWidth, pp.ImageMaxHeight, pp.ExtensionId, e.Extensions,
pt.WebComponent, pt.OfflineWebComponent ,isnull(iop.CSSClass,iopt.CSSClass) AS IconClass,tb.ToolbarName
,isnull(isnull(opt.[SQlSentence],ovSQL.SQLSentence),'select '+opt.SQLDisplayField+', '+opt.SQLValueField+' from '+oSQL.TableName) as SQLSentence
FROM Processes_Params pp
Inner join Objects_Properties_Templates opt on pp.CustomPropName=opt.CustomPropName and pp.TypeId='custom'
inner join Objects_properties_types pt on opt.TypeId=pt.TypeId
left join icons iop on pp.IconName=iop.IconName
left join icons iopt on opt.IconName=iopt.IconName
left join Extensions e ON pp.ExtensionId = e.ExtensionId
left join toolbars tb on pp.toolbarName=tb.ToolbarName
left join objects_views ovSQL on isnull(opt.[SQLObjectName],pp.[SQLObjectName])=ovSQL.ObjectName and isnull(opt.[SQLViewName],pp.[SQLViewName])=ovSQL.ViewName
left join objects oSQL on isnull(opt.[SQLObjectName],pp.[SQLObjectName])=oSQL.ObjectName and isnull(opt.[SQLViewName],pp.[SQLViewName]) is null
WHERE
PP.ProcessName = @ProcessName
ORDER BY
PositionY,PositionX

/*Process parameters dependencies*/
SELECT
pd.ProcessName,
pd.ParamNa

pNet_LoadProcessDefinition Stored

me,
pd.DependingParamName,
pd.[Order],
pd.Active,
pd.Descrip,
pd.SQLValue,
pd.SQLComboSentence,
pd.SQLComboFilter,
pd.SQLEnabled,
pd.EnabledValues,
pd.DisabledValues,
pd.SQLVisible,
pd.VisibleValues,
pd.HiddenValues,
pd.SQLClass,
pd.SQLRequired,
pd.RequiredValues,
pd.NotRequiredValues,
pd.PropertyValue,
pd.SQLCustomProperty,
pd.CusPropName,
isnull(pd.ConnStringId,pp.ConnStringId) as ConnStringId,
pd.OriginId
FROM
Processes_Params_Dependencies pd inner join
processes_params pp on pd.ProcessName=pp.ProcessName and pd.ParamName=pp.ParamName
WHERE
PD.ProcessName = @ProcessName
ORDER BY
PD.ProcessName,[Order]

Return -1
END

pNet_LoadProfileInterfaces Stored

CREATE PROCEDURE [dbo].[pNet_LoadProfileInterfaces]
@ProfileName [dbo].[T_ProfileName]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadProfileInterfaces
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading profile interfaces for a given ProfileName
-- Loads from table Interfaces and ASPNetProfiles
--#PARAMETERS
-- @ProfileName: The Profile Id.
--#OBSERVATIONS
-- Loads Profile Info and the two interfaces, one for web and one for Mobile
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

select * from AspNetProfiles where ProfileName=@ProfileName

select i.*
From AspNetProfiles p inner join interfaces i on p.WebInterfaceName =i.InterfaceName
where p.ProfileName=@ProfileName


select i.*
From AspNetProfiles p inner join interfaces i on p.MobileInterfaceName =i.InterfaceName
where p.ProfileName=@ProfileName


Return -1
END

pNet_LoadReportDefinition Stored


CREATE PROCEDURE [dbo].[pNet_LoadReportDefinition](@ReportName T_ReportName)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadReportDefinition
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Report definitons from Reports,Reports_Params
-- icons, toolbars and Reports_Params_Dependencies Table into Framework
--#PARAMETERS
-- @ReportName: Report name to use as filter.
--#OBSERVATIONS
-- Loas reports parameters and dependencies all in one
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 10/10/2017- David Miralpeix. Fix for custom controls
-- 23/01/2018- Alberto Criado Andrés Added CascadeDependencies
-- 04/05/2018- Rubén Pardo Added UseRootSettingsPath Field
-- 05/10/2018- Alberto Criado Andrés Added RootPathType Field And Delete UseRootSettingsPath Field
-- 05/09/2019- Sergio Vera Added ImageCompressionType Field, ImageMaxWidth Field,ImageMaxHeight Field
-- 16/06/2021- Fernando Fernández Load Reports without icon
----------------------------------------------------------------------------------
BEGIN
/*Reports*/
select Reports.*, isnull(ParamCount,0) as ParamCount , Icons.CSSClass
From Reports left Join (Select ReportName, Count(ReportName) As ParamCount
from Reports_Params where hide=0 group by ReportName ) rp On Reports.ReportName= rp.ReportName
left join Icons ON Reports.IconName = Icons.IconName
where Reports.ReportName=@ReportName
Order By Reports.[Order]


/*Reports parameters with posible customized parameter*/
SELECT pp.ReportName,pp.ParamName, pp.Hide, pp.TypeId, pp.DefaultValue, pp.Label, pp.Locked, pp.PositionX, pp.PositionY, pp.Width, pp.Height, pp.TypeId, pp.Mask,
pp.SQLFilter, pp.Autoselect, pp.SQLValueField,pp.SQLDisplayField, pp.SQLObjectName,pp.SQLViewName,pp.[SQLOfflineSentence], pp.[SQLOfflineOrderBy], pp.WhereSentence,
pp.DetachedFromProcess, pp.SearchFunction, pp.SearchCollection, pp.SearchWhere, pp.SearchReturnFields, pp.SecurityObject,
pp.AllowNew, pp.AllowNewFunction, pp.AllowNewReturnFields, pp.AllowNewDefaults, pp.ObjNameLink, pp.ObjWhereLink, pp.TargetIdLink, pp.Style, pp.CSSClass,
pp.LabelStyle, pp.LabelCSSClass, pp.DecimalPlaces, pp.RootPath, pp.FormatString, pp.DirectTemplate, pp.Tag, pp.HelpId,
pp.ConnStringId, pp.IsRequired, pp.IsRequiredMessage,pp.minValue, pp.minValueMessage, pp.maxValue, pp.maxValueMessage, pp.RegExp, pp.RegExpText, pp.SQLValidator, pp.ValidatorMessage,
pp.OnChangeJsFunction, pp.OnChangeProcessName, pp.PlaceHolder, pp.IconName, pp.Separator, pp.CascadeDependencies, pp.RootPathType, pp.ImageCompressionType,pp.ImageMaxWidth,pp.ImageMaxHeight,pp.ExtensionId,e.Extensions,
pt.WebComponent,pt.OfflineWebComponent ,i.CSSClass as IconClass,tb.ToolbarName
,isnull(isnull(pp.[SQlSentence],ovSQL.SQLSentence),'select '+pp.SQLDisplayField+', '+pp.SQLValueField+' from '+oSQL.TableName) as SQLSentence
FROM Reports AS r INNER JOIN Reports_Params pp on r.ReportName=pp.ReportName
inner join Objects_properties_types pt on pp.TypeId=pt.TypeId
left join icons i on pp.IconName=i.IconName
left join Extensions e ON pp.ExtensionId = e.ExtensionId
left join toolbars tb on pp.toolbarname=tb.Toolbarname
left join objects_views ovSQL on pp.SQLObjectName=ovSQL.ObjectName and pp.SQLViewName=ovSQL.ViewName
left join objects oSQL on pp.SQLObjectName=oSQL.ObjectName and pp.SQLViewName is null
where r.ReportName=@ReportName and pp.TypeId<>'custom'


UNION
SELECT pp.ReportName,pp.ParamName, pp.Hide, opt.TypeId, pp.DefaultValue, pp.Label, pp.Locked, pp.PositionX, pp.PositionY, isnull(pp.Width,opt.width) as Width,isnull(pp.Height,opt.height) as Height, opt.[TypeId] ,opt.[Mask] ,
opt.[SQLFilter], opt.[Autoselect], opt.[SQLValueField] ,opt.[SQLDisplayField], ISNULL(opt.[SQLObjectName],pp.[SQLObjectName]) as [SQLO

pNet_LoadReportDefinition Stored

bjectName], isnull(opt.[SQLViewName],pp.[SQLViewName]) as [SQLViewName] ,ISNULL(opt.[SQLOfflineSentence],pp.[SQLOfflineSentence]) AS SQLOfflineSentence, ISNULL(opt.[SQLOfflineOrderBy],pp.[SQLOfflineOrderBy]) AS SQLOfflineOrderBy, CASE when len(pp.wheresentence)<=0 then opt.[WhereSentence] else pp.WhereSentence end as WhereSentence ,
opt.[DetachedFromDB] as DetachedFromProcess ,
isnull(pp.[SearchFunction],opt.[SearchFunction]) as [SearchFunction], isnull(pp.[SearchCollection],opt.[SearchCollection]) as [SearchCollection], isnull(pp.[SearchWhere],opt.[SearchWhere]) as [SearchWhere], isnull(pp.[SearchReturnFields],opt.[SearchReturnFields]) as [SearchReturnFields],
opt.[SecurityObject],
opt.[AllowNew],opt.[AllowNewFunction],opt.[AllowNewReturnFields], opt.[AllowNewDefaults] ,opt.[ObjNameLink],opt.[ObjWhereLink],opt.[TargetIdLink],isnull(pp.[Style],opt.[Style]) as Style,isnull(pp.[CSSClass],opt.[CSSClass]) as CSSClass,
isnull(pp.[LabelStyle],opt.[LabelStyle]) as LabelStyle,isnull(pp.[LabelCSSClass],opt.[LabelCSSClass]) as LabelCSSClass,opt.[DecimalPlaces],opt.RootPath, opt.FormatString, opt.DirectTemplate,opt.Tag, opt.HelpId,
isnull(pp.[ConnStringId],opt.[ConnStringId]) AS [ConnStringId] ,case when opt.[IsRequired]=1 then 1 else pp.IsRequired end as IsRequired , case when len(opt.[IsRequiredMessage])>0 then opt.[IsRequiredMessage] else pp.[IsRequiredMessage] end as [IsRequiredMessage],opt.[minValue],opt.[minValueMessage],opt.[maxValue],opt.[maxValueMessage],opt.[RegExp],opt.[RegExpText], opt.SQLValidator, opt.ValidatorMessage,
opt.[OnChangeJsFunction],isnull(pp.[OnChangeProcessName],opt.[OnChangeProcessName]) as [OnChangeProcessName],opt.[PlaceHolder],pp.IconName,pp.separator, pp.CascadeDependencies ,pp.RootPathType,pp.ImageCompressionType,pp.ImageMaxWidth,pp.ImageMaxHeight,pp.ExtensionId,e.Extensions,
pt.WebComponent, pt.OfflineWebComponent ,isnull(iop.CSSClass,iopt.CSSClass) AS IconClass,tb.ToolbarName
,isnull(isnull(opt.[SQlSentence],ovSQL.SQLSentence),'select '+opt.SQLDisplayField+', '+opt.SQLValueField+' from '+oSQL.TableName) as SQLSentence
FROM Reports AS r INNER JOIN Reports_Params pp on r.ReportName=pp.ReportName
Inner join Objects_Properties_Templates opt on pp.CustomPropName=opt.CustomPropName and pp.TypeId='custom'
inner join Objects_properties_types pt on opt.TypeId=pt.TypeId
left join icons iop on pp.IconName=iop.IconName
left join icons iopt on opt.IconName=iopt.IconName
left join Extensions e ON pp.ExtensionId = e.ExtensionId
left join toolbars tb on pp.toolbarname=tb.Toolbarname
left join objects_views ovSQL on isnull(opt.[SQLObjectName],pp.[SQLObjectName])=ovSQL.ObjectName and isnull(opt.[SQLViewName],pp.[SQLViewName])=ovSQL.ViewName
left join objects oSQL on isnull(opt.[SQLObjectName],pp.[SQLObjectName])=oSQL.ObjectName and isnull(opt.[SQLViewName],pp.[SQLViewName]) is null
WHERE
PP.ReportName = @ReportName

ORDER BY
PositionY,PositionX


/*Dependencies */
SELECT
pd.ReportName,
pd.ParamName,
pd.DependingParamName,
pd.[order],
pd.Active,
pd.Descrip,
pd.SQLValue,
pd.SQLComboSentence,
pd.SQLComboFilter,
pd.SQLEnabled,
pd.EnabledValues,
pd.DisabledValues,
pd.SQLVisible,
pd.VisibleValues,
pd.HiddenValues,
pd.SQLClass,
pd.SQLRequired,
pd.RequiredValues,
pd.NotRequiredValues,
pd.PropertyValue,
pd.SQLCustomProperty,
pd.CusPropName,
isnull(pd.ConnStringId,rp.ConnStringId) as ConnStringId,
pd.OriginId
FROM reports AS r INNER JOIN Reports_Params rp on r.ReportName=rp.ReportName
inner join Reports_Params_Dependencies pd on pd.ReportName=rp.ReportName
where r.ReportName=@ReportName
Order By pd.ReportName,pd.[Order]




Return -1
END

pNet_LoadReportsSecurity Stored



CREATE PROCEDURE [dbo].[pNet_LoadReportsSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS

----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadReportsSecurity
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Report Security definition from Security_Reports_Roles and
-- Security__Reports_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 01/01/2017- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all report overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedReportsSecurity Rest
left join (select * from Security_Reports_Roles where RoleId='allUsers') AllU on allU.ReportName=Rest.ReportName
left join (select * from Security_Reports_Roles where RoleId='notRegistered') NotReg on Rest.ReportName=NotReg.ReportName
where NotReg.ReportName is null and AllU.ReportName is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Reports_Roles where RoleId='allUsers') AllU
left join (select * from Security_Reports_Roles where RoleId='notRegistered') NotReg on allU.ReportName=NotReg.ReportName
where NotReg.ReportName is null
UNION

-- Load NotRegisterd security
select * from Security_Reports_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Reports_Roles where RoleId='allUsers') AllU
left join (select * from Security_Reports_Roles where RoleId='Registered') NotReg on allU.ReportName=NotReg.ReportName
left join (select * from Security_Reports_Roles where RoleId=@RoleId) mySec on allU.ReportName=mySec.ReportName
where NotReg.ReportName is null and mySec.ReportName is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Reports_Roles where RoleId='Registered') NotReg
left join (select * from Security_Reports_Roles where RoleId=@roleid) mySec on NotReg.ReportName=mySec.ReportName
where mySec.ReportName is null
UNION

-- Load Actual Role Group Security
select * from Security_Reports_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Reports_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Reports_Faculties Inner join AspNetUsers_Faculties a on Security_Reports_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ReportName

end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Reports_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Reports_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Reports_Faculties Inner join AspNetUsers_Faculties a on Security_Reports_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by ReportName

END


Return -1

END

pNet_LoadScriptJobs Stored



CREATE PROCEDURE [dbo].[pNet_LoadScriptJobs]
(@ConnStringId NVARCHAR(255))

AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadScriptJobs
--#CREATION
-- 28/05/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load new script jobs to execute them.
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN
Select ScriptId, ExecuteOrder, Script
FROM Scripts_Jobs
WHERE (State='P' OR State= 'E') AND ConnStringId=@ConnStringId
ORDER BY ExecuteOrder ASC

RETURN -1
END

pNet_LoadSearchTypesDefinition Stored



CREATE PROCEDURE [dbo].[pNet_LoadSearchTypesDefinition]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadSearchTypesDefinition
--#CREATION
-- 08/03/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Combos with filter types
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 08/03/2017 - Rubén Pardo
-- 31/07/2017 - JJR - Return filter types
----------------------------------------------------------------------------------
BEGIN

select Type from Objects_Search_Types

select PropertySearchType,Descrip,WebComponent,DefaultSize,IconName from Objects_Search_Properties_Types


Return -1
END

pNet_LoadSettings Stored

CREATE PROCEDURE [dbo].[pNet_LoadSettings]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadSettings
--#CREATION
-- 26/10/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Settings definition from Settings Table
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 26/10/2017 - Rubén Pardo - Stored created
-- 18/12/2017 - JJR - Added field [Active] to table. Read only active settings
----------------------------------------------------------------------------------
BEGIN

SELECT *
FROM Settings
WHERE
Active = 1

RETURN -1
END

pNet_LoadSkins Stored

CREATE PROCEDURE [dbo].[pNet_LoadSkins]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadSkins
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Skins definition from Skins Table and Skins_Css Table.
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN

select * from Skins
select * from Skins_Css where [enabled]=1 order by [Order],[CssId]
select * from Skins_Variables

Return -1
END

pNet_LoadTabDefinition Stored

Create PROCEDURE [dbo].[pNet_LoadTabDefinition](
@TabName T_ModuleName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadTabDefinition
--#CREATION
-- 14/06/2017- Rubén Pardo
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Pages_Modules from specified tab.
--#PARAMETERS
-- @TabName Tab Id
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN

--Modules
select pm.PageName,pm.ModuleName,pm.LayoutPositionId,pm.RelationWhere,pm.[Order],pm.SQLEnabled,pm.SQLEnabledDescrip,
m.params,m.CollapsibleButton,m.FullscreenButton,m.RefreshButton, m.JSAfterLoad,m.ShowWhenNew,
mc.TemplateHTML as ContainerTemplate,mc.CSSClass as ContainerClass,
mt.webcomponent as WebComponent,
case when pm.Title is null then m.title else pm.Title end as Title,case when pm.HeaderClass is null then m.HeaderClass else pm.HeaderClass end as HeaderClass,case when pm.ModuleClass is null then m.ModuleClass else pm.ModuleClass end as ModuleClass,
case when pmi.IconName is null then Icons.IconName else pm.IconName end as IconName,case when pmi.IconName is null then Icons.CSSClass else pmi.CSSClass end as IconCssClass,case when pmi.IconName is null then Icons.ImagePath else pmi.ImagePath end as IconImagePath,
tabs.TabModuleName as TabName,tabs.[Order] as TabOrder, m.ObjectName, m.PresetName
from Pages_Modules pm
inner join modules m on pm.ModuleName=m.ModuleName
inner join Modules_Containers mc on m.ContainerId=mc.ContainerId
inner join Modules_Types mt on m.TypeId=mt.TypeId
inner join Icons on m.IconName=icons.IconName
inner Join vPages_Modules_Tabs tabs on pm.ModuleName=tabs.ModuleName and tabs.PageName=pm.PageName
left join Icons pmi on pm.IconName=pmi.IconName
where tabs.TabModuleName = @TabName
order by pm.[order]

Return -1
END

pNet_LoadTemplatesSecurity Stored

CREATE PROCEDURE [dbo].[pNet_LoadTemplatesSecurity](
@UserId T_UserId,
@RoleId T_RoleId
)
AS

----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadTemplatesSecurity
--#CREATION
-- 01/12/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Template Security definition from Security_Objects_Templates_Roles and
-- Security__Templates_Users Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
-- @RoleId: Role Identifier.
--#OBSERVATIONS
--
--#CHANGES

----------------------------------------------------------------------------------
BEGIN
if(select count(*) from aspnetroles where (IsDesigner=1 or IsAdmin=1) and id=@RoleId)=0 BEGIN

if @RoleId='notRegistered' BEGIN
--User is not registered


-- Load Restriction for all report overwrite with allusers security and overwrite with NotRegisterd security
select Rest.* from vNet_AllRestrictedTemplatesSecurity Rest
left join (select * from Security_Objects_Templates_Roles where RoleId='allUsers') AllU on allU.TemplateId=Rest.TemplateId
left join (select * from Security_Objects_Templates_Roles where RoleId='notRegistered') NotReg on Rest.TemplateId=NotReg.TemplateId
where NotReg.TemplateId is null and AllU.TemplateId is null
UNION

-- Load allusers security and overwrite with NotRegisterd security
select AllU.* from (select * from Security_Objects_Templates_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Templates_Roles where RoleId='notRegistered') NotReg on allU.TemplateId=NotReg.TemplateId
where NotReg.TemplateId is null
UNION

-- Load NotRegisterd security
select * from Security_Objects_Templates_Roles where RoleId='notRegistered'


-- Ther is no security for individual nonregistered users



end else begin
--User is registered and not admin


-- Load allusers security and overwrite with Registerd security and overwite with Actual Role Group
select allU.* from (select * from Security_Objects_Templates_Roles where RoleId='allUsers') AllU
left join (select * from Security_Objects_Templates_Roles where RoleId='Registered') NotReg on allU.TemplateId=NotReg.TemplateId
left join (select * from Security_Objects_Templates_Roles where RoleId=@RoleId) mySec on allU.TemplateId=mySec.TemplateId
where NotReg.TemplateId is null and mySec.TemplateId is null
UNION

-- Load Registerd security and overwite with Actual Role Group
select NotReg.* from (select * from Security_Objects_Templates_Roles where RoleId='Registered') NotReg
left join (select * from Security_Objects_Templates_Roles where RoleId=@roleid) mySec on NotReg.TemplateId=mySec.TemplateId
where mySec.TemplateId is null
UNION

-- Load Actual Role Group Security
select * from Security_Objects_Templates_Roles where RoleId=@roleid


-- Load Individual security
select * from Security_Objects_Templates_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Templates_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Templates_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by TemplateId


end

END ELSE BEGIN
--User is administrator or designer.
select * from Security_Objects_Templates_Roles where RoleId =@RoleId

--Load individual security
select * from Security_Objects_Templates_Users where UserId =@UserId

-- Load Faculty security
select * from Security_Objects_Templates_Faculties Inner join AspNetUsers_Faculties a on Security_Objects_Templates_Faculties.FacultyId=a.FacultyId where UserId =@UserId order by TemplateId


END


Return -1

END

pNet_LoadTests Stored

CREATE PROCEDURE [dbo].[pNet_LoadTests]
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadTests
--#CREATION
-- 09/11/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Loads available test.
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
-- 09/11/2018-David Miralpeix
----------------------------------------------------------------------------------
BEGIN

select * from Tests

Return -1
END

pNet_LoadTimelineSetting Stored

CREATE PROCEDURE [dbo].[pNet_LoadTimelineSetting](
@TimelineSettingName nvarchar(100)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadTimelineSetting
--#CREATION
-- 11/03/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load timeline setting
--#PARAMETERS
-- TimelineSettingName - Setting name to load configuration
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

SELECT [TimelineSettingName]
,[TimelineSettingDescrip]
,[ObjectName]
,[Advanced]
,[Editable]
,[EventPageTypeId]
,[WithGroups]
,[ShowItemsWithoutGroup]
,[TitleItemsWithoutGroup]
,[LayoutName]
,[DefaultRangeName]
,[ShowControls]
,[OnInsertOpenNewWithDefaults]
,[PropertyDescrip]
,[PropertyStartDate]
,[PropertyEndDate]
,[PropertyGroup]
,[GroupViewName]
,[GroupIdField]
,[GroupDescripField]
,[GroupClassNameField]
,[GroupStyleField]
,[GroupContentTemplate]
,[ItemViewName]
,[ItemDescripField]
,[ItemStartDateField]
,[ItemEndDateField]
,[ItemGroupField]
,[ItemEditableField]
,[ItemClassNameField]
,[ItemStyleField]
,[ItemTypeField]
,[ItemContentTemplate]
,[ItemVisibleFrameTemplate]
,[OnMovingFunction]
,[OnDropObjectOnItemFunction]
,[OnDeleteFunction]
,[CustomOptions]
,[DefaultTime]
,[OriginId]
FROM [dbo].[Timelines_Settings]
WHERE [TimelineSettingName] = @TimelineSettingName

RETURN -1
END

pNet_LoadToolBar Stored


CREATE PROCEDURE [dbo].[pNet_LoadToolBar](@ToolbarName T_ToolbarName)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_LoadToolBar]
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Toolbar Buttons given a TooBar Id
-- Loads from table ToolBars_Buttons Table
--#PARAMETERS
-- @ToolbarName: The Toolbar Name
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 04/08/2020- Sergio Vera
----------------------------------------------------------------------------------
BEGIN
select T.* ,i.CSSClass as IconClass ,i.ImagePath, IIF(RP.numParameters IS NULL,0,1) as ReportHasParams from
Toolbars_Buttons T left join Icons i on T.IconName =i.IconName
LEFT JOIN (
SELECT count(*) numParameters,r.reportname
FROM
Reports_Params rp
INNER JOIN Reports r on rp.ReportName=r.ReportName
GROUP BY
r.ReportName
) RP ON T.ReportName=RP.ReportName
where t.toolbarName=@ToolbarName and [disabled]=0
order by T.[Order]

Return -1
END

pNet_LoadUserInfo Stored



CREATE PROCEDURE [dbo].[pNet_LoadUserInfo]( @UserName nvarchar(50))
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadUserInfo
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading User information into Framework
--#PARAMETERS
-- @UserName: User Name to use as filter.
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
-- 06/08/2018- Rubén Pardo - Add webapi security
----------------------------------------------------------------------------------
BEGIN
SELECT u.Id as UserId,UserName, IsAdmin,IsDesigner, Reference, Subreference ,r.id as RoleId, r.Name as RoleName,u.ProfileName ,u.CultureId,u.Email,
isnull(u.Name+' '+isnull(SurName,' '),username) as FullName, ISNULL(ISNULL(WU.IsAuthorized,WR.IsAuthorized),0) as WebAPI_IsAuthorized, isnull(u.MailAccountId,p.MailAccountId) as MailAccountId
FROM AspNetUsers u inner join aspnetRoles r on u.RoleId= r.id
LEFT JOIN WebAPI_Users WU ON u.id=WU.UserId
LEFT JOIN WebAPI_Roles WR ON r.id=WR.RoleId
LEFT JOIN AspNetProfiles P On P.ProfileName=u.ProfileName
where UserName=@UserName

Return -1
END

pNet_LoadUserSearchCriterias Stored

CREATE PROCEDURE [dbo].[pNet_LoadUserSearchCriterias](
@UserId T_UserId,
@ObjectName T_ObjectName,
@SearchId VARCHAR(50)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadUserSearchCriterias
--#CREATION
-- 07/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Users generic search criterias based on
-- Objects_Search_Users_Settings Tables into Framework
-- If SearchId is specified, it will return it for that specified search id
-- If ObjectName is blank it will return it for all selected objects
-- If ObjectName is not blank it will return for that object name
--#PARAMETERS
-- @UserId: User Identifier.
-- @ObjectName:Optional Object name.
-- @SearchId: Optional SearchId
--#OBSERVATIONS
--
--#CHANGES
-- 07/12/2016- David Miralpeix
-- 31/07/2017- David Miralpeix
-- 03/08/2017- JJR - Added SearchId parameter
----------------------------------------------------------------------------------
BEGIN

IF ISNULL(@SearchId,'')<>'' BEGIN

SELECT os.SearchId, os.ObjectName,os.Name, o.Descrip, i.CSSClass, os.SQLSentence, os.Generic
FROM
Objects_Search os
INNER JOIN objects o on o.Objectname=os.ObjectName
INNER JOIN icons i ON o.IconName=i.IconName
WHERE
os.searchid=@SearchId

SELECT
OSP.SearchId, os.ObjectName as SearchObject,osp.Objectname, osp.PropertyName, osp.ObjectPath
FROM
Objects_Search os
INNER JOIN Objects_Search_Properties osp ON os.SearchId=osp.SearchId
WHERE
os.searchid=@SearchId
ORDER BY osp.[order]



END ELSE BEGIN

if len(@ObjectName)>0
BEGIN
SELECT os.SearchId, os.ObjectName,os.Name, o.Descrip, i.CSSClass, os.SQLSentence , os.Generic
FROM Objects_Search_Users_Settings us
INNER JOIN Objects_Search os ON us.SearchId=os.SearchId
INNER JOIN objects o on o.Objectname=os.ObjectName
INNER JOIN icons i ON o.IconName=i.IconName
WHERE us.UserId=@UserId and os.ObjectName=@ObjectName ORDER BY us.[order]

SELECT OSP.SearchId, os.ObjectName as SearchObject,osp.Objectname, osp.PropertyName, osp.ObjectPath
FROM Objects_Search_Users_Settings us
INNER JOIN Objects_Search os ON us.SearchId=os.SearchId
INNER JOIN Objects_Search_Properties osp ON us.SearchId=osp.SearchId
WHERE us.UserId=@UserId and os.ObjectName=@ObjectName ORDER BY us.[order]

END

ELSE

BEGIN

SELECT os.SearchId, os.ObjectName,os.Name, o.Descrip, i.CSSClass, os.SQLSentence, os.Generic
FROM Objects_Search AS os
LEFT JOIN Objects_Search_Users_Settings AS us ON os.SearchId = us.SearchId AND us.UserId = @UserId
INNER JOIN objects o on o.Objectname=OS.ObjectName
INNER JOIN icons i ON o.IconName=i.IconName
WHERE Generic = 1 AND ISNULL(us.[Enabled],1) = 1 ORDER BY us.[order]


SELECT osp.SearchId, os.ObjectName as SearchObject,osp.Objectname, osp.PropertyName, osp.ObjectPath
FROM Objects_Search AS os
LEFT JOIN Objects_Search_Users_Settings AS us ON os.SearchId = us.SearchId AND us.UserId = @UserId
INNER JOIN Objects_Search_Properties osp ON os.SearchId=osp.SearchId
WHERE Generic = 1 AND ISNULL(us.[Enabled],1) = 1 ORDER BY us.[order]

END



END


Return -1
END

pNet_LoadUserSearchCriteriasSettings Stored


CREATE PROCEDURE [dbo].[pNet_LoadUserSearchCriteriasSettings](
@UserId T_UserId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadUserSearchCriteriasSettings
--#CREATION
-- 07/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for Loading Users generic search criterias options based on
-- Objects_Search_Users_Settings Tables into Framework
--#PARAMETERS
-- @UserId: User Identifier.
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/12/2016- David Miralpeix
-- 08/08/2017- David Miralpeix added configDB
-- 09/11/2018- David Miralpeix Set default values to true for all users
----------------------------------------------------------------------------------
BEGIN

SELECT os.SearchId, os.ObjectName,os.Name, o.Descrip, i.CSSClass, os.SQLSentence, isnull(us.[Enabled],1)as [Enabled] , isnull(us.[order] ,100) as [Order], o.ConfigDB
FROM Objects_Search os
LEFT JOIN Objects_Search_Users_Settings us on os.SearchId=us.SearchId and us.UserId=@UserId
LEFT JOIN objects o on o.Objectname=os.ObjectName
LEFT JOIN icons i on o.IconName=i.IconName
WHERE generic=1 and (os.UserId=@UserId or os.UserId is null) order by us.[order],os.[Order]

Return -1
END

pNet_LoadUserSearchValues Stored

CREATE PROCEDURE [dbo].[pNet_LoadUserSearchValues](
@CollectionName as t_ObjectName,
@UserId as T_UserId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LoadUserSearchValues
--#CREATION
-- 17/01/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Load user saved values for a filter.
--#PARAMETERS
-- @CollectionName the collection Name
-- @UserId user id for personal filters
--#OBSERVATIONS
--
--#CHANGES
-- 30/04/18-dmiralpeix- created
-- 28/08/18-Alberto Criado Andrés- Add Generic
----------------------------------------------------------------------------------
BEGIN

--Filters

select Objects_Search_users_Values.* from Objects_Search_users_Values
INNER JOIN Objects_Search os ON Objects_Search_users_Values.SearchId=os.SearchId
where os.ObjectName=@CollectionName And (Objects_Search_users_Values.UserId=@UserId OR Objects_Search_users_Values.Generic = 1)
order by Objects_Search_users_Values.Generic desc, Objects_Search_users_Values.[Name]

Return -1
END

pNet_LogError Stored

CREATE procedure [dbo].[pNet_LogError](
@Id int output,
@UserId t_UserId,
@ErrorLevel int,
@ErrorMessage nvarchar(max),
@ErrorStack nvarchar(max),
@ErrorCode nvarchar(50),
@ObjectName t_objectName,
@ObjectKey nvarchar(255),
@ActionType int,
@ProcessName T_processName,
@ProcessParams nvarchar(max),
@ConnStringId T_ConnStringId,
@Username nvarchar(128),
@Browser nvarchar(50),
@BrowserVersion nvarchar(50),
@MoreInfo nvarchar(max),
@ErrorSeverity INT,
@IP nvarchar(50),
@CausesLockout bit output
) as
----------------------------------------------------------------------------------
--#NAME
-- pNet_LogError
--#CREATION
-- 07/06/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Logs Errors to table from different parts of application
--#PARAMETERS
-- @Id int output,
-- @UserId t_UserId,
-- @ErrorLevel int,
-- @ErrorMessage nvarchar(max),
-- @ErrorStack nvarchar(max),
-- @ErrorCode nvarchar(50),
-- @ObjectName t_objectName,
-- @ObjectKey nvarchar(255),
-- @ActionType int,
-- @ProcessName T_processName,
-- @ProcessParams nvarchar(max),
-- @ConnectionStringId T_ConnStringId,
-- @Username nvarchar(128),
-- @Browser nvarchar(250),
-- @DatabaseName nvarchar(250)
-- @MoreInfo nvarchar(max)
-- @ErrorSeverity INT
-- @IP nvarchar(50),
-- @CausesLockout bit output
--
--#OBSERVATIONS
--
--#CHANGES
-- 07/06/2018- David Miralpeix
-- 25/10/2019- Rubén Pardo -- Auto block malicious IP
----------------------------------------------------------------------------------
BEGIN
declare @Version nvarchar(50)
declare @currentTimeStamp datetime = GETDATE()
set @CausesLockout=0

Select top(1) @Version=isnull(VersionNumber,'No version') from Versions
INSERT INTO [Error_Log]
([UserId]
,[ErrorLevel]
,[ErrorMessage]
,[ErrorStack]
,[ErrorCode]
,[ErrorSeverity]
,[ObjectName]
,[ObjectKey]
,[ActionType]
,[ProcessName]
,[ProcessParams]
,[ConnectionStringId]
,[UserName]
,[Browser]
,[BrowserVersion]
,[TimeStamp]
,[Version],MoreInfo,[IP])
VALUES
(@UserId,@ErrorLevel,@ErrorMessage,@ErrorStack,@ErrorCode,@ErrorSeverity,@ObjectName,@ObjectKey
,@ActionType,@ProcessName,@ProcessParams,@ConnStringId,@UserName
,@Browser ,@BrowserVersion, @currentTimeStamp,@Version,@MoreInfo,@IP)

IF @@ROWCOUNT=0 BEGIN
PRINT 'ERROR IN pNet_LogError'
RETURN 0
END

SELECT @Id=Max(id) FROM [Error_Log]

if @IP<>'::1' BEGIN

--Más de x intentos black list en 1 minuto o más de y intentos de grey list en un minuto.
declare @SentinelMaxBlackRequests int
declare @SentinelMaxGreyRequests int

declare @SentinelCurrentBlackRequests int
declare @SentinelCurrentGreyRequests int

set @SentinelMaxBlackRequests=(select SettingValue from Settings where SettingName='SentinelMaxBlackRequests')
set @SentinelMaxGreyRequests=(select SettingValue from Settings where SettingName='SentinelMaxGreyRequests')


select @SentinelCurrentBlackRequests=count(*) from Error_Log
where ip=@IP
and errorlevel=7
and errorcode=666
and ErrorSeverity=2 --1 Grey list 2 BlackList
and [TimeStamp]>=dateadd(SECOND,-30,@currentTimeStamp)
and [TimeStamp]<=dateadd(SECOND,30,@currentTimeStamp)

select @SentinelCurrentGreyRequests=count(*) from Error_Log
where ip=@IP
and errorlevel=7
and errorcode=666
and ErrorSeverity=1 --1 Grey list 2 BlackList
and [TimeStamp]>=dateadd(SECOND,-30,@currentTimeStamp)
and [TimeStamp]<=dateadd(SECOND,30,@currentTimeStamp)


if isnull(@SentinelMaxBlackRequests,0)>0 and @SentinelCurrentBlackRequests > @SentinelMaxBlackRequests BEGIN
Insert into Security_IP_Lockout(IP,LockoutDate,Reason) values (@IP,getdate(),'Too much malicious request

pNet_LogError Stored

per minute catched by black list')
set @CausesLockout=1
END ELSE IF isnull(@SentinelMaxGreyRequests,0)>0 and @SentinelCurrentGreyRequests > @SentinelMaxGreyRequests BEGIN
Insert into Security_IP_Lockout(IP,LockoutDate,Reason) values (@IP,getdate(),'Too much malicious request per minute catched by grey list')
set @CausesLockout=1
END

END



RETURN -1
END

pNet_LogJobs Stored



CREATE PROCEDURE [dbo].[pNet_LogJobs]
(
@ExecutionId NVARCHAR(50),
@JobName nvarchar(50),
@JobStart DATETIME,
@JobEnd DATETIME,
@HasError BIT,
@Descrip nvarchar(max)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_LogJobs
--#CREATION
-- 22/12/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Insert or update scheduled job log
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

IF (select count(ExecutionId) as Log from Jobs_Log where ExecutionId=@ExecutionId) > 0 BEGIN
UPDATE Jobs_Log SET JobEnd=@JobEnd, HasError=@HasError,Descrip=@Descrip WHERE ExecutionId=@ExecutionId
END ELSE BEGIN
INSERT INTO Jobs_Log (ExecutionId,JobName,JobStart,JobEnd,HasError,Descrip)
VALUES (@ExecutionId,@JobName,@JobStart,@JobEnd,@HasError,@Descrip)
END


RETURN -1
END

pNet_LogObjectAction Stored


CREATE procedure [dbo].[pNet_LogObjectAction](
@UserId t_UserId,
@TypeId int,
@Message nvarchar(1000),
@ObjectName t_objectName,
@ObjectKey nvarchar(255),
@Username nvarchar(128),
@ProcessName nvarchar(500),
@TimeStamp datetime,
@EndTimeStamp datetime,
@LogId int output

) as
----------------------------------------------------------------------------------
--#NAME
-- pNet_LogObjectAction
--#CREATION
-- 07/01/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Logs users insert-update-delete-view actions if audit enabled on object
-- Also logs Process Execution
--#PARAMETERS
-- @UserId User id,
-- @TypeId Type of action,
-- @Message mesage string,
-- @ObjectName object name,
-- @ObjectKey Object key,
-- @Username UserName,
-- @LogId return value
-- @ProcessName
--#OBSERVATIONS
--
--#CHANGES
-- 07/01/2016- David Miralpeix
----------------------------------------------------------------------------------
BEGIN
INSERT INTO [dbo].[ActionsLog]
([UserId]
,[TypeId]
,[ActionMessage]
,[ObjectName]
,[ObjectKey]
,[TimeStamp]
,[UserName]
,[ProcessName]
,[EndTimeStamp])
VALUES
(@UserId,convert(int,@TypeId ),@Message,@ObjectName,@ObjectKey,@TimeStamp,@Username,@ProcessName,@EndTimeStamp)

IF @@ROWCOUNT=0 BEGIN
PRINT 'ERROR IN pNet_LogdObjectAction'
RETURN 0
END
SELECT @LogId=Max(id) FROM [ActionsLog]

RETURN -1
END

pNet_MailSendUpdateStatusErr Stored

CREATE PROCEDURE [dbo].[pNet_MailSendUpdateStatusErr]
@Id NVARCHAR(100),
@ErrorMsg nvarchar(max)

AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_MailSendUpdateStatuseRR
--#CREATION
-- 12/04/2018
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Updates outbox mails with ERROR MESAGES
--#PARAMETERS
-- @Id: Mail Id
-- @ErrorMsg: Error message
--#OBSERVATIONS
--
--#CHANGES
-- 12/04/201-DML-First version
----------------------------------------------------------------------------------
BEGIN TRY

Update mails_Outbox set Status=-1 , SentDate=getdate(),ErrorMsg= @ErrorMsg where ID=@Id
RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_MailSendUpdateStatusOK Stored

CREATE PROCEDURE [dbo].[pNet_MailSendUpdateStatusOK]
@OKList NVARCHAR(max)

AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_MailSendUpdateStatusOK
--#CREATION
-- 12/04/2018
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Updates outbox mails with
--#PARAMETERS
-- @OKList: list of mail Id's separated with comas

--#OBSERVATIONS
--
--#CHANGES
-- 12/04/201-DML-First version
----------------------------------------------------------------------------------
BEGIN TRY

Update m set Status=2 , SentDate=getdate()
from mails_Outbox M
INNER JOIN string_split (@OKList,',' ) k on m.ID=k.value


RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_NavigationNodeClone Stored

CREATE PROCEDURE [dbo].[pNet_NavigationNodeClone](
@NodeId NVARCHAR(MAX),
@NewTitle NVARCHAR(255),
@NewParentNodeId NVARCHAR(MAX)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_NavigationNodeClone
--#CREATION
-- 05/05/2021
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Clones existing navigation node and childs nodes
--#PARAMETERS
-- @NodeId uniqueidentifier,
-- @NewTitle nvarchar(255),
-- @NewParentNodeId uniqueidentifier
--#OBSERVATIONS
--
--#CHANGES
-- 04/05/2021- Sergio Vera
----------------------------------------------------------------------------------

BEGIN TRY

BEGIN TRAN

DECLARE @NewNodeId TABLE (NewNodeId uniqueidentifier)

--Insert principal node
INSERT INTO Navigation_Nodes([ParentNodeId], [Order], [Title], [IconName], [Descrip], [TypeId], [Params], [Url], [TargetId], [ProcessName], [PageTypeId], [PageName], [ReportName], [HelpId], [ReportWhere], [ObjectName], [ObjectWhere], [Defaults], [SQLSentence], [SQLConStringId], [WebComponent], [TableName], [BadgeClass], [BadgeSQL], [BadgeConStringId], [BadgeRefresh], [Enabled], [cssClass])
OUTPUT inserted.NodeId into @NewNodeId
SELECT @NewParentNodeId, [Order], iif(@NewTitle is not null,@NewTitle,[Descrip]), [IconName], iif(@NewTitle is not null,@NewTitle,[Descrip]), [TypeId], [Params], [Url], [TargetId], [ProcessName], [PageTypeId], [PageName], [ReportName], [HelpId], [ReportWhere], [ObjectName], [ObjectWhere], [Defaults], [SQLSentence], [SQLConStringId], [WebComponent], [TableName], [BadgeClass], [BadgeSQL], [BadgeConStringId], [BadgeRefresh], [Enabled], [cssClass]
FROM Navigation_Nodes Where NodeId = @NodeId

--Insert child nodes
DECLARE @Nodes uniqueidentifier

DECLARE Nodes_Cur CURSOR FOR
Select Nodeid from Navigation_Nodes Where ParentNodeId = @NodeId and OriginId != 0

OPEN Nodes_Cur
FETCH NEXT FROM Nodes_Cur INTO @Nodes

WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE @NewNode uniqueidentifier
SELECT @NewNode = NewNodeId From @NewNodeId
exec pNet_NavigationNodeClone @Nodes,null,@NewNode

FETCH NEXT FROM Nodes_Cur INTO @Nodes
END
CLOSE Nodes_Cur
DEALLOCATE Nodes_Cur
COMMIT
RETURN 1

END TRY

BEGIN CATCH

Rollback
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_NoticeIsRead Stored

CREATE PROCEDURE [dbo].pNet_NoticeIsRead
@NoticeId NVARCHAR(50),
@UserId T_userId
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_NoticeIsRead
--#CREATION
-- 12/12/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Changes notice to red for givennotice and User
-- If NoticeId is null then changes all notices toread for that user
--#PARAMETERS
-- @NoticeId: Notice to change read flag
-- @UserId: Sets read for that user if it is a notice for all Users
--#OBSERVATIONS
--
--#CHANGES
---------------------------------------------------------------------------------
BEGIN TRY

IF @NoticeId is null
BEGIN

Update U set IsRead=1
from Notices N inner join Notices_Users U on N.NoticeId=U.NoticeId
where
--u.IsSent=1 and U.UserId=@UserId and IsRead=0
U.UserId=@UserId and IsRead=0


--insert into Notices_Users(NoticeId,UserId,IsSent,IsRead)
--select N.NoticeId,@UserId as UserId,1 as IsSent,1 as IsRead from Notices N
insert into Notices_Users(NoticeId,UserId,IsRead)
SELECT N.NoticeId,@UserId as UserId,1 as IsRead from Notices N
left join Notices_Users U on N.NoticeId=U.NoticeId and u.UserId=@UserId
where
--n.AllUsers =1 and n.AllUsersIsSent=1 and U.NoticeId is null
n.AllUsers =1 and U.NoticeId is null
END
ELSE
BEGIN

Update U set IsRead=1
from Notices N inner join Notices_Users U on N.NoticeId=U.NoticeId
where N.NoticeId=@NoticeId and U.UserId=@UserId and IsRead=0

--insert into Notices_Users(NoticeId,UserId,IsSent,IsRead)
--select N.NoticeId,@UserId as UserId,1 as IsSent,1 as IsRead from Notices N
INSERT INTO Notices_Users(NoticeId,UserId,IsRead)
SELECT N.NoticeId,@UserId AS UserId, 1 as IsRead from Notices N
left join Notices_Users U on N.NoticeId=U.NoticeId and u.UserId=@UserId
where N.NoticeId=@NoticeId and U.NoticeId is null

END

RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_OfflineCloneObject Stored

CREATE PROCEDURE [dbo].[pNet_OfflineCloneObject](
@AppName AS NVARCHAR(100),
@ObjectName T_ObjectName,
@Properties AS NVARCHAR(MAX),
@NewObjectName T_ObjectName,
@NewCollectionName T_ObjectName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_OfflineCloneObject
--#CREATION
-- 05/11/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Clones existing object to offline object
--#PARAMETERS
-- @ObjectName T_ObjectName,
-- @Properties AS NVARCHAR(MAX),
-- @NewObjectName T_ObjectName,
-- @NewCollectionName T_ObjectName
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY
BEGIN TRAN
/*New names*/
SET @NewObjectName = 'Offline_' + @NewObjectName
SET @NewCollectionName = 'Offline_' + @NewCollectionName

/*Clone Object*/
INSERT INTO [dbo].[Objects]
([ObjectName]
,[Iscollection]
,[ObjectChildName]
,[TableName]
,[WhereSentence]
,[ConfigDB]
,[OrderBy]
,[Descrip]
,[IconName]
,[UniqueIdentifierField]
,[ShowDefaultMenu]
,[DefaultPageSize]
,[ParsedDescrip]
,[Auditable]
,[Active]
,[CanInsert]
,[CanUpdate]
,[CanDelete]
,[CanView]
,[CanPrint]
,[InsertType]
,[UpdateType]
,[DeleteType]
,[InsertProcessName]
,[UpdateProcessName]
,[DeleteProcessName]
,[LoadProcessName]
,[HelpId]
,[OverrideObjectName]
,[OverrideObjectWhere]
,[NavigateNodeId]
,[Clonable]
,[ViewKeys]
,[IgnoreDBRequired]
,[ConnStringID]
,[TransactionOn]
,[InsertFlowText]
,[UpdateFlowText]
,[DeleteFlowText]
,[Offline]
,[BeforeUpdate]
,[BeforeInsert]
,[BeforeDelete]
,[AfterUpdate]
,[AfterInsert]
,[AfterDelete]
,[Reserved]
/*,[OriginId]*/)
SELECT @NewObjectName --[ObjectName]
,[Iscollection]
,[ObjectChildName]
,[TableName]
,[WhereSentence]
,[ConfigDB]
,[OrderBy]
,[Descrip]
,[IconName]
,[UniqueIdentifierField]
,0 --[ShowDefaultMenu]
,[DefaultPageSize]
,[ParsedDescrip]
,[Auditable]
,[Active]
,[CanInsert]
,[CanUpdate]
,[CanDelete]
,[CanView]
,[CanPrint]
,[InsertType]
,[UpdateType]
,[DeleteType]
,[InsertProcessName]
,[UpdateProcessName]
,[DeleteProcessName]
,[LoadProcessName]
,[HelpId]
,[OverrideObjectName]
,[OverrideObjectWhere]
,[NavigateNodeId]
,[Clonable]
,[ViewKeys]
,[IgnoreDBRequired]
,[ConnStringID]
,[TransactionOn]
,[InsertFlowText]
,[UpdateFlowText]
,[DeleteFlowText]
,1 --[Offline]
,[BeforeUpdate]
,[BeforeInsert]
,[BeforeDelete]
,[AfterUpdate]
,[AfterInsert]
,[AfterDelete]
,[Reserved]
--,[OriginId]
FROM [dbo].[Objects]
WHERE [ObjectName] = @ObjectName

/*Clone Collection*/
INSERT INTO [dbo].[Objects]
([ObjectName]
,[Iscollection]
,[ObjectChildName]
,[TableName]
,[WhereSentence]
,[ConfigDB]
,[OrderBy]
,[Descrip]
,[IconName]
,[UniqueIdentifierField]
,[ShowDefaultMenu]
,[DefaultPageSize]
,[ParsedDescrip]
,[Auditable]
,[Active]
,[CanInsert]
,[CanUpdate]
,[CanDelete]
,[CanView]
,[CanPrint]
,[InsertType]
,[UpdateType]
,[DeleteType]
,[InsertProcessName]

pNet_OfflineCloneObject Stored

,[UpdateProcessName]
,[DeleteProcessName]
,[LoadProcessName]
,[HelpId]
,[OverrideObjectName]
,[OverrideObjectWhere]
,[NavigateNodeId]
,[Clonable]
,[ViewKeys]
,[IgnoreDBRequired]
,[ConnStringID]
,[TransactionOn]
,[InsertFlowText]
,[UpdateFlowText]
,[DeleteFlowText]
,[Offline]
,[BeforeUpdate]
,[BeforeInsert]
,[BeforeDelete]
,[AfterUpdate]
,[AfterInsert]
,[AfterDelete]
,[Reserved]
/*,[OriginId]*/)
SELECT @NewCollectionName --[ObjectName]
,[Iscollection]
,@NewObjectName --[ObjectChildName]
,[TableName]
,[WhereSentence]
,[ConfigDB]
,[OrderBy]
,[Descrip]
,[IconName]
,[UniqueIdentifierField]
,0 --[ShowDefaultMenu]
,[DefaultPageSize]
,[ParsedDescrip]
,[Auditable]
,[Active]
,[CanInsert]
,[CanUpdate]
,[CanDelete]
,[CanView]
,[CanPrint]
,[InsertType]
,[UpdateType]
,[DeleteType]
,[InsertProcessName]
,[UpdateProcessName]
,[DeleteProcessName]
,[LoadProcessName]
,[HelpId]
,[OverrideObjectName]
,[OverrideObjectWhere]
,[NavigateNodeId]
,[Clonable]
,[ViewKeys]
,[IgnoreDBRequired]
,[ConnStringID]
,[TransactionOn]
,[InsertFlowText]
,[UpdateFlowText]
,[DeleteFlowText]
,1 --[Offline]
,[BeforeUpdate]
,[BeforeInsert]
,[BeforeDelete]
,[AfterUpdate]
,[AfterInsert]
,[AfterDelete]
,[Reserved]
--,[OriginId]
FROM [dbo].[Objects]
WHERE [ObjectChildName] = @ObjectName

/*Clone custom properties*/

Insert into Objects_Properties_Templates (CustomPropName, Descrip, TypeId, Mask, SQlSentence, SQLEditSentence, SQLFilter, SQLValueField, SQLDisplayField, SQLObjectName, SQLOfflineSentence, SQLOfflineOrderBy, SQLViewName, WhereSentence, Label, Width, Height, DefaultValue, PersistDefaultValue, IgnoreDBDefaultValue, DetachedFromDB, SearchFunction, SearchCollection, SearchWhere, SearchReturnFields, SecurityObject, AllowNew, AllowNewFunction, AllowNewReturnFields, AllowNewDefaults , ObjNameLink, ObjWhereLink, TargetIdLink, Style, CSSClass, LabelStyle, LabelCSSClass, DecimalPlaces, RootPath, FormatString, DirectTemplate, Tag, HelpId, ConnStringId, IsRequired, IsRequiredMessage, minValue, minValueMessage, maxValue, maxValueMessage, RegExp, RegExpText, SQLValidator, ValidatorMessage, OnChangeJsFunction, OnChangeProcessName, PlaceHolder, Separator, PageSize, ImageCompressionType, ImageMaxWidth, ImageMaxHeight, Offline, ExtensionId)
Select distinct
OPT.CustomPropName+'_Offline' as CustomPropName,
OPT.Descrip,
OPT.TypeId,
OPT.Mask,
OPT.SQlSentence,
OPT.SQLEditSentence,
OPT.SQLFilter,
OPT.SQLValueField,
OPT.SQLDisplayField,
OPT.SQLObjectName,
OPT.SQLViewName,
OPT.[SQLOfflineSentence],
OPT.[SQLOfflineOrderBy],
OPT.WhereSentence,
OPT.Label,
OPT.Width,
OPT.Height,
OPT.DefaultValue,
OPT.PersistDefaultValue,
OPT.IgnoreDBDefaultValue,
OPT.DetachedFromDB,
OPT.SearchFunction,
OPT.SearchCollection,
OPT.SearchWhere,
OPT.SearchReturnFields,
OPT.SecurityObject,
OPT.AllowNew,
OPT.AllowNewFunction,
OPT.AllowNewReturnFields,
OPT.AllowNewDefaults,
OPT.ObjNameLink,
OPT.ObjWhereLink,
OPT.TargetIdLink,
OPT.Style,
OPT.CSSClass,
OPT.LabelStyle,
OPT.LabelCSSClass,
OPT.DecimalPlaces,
OPT.RootPath,
OPT.FormatString,
OPT.DirectTemplate,
OPT.Tag,
OPT.HelpId,
OPT.ConnStringId,
OPT.IsRequired,
OPT.IsRequiredMessage,
OPT.minValue,
OPT.minValueMessage,
OPT.maxValue,
OPT.maxValueMessage,
OPT.RegExp,
OPT.RegExpText,
OPT.SQLValidator,
OPT.ValidatorMessage,
OPT.OnChangeJsFunction,
OPT.OnChangeProcessName,
OPT.PlaceHolder,
OPT.Separator,
OPT.PageSize,

pNet_OfflineCloneObject Stored


OPT.ImageCompressionType,
OPT.ImageMaxWidth,
OPT.ImageMaxHeight,
1, --OPT.Offline
OPT.ExtensionId
from Objects_Properties OP
inner join Objects_Properties_Templates OPT ON OP.CustomPropName=OPT.CustomPropName
left join Objects_Properties_Templates OPT_NEW ON OP.CustomPropName+'_Offline'=OPT_NEW.CustomPropName
WHERE OP.[ObjectName] = @ObjectName AND OP.[PropertyName] IN (SELECT value FROM STRING_SPLIT(@Properties, '|')) AND OP.TypeId='custom' and OPT_NEW.CustomPropName is null

/*Clone Properties*/
INSERT INTO [dbo].[Objects_Properties]
([ObjectName]
,[PropertyName]
,[Label]
,[PositionY]
,[PositionX]
,[Width]
,[Height]
,[Hide]
,[ClientReadOnly]
,[FormDisplay]
,[TypeId]
,[Locked]
,[CustomPropName]
,[Mask]
,[SQlSentence]
,[SQLEditSentence]
,[SQLFilter]
,[SQLValueField]
,[SQLDisplayField]
,[SQLObjectName]
,[SQLViewName]
,[SQLOfflineSentence]
,[SQLOfflineOrderBy]
,[WhereSentence]
,[DefaultValue]
,[PersistDefaultValue]
,[IgnoreDBDefaultValue]
,[DetachedFromDB]
,[SearchFunction]
,[SearchCollection]
,[SearchWhere]
,[SearchReturnFields]
,[SecurityObject]
,[AllowNew]
,[AllowNewFunction]
,[AllowNewReturnFields]
,[AllowNewDefaults]
,[ObjNameLink]
,[ObjWhereLink]
,[TargetIdLink]
,[Style]
,[CSSClass]
,[LabelStyle]
,[LabelCSSClass]
,[DecimalPlaces]
,[RootPath]
,[FormatString]
,[DirectTemplate]
,[Tag]
,[HelpId]
,[ConnStringId]
,[IsRequired]
,[IsRequiredMessage]
,[minValue]
,[minValueMessage]
,[maxValue]
,[maxValueMessage]
,[RegExp]
,[RegExpText]
,[OnChangeJsFunction]
,[OnChangeProcessName]
,[PlaceHolder]
,[IconName]
,[ToolbarName]
,[Separator]
,[AutoIncrement]
,[AutoIncrementFunction]
,[CascadeDependencies]
,[RootPathType]
,[PageSize]
,[ImageCompressionType]
,[ImageMaxWidth]
,[ImageMaxHeight]
,[Offline]
,[ExtensionId]
/*,[OriginId]*/)
SELECT @NewObjectName --[ObjectName]
,[Objects_Properties].[PropertyName]
,[Objects_Properties].[Label]
,[Objects_Properties].[PositionY]
,[Objects_Properties].[PositionX]
,[Objects_Properties].[Width]
,[Objects_Properties].[Height]
,[Objects_Properties].[Hide]
,[Objects_Properties].[ClientReadOnly]
,[Objects_Properties].[FormDisplay]
,[Objects_Properties].[TypeId]
,[Objects_Properties].[Locked]
,OPT_NEW.CustomPropName
,[Objects_Properties].[Mask]
,[Objects_Properties].[SQlSentence]
,[Objects_Properties].[SQLEditSentence]
,[Objects_Properties].[SQLFilter]
,[Objects_Properties].[SQLValueField]
,[Objects_Properties].[SQLDisplayField]
,[Objects_Properties].[SQLObjectName]
,[Objects_Properties].[SQLViewName]
,[Objects_Properties].[SQLOfflineSentence]
,[Objects_Properties].[SQLOfflineOrderBy]
,[Objects_Properties].[WhereSentence]
,[Objects_Properties].[DefaultValue]
,[Objects_Properties].[PersistDefaultValue]
,[Objects_Properties].[IgnoreDBDefaultValue]
,[Objects_Properties].[DetachedFromDB]
,[Objects_Properties].[SearchFunction]
,[Objects_Properties].[SearchCollection]
,[Objects_Properties].[SearchWhere]
,[Objects_Properties].[SearchReturnFields]
,[Objects_Pro

pNet_OfflineCloneObject Stored

perties].[SecurityObject]
,[Objects_Properties].[AllowNew]
,[Objects_Properties].[AllowNewFunction]
,[Objects_Properties].[AllowNewReturnFields]
,[Objects_Properties].[AllowNewDefaults]
,[Objects_Properties].[ObjNameLink]
,[Objects_Properties].[ObjWhereLink]
,[Objects_Properties].[TargetIdLink]
,[Objects_Properties].[Style]
,[Objects_Properties].[CSSClass]
,[Objects_Properties].[LabelStyle]
,[Objects_Properties].[LabelCSSClass]
,[Objects_Properties].[DecimalPlaces]
,[Objects_Properties].[RootPath]
,[Objects_Properties].[FormatString]
,[Objects_Properties].[DirectTemplate]
,[Objects_Properties].[Tag]
,[Objects_Properties].[HelpId]
,[Objects_Properties].[ConnStringId]
,[Objects_Properties].[IsRequired]
,[Objects_Properties].[IsRequiredMessage]
,[Objects_Properties].[minValue]
,[Objects_Properties].[minValueMessage]
,[Objects_Properties].[maxValue]
,[Objects_Properties].[maxValueMessage]
,[Objects_Properties].[RegExp]
,[Objects_Properties].[RegExpText]
,[Objects_Properties].[OnChangeJsFunction]
,[Objects_Properties].[OnChangeProcessName]
,[Objects_Properties].[PlaceHolder]
,[Objects_Properties].[IconName]
,[Objects_Properties].[ToolbarName]
,[Objects_Properties].[Separator]
,[Objects_Properties].[AutoIncrement]
,[Objects_Properties].[AutoIncrementFunction]
,[Objects_Properties].[CascadeDependencies]
,[Objects_Properties].[RootPathType]
,[Objects_Properties].[PageSize]
,[Objects_Properties].[ImageCompressionType]
,[Objects_Properties].[ImageMaxWidth]
,[Objects_Properties].[ImageMaxHeight]
,1
,[Objects_Properties].[ExtensionId]
--,[OriginId]
FROM [dbo].[Objects_Properties]
left join Objects_Properties_Templates OPT_NEW ON [Objects_Properties].CustomPropName+'_Offline'=OPT_NEW.CustomPropName
WHERE [Objects_Properties].[ObjectName] = @ObjectName AND [Objects_Properties].[PropertyName] IN (SELECT value FROM STRING_SPLIT(@Properties, '|'))

/*Enable object on the webapi*/
INSERT INTO [dbo].[Offline_Objects]
([AppName]
,[ObjectName])
VALUES
(@AppName
,@NewObjectName)

INSERT INTO [dbo].[WebAPI_Objects]
([ObjectName]
,[CanView]
,[CanViewCollection]
,[CanInsert]
,[CanEdit]
,[CanDelete]
,[CanPrint])
VALUES
(@NewObjectName
,1
,1
,0
,0
,0
,0)


DECLARE @ObjectParsedDescrip NVARCHAR(510)
Declare @ObjectIconName T_IconName
DECLARE @CollectionDescrip NVARCHAR(510)

SELECT @ObjectIconName=IconName,@ObjectParsedDescrip=ParsedDescrip FROM [Objects] WHERE ObjectName=@NewObjectName
select @CollectionDescrip=ParsedDescrip from [Objects] where ObjectName=@NewCollectionName

DECLARE @IconCss NVARCHAR(200) = (select CSSClass from Icons where IconName=@ObjectIconName)
DECLARE @DefaultListTemplate NVARCHAR(MAX)
SET @DefaultListTemplate='
<ion-item lines="full" onclick="flexygo.nav.goView('''+@NewObjectName+''','''+@NewObjectName + '_View'',''{{objIdent|JS}}'')">
<ion-chip color="primary">
<i class="'+ISNULL(@IconCss,'')+'" ></i>
</ion-chip>
<ion-label>
<h2>'+ISNULL(@ObjectParsedDescrip,'Field1')+'</h2>
<h3><i class="ion-color-medium flx-icon icon-phone" ></i> TODO: Field 2</h3>
</ion-label>
</ion-item>'

DECLARE @DefaultViewTemplate NVARCHAR(MAX)
SET @DefaultViewTemplate='
<ion-card>
<ion-grid>
<ion-row>
<ion-col size="3">
<ion-chip color="medium" >
<i class="'+ISNULL(@IconCss,'')+' icon-lg" ></i>
</ion-chip>
</ion-col>
<ion-col size="9">
<ion-list>
<h5>'+ISNULL(@ObjectParsedDescrip,'Field1')+'</h5>
<p><i class="flx-icon icon-digger" ></i> {{Field1}}</p>
<p><i class="flx-icon icon-vc

pNet_OfflineCloneObject Stored

alendar" ></i> {{Field2}}</p>
</ion-list>
</ion-col>
</ion-row>
<ion-row >
<ion-col>
<ion-list>
<ion-list-header>
Descripci�n
</ion-list-header>
<ion-note>{{Descrip}}</ion-note>
</ion-list>
</ion-col>
</ion-row>
</ion-grid>
</ion-card>'

DECLARE @DefaultViewFooter NVARCHAR(MAX)
SET @DefaultViewFooter='<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button onclick="flexygo.nav.goEdit('''+@NewObjectName+''',null,''{{objIdent|JS}}'')">
<ion-icon name="create-outline"></ion-icon>
</ion-fab-button>
</ion-fab>'

DECLARE @DefaultListFooter NVARCHAR(MAX)
set @DefaultListFooter='<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button onclick="flexygo.nav.goInsert('''+@NewObjectName+''')">
<ion-icon name="add"></ion-icon>
</ion-fab-button>
</ion-fab>'

/*Default list and view page*/
INSERT INTO [dbo].[Offline_Pages]
([AppName]
,[PageName]
,[ObjectName]
,[TypeId]
,[Title]
,[Body]
,[Header]
,[Footer]
,[Empty]
,[SQLSentence]
,[ShowSearchBar]
,[IsDefault])
VALUES
(
@AppName
,@NewObjectName + '_List'
,@NewObjectName
,'list'
,@CollectionDescrip
,@DefaultListTemplate
,NULL
,@DefaultListFooter
,NULL
,NULL
,1
,1
),
(
@AppName
,@NewObjectName + '_View'
,@NewObjectName
,'view'
,@ObjectParsedDescrip
,@DefaultViewTemplate
,NULL
,@DefaultViewFooter
,NULL
,NULL
,0
,1
)

IF EXISTS (
select 1
from Objects_Properties
Where not Objects_Properties.SQLSentence is null and Objects_Properties.SQLObjectName is null and Objects_Properties.ObjectName=@NewObjectName
UNION
SELECT 1
FROM Objects_Properties_Templates
inner join Objects_Properties on Objects_Properties.CustomPropName=Objects_Properties_Templates.CustomPropName
Where
not Objects_Properties_Templates.SQLSentence is null
and Objects_Properties_Templates.SQLObjectName is null
and Objects_Properties.ObjectName=@NewObjectName )
BEGIN
SELECT 'flexygo.nav.openPageName(''sysOfflinePendingComboProperties'',''SysOfflineObject'',''(Offline_Objects.ObjectName=\''' + @NewObjectName + '\'')'',null,''modal'')' as Javascript
END ELSE BEGIN
SELECT 'flexygo.nav.openPageName(''syspage-generic-objectwizard'',''sysObject'',''(Objects.ObjectName=\''' + @NewObjectName + '\'')'',null,''modal'')' as Javascript
END

COMMIT TRAN
RETURN 1
END TRY
BEGIN CATCH
ROLLBACK TRAN
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)
RETURN 0
END CATCH

pNet_PowerBIIntegration Stored

CREATE PROCEDURE [dbo].[pNet_PowerBIIntegration]
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_PowerBIIntegrationn]
--#CREATION
-- 07/08/2020 - dmiralpeix
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Creates PowerBI settings entries
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIApiUrl','','chart-11','PowerBI Appi Url',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIApplicationId','','chart-11','PowerBI Application Secret',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIApplicationSecret','','chart-11','PowerBI Authentication Type',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIAuthenticationType','','chart-11','PowerBI Appi Url',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIAuthorityUrl','','chart-11','PowerBI Authority Url',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIPassword','','chart-11','PowerBI Password',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIResourceUrl','','chart-11','PowerBI Resource Url',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBITenant','','chart-11','PowerBI Application Secret',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIUsername','','chart-11','PowerBI Username',1,'flx-powerBI')
Insert Into Settings ([SettingName],[SettingValue],[IconName],[Description] ,[Active],[GroupName]) Values('PowerBIWorkspaceId','','chart-11','PowerBI WorkspaceId',1,'flx-powerBI')


COMMIT

select 'Please goto settings and fill out all the new PowerBi Settings' as WarningMessage


RETURN -1

END TRY
BEGIN CATCH

IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_relocateNode Stored


CREATE PROCEDURE [dbo].[pNet_relocateNode]
@NodeId VARCHAR(50),
@parentNodeId VARCHAR(50),
@Order INT
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_relocateNode]
--#CREATION
-- 15/06/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Relocate node table Navigation_Nodes
--#PARAMETERS
-- @NodeId: NodeId to relocate
-- @parentNodeId New parent of the node
-- @Order
--#OBSERVATIONS
--
--#CHANGES
-- 15/06/2017- jjrodriguez
----------------------------------------------------------------------------------
BEGIN TRY

IF NOT EXISTS(
SELECT NodeId FROM navigation_nodes WHERE NodeId = @NodeId
) BEGIN
RAISERROR('ERROR. Node does not exists.',12,1)
END

IF @ParentNodeId IS NOT NULL AND NOT EXISTS(
SELECT NodeId FROM navigation_nodes WHERE NodeId = @parentNodeId
) BEGIN
RAISERROR('ERROR. Parent node does not exists.',12,1)
END

CREATE TABLE #Children (NodeId VARCHAR(50),NewOrder INT)
INSERT INTO #Children(NodeId,NewOrder)
SELECT NodeId,ROW_NUMBER() OVER (ORDER BY [Order]) -1
FROM Navigation_Nodes
WHERE
NodeId <> @NodeId
AND (
(@parentNodeId IS NOT NULL AND ParentNodeId = @parentNodeId)
OR
(@parentNodeId IS NULL AND ParentNodeId IS NULL)
)
ORDER BY
[Order]

UPDATE #Children SET NewOrder = NewOrder + 1 WHERE NewOrder >= @Order

INSERT INTO #Children(NodeId,NewOrder)
SELECT @NodeId,@Order

UPDATE NN SET NN.ParentNodeId = @parentNodeId, NN.[Order] = C.NewOrder
FROM
Navigation_Nodes NN
INNER JOIN #Children C ON NN.NodeId = C.NodeId


RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_relocateOfflineMenu Stored


CREATE PROCEDURE [dbo].[pNet_relocateOfflineMenu]
@MenuId VARCHAR(50),
@parentMenuId VARCHAR(50),
@Order INT
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_relocateOfflineMenu]
--#CREATION
-- 22/10/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Relocate menu table OfflineMenus
--#PARAMETERS
-- @MenuId: MenuId to relocate
-- @parentMenuId New parent of the node
-- @Order
--#OBSERVATIONS
--
--#CHANGES
-- 22/10/2019- dmiralpeix
----------------------------------------------------------------------------------
BEGIN TRY

IF NOT EXISTS(
SELECT MenuId FROM Offline_Menus WHERE MenuId = @MenuId
) BEGIN
RAISERROR('ERROR. Menu does not exists.',12,1)
END

IF @ParentMenuId IS NOT NULL AND NOT EXISTS(
SELECT MenuId FROM Offline_Menus WHERE MenuId = @ParentMenuId
) BEGIN
RAISERROR('ERROR. Parent menu does not exists.',12,1)
END

CREATE TABLE #Children (MenuId VARCHAR(50),NewOrder INT)
INSERT INTO #Children(MenuId,NewOrder)
SELECT MenuId,ROW_NUMBER() OVER (ORDER BY [Order]) -1
FROM Offline_Menus
WHERE
MenuId <> @MenuId
AND (
(@parentMenuId IS NOT NULL AND parentMenuId = @parentMenuId)
OR
(@parentMenuId IS NULL AND parentMenuId IS NULL)
)
ORDER BY
[Order]

UPDATE #Children SET NewOrder = NewOrder + 1 WHERE NewOrder >= @Order

INSERT INTO #Children(MenuId,NewOrder)
SELECT @MenuId,@Order

UPDATE NN SET NN.ParentMenuId = @ParentMenuId, NN.[Order] = C.NewOrder
FROM
Offline_Menus NN
INNER JOIN #Children C ON NN.MenuId = C.MenuId


RETURN -1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX) = ERROR_MESSAGE()
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_RemoveImage Stored

CREATE PROCEDURE [dbo].[pNet_RemoveImage]
@ImageId uniqueidentifier

AS
DECLARE @ObjectName AS dbo.T_ObjectName
DECLARE @ObjectId AS nvarchar(170)
DECLARE @MainImage AS dbo.T_Boolean
DECLARE @OrderNumber AS INTEGER
DECLARE @Path AS nvarchar(300)
DECLARE @RImageId AS uniqueidentifier

SELECT @ObjectName = ObjectName, @ObjectId = ObjectId, @MainImage = MainImage, @OrderNumber = OrderNumber, @Path = Path FROM Objects_Images WHERE ImageId = @ImageId

DELETE FROM Objects_Images WHERE ImageId = @ImageId

IF @MainImage = 1
BEGIN
UPDATE
Objects_Images
SET
MainImage = 1
WHERE
ObjectName = @ObjectName
AND ObjectId = @ObjectId
AND OrderNumber = (SELECT MIN(OrderNumber) AS OrderNumber FROM Objects_Images WHERE ObjectName = @ObjectName AND ObjectId = @ObjectId)

SELECT @RImageId = ImageId FROM Objects_Images WHERE ObjectName = @ObjectName AND ObjectId = @ObjectId AND MainImage = 1
END

UPDATE
Objects_Images
SET
OrderNumber = OrderNumber -1
WHERE
ObjectName = @ObjectName
AND ObjectId = @ObjectId
AND OrderNumber > @OrderNumber

SELECT @RImageId AS ImageId

RETURN 1

pNet_RemoveImageRecognition Stored

CREATE PROCEDURE [dbo].[pNet_RemoveImageRecognition]
@ImageId uniqueidentifier

AS
DECLARE @ObjectName AS dbo.T_ObjectName
DECLARE @ObjectId AS nvarchar(170)
DECLARE @OrderNumber AS INTEGER
DECLARE @RImageId AS uniqueidentifier

SELECT @ObjectName = ObjectName, @ObjectId = ObjectId, @OrderNumber = OrderNumber FROM Objects_Images_Recognition WHERE ImageId = @ImageId

DELETE FROM Objects_Images_Recognition WHERE ImageId = @ImageId


UPDATE
Objects_Images_Recognition
SET
OrderNumber = OrderNumber -1
WHERE
ObjectName = @ObjectName
AND ObjectId = @ObjectId
AND OrderNumber > @OrderNumber

SELECT @RImageId AS ImageId

RETURN 1

pNet_ResizeProcessProperties Stored

CREATE PROCEDURE [dbo].[pNet_ResizeProcessProperties](
@Properties Tbl_Processes_Params_sizes readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ResizeProcessProperties
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Resizes and reordes a list of params.
--#PARAMETERS
-- @Properties: Table with the properties to resize.

--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017- Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY

update op
set [PositionX]=n.PositionX,
[PositionY]=n.positionY,
[Width]=n.width,
[Height]=n.height
from
Processes_Params op inner join @Properties n
on n.[Name]=op.ProcessName
and n.PropertyName=op.ParamName
where (n.width<>op.width or n.height<>op.height or n.PositionX<>op.PositionX or n.positionY<>op.positionY)


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ResizeProperties Stored

CREATE PROCEDURE [dbo].[pNet_ResizeProperties](
@Properties Tbl_Objects_Properties_sizes readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ResizeProperties
--#CREATION
-- 18/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Resizes a lis of properties.
--#PARAMETERS
-- @Properties: Table with the properties to resize.

--#OBSERVATIONS
--
--#CHANGES
-- 18/12/2016- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

update op
set [PositionX]=n.PositionX,
[PositionY]=n.positionY,
[Width]=n.width,
[Height]=n.height
from
objects_Properties op inner join @Properties n
on n.[Name]=op.ObjectName
and n.propertyname=op.propertyname
where (n.width<>op.width or n.height<>op.height or n.PositionX<>op.PositionX or n.positionY<>op.positionY)


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ResizeReportProperties Stored

CREATE PROCEDURE [dbo].[pNet_ResizeReportProperties](
@Properties Tbl_Reports_Params_sizes readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ResizeReportProperties
--#CREATION
-- 05/09/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Resizes and reordes a list of params.
--#PARAMETERS
-- @Properties: Table with the properties to resize.

--#OBSERVATIONS
--
--#CHANGES
-- 05/09/2017- Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY

update op
set [PositionX]=n.PositionX,
[PositionY]=n.positionY,
[Width]=n.width,
[Height]=n.height
from
Reports_Params op inner join @Properties n
on n.[Name]=op.ReportName
and n.PropertyName=op.ParamName
where (n.width<>op.width or n.height<>op.height or n.PositionX<>op.PositionX or n.positionY<>op.positionY)


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveDocument Stored

CREATE PROCEDURE [dbo].[pNet_SaveDocument]
@DocumentName nvarchar(100),
@DocumentExtension nvarchar(10),
@DocumentType nvarchar(50),
@ObjectName T_ObjectName,
@ObjectId nvarchar(250),
@Path nvarchar(500),
@DownloadLink nvarchar(500),
@InProgress BIT,
@CloudId nvarchar(250),
@DefaultCategory NVARCHAR(100)

AS
DECLARE @DocGuidT table(DocGuid uniqueidentifier, CreationDate smalldatetime, CategoryId nvarchar(50), Description nvarchar(250))
DECLARE @Origin AS nvarchar(50)
DECLARE @IconName AS T_IconName
DECLARE @DocGuid AS uniqueidentifier
DECLARE @CreationDate AS smalldatetime
DECLARE @CategoryId AS nvarchar(50)
DECLARE @Description AS nvarchar(250)
DECLARE @Category AS nvarchar(255)

SELECT @Origin = ISNULL((SELECT Origin FROM Documents_Extensions WHERE extension = @DocumentExtension) ,'FILE'), @IconName = ISNULL((SELECT IconName FROM Documents_Extensions WHERE extension = @DocumentExtension) ,'file-o');

if @DefaultCategory is NULL BEGIN
INSERT INTO [dbo].[Documents]([Name])
OUTPUT Inserted.DocGuid, inserted.CreationDate, inserted.CategoryId, inserted.Description INTO @DocGuidT
VALUES(@DocumentName);
END ELSE BEGIN
INSERT INTO [dbo].[Documents]([Name],CategoryId)
OUTPUT Inserted.DocGuid, inserted.CreationDate, inserted.CategoryId, inserted.Description INTO @DocGuidT
VALUES(@DocumentName,@DefaultCategory);
END

SELECT TOP 1 @DocGuid = DocGuid, @CreationDate = CreationDate, @CategoryId = CategoryId, @Description = Description FROM @DocGuidT;

SELECT TOP 1 @Category = Category FROM Documents_Category WHERE CategoryId = @CategoryId

INSERT INTO [dbo].[Documents_Objects]([DocGuid],[ObjectName],[ObjectId])
VALUES (@DocGuid,@ObjectName ,@ObjectId);

INSERT INTO [dbo].[Documents_Versions]([DocGuid],[Revision],[FilePath],[DownloadLink],[CloudID],[DocumentTypeName],[InProgress],[Origin])
VALUES (@DocGuid,0,@Path,@DownloadLink,@CloudId,@DocumentType,@InProgress,@Origin);


SELECT @DocGuid AS DocGuid,@CreationDate AS CreationDate, @Category AS Category, @CategoryId AS CategoryId, @Description AS Description, @Origin AS Origin, CSSClass
FROM Icons
WHERE IconName = @IconName;


RETURN 1

pNet_SaveEmail Stored

CREATE PROCEDURE [dbo].[pNet_SaveEmail]
@MessageId [dbo].[T_MailID],
@HeaderMessageId [dbo].[T_MailID],
@Uid [bigint],
@MailDate [SMALLDATETIME],
@Subject [NVARCHAR](MAX),
@BodyHtml [NVARCHAR](MAX),
@BodyText [NVARCHAR](MAX),
@BodyRtf [nvarchar](max),
@InReplyTo [dbo].[T_MailID],
@PartialId [dbo].[T_MailID],
@Importance [nvarchar](150),
@MimeVersion [nvarchar](150),
@RcptTo [nvarchar](150),
@ReturnPath [nvarchar](150),
@MailAccountId [nvarchar](100),
@FolderId [nvarchar](50),
@IsForward [dbo].[T_Boolean],
@IsReply [dbo].[T_Boolean],
@IsPartial [dbo].[T_Boolean],
@IsEncrypted [dbo].[T_Boolean],
@IsSigned [dbo].[T_Boolean],
@IsLinked [dbo].[T_Boolean],
@HasAttachments [dbo].[T_Boolean],
@FromAddress [nvarchar](500),
@FromName [nvarchar](500),
@MailTo [nvarchar](500),
@MailCC [nvarchar] (500),
@Seen [dbo].[T_Boolean]
AS

Insert into Mails ([MessageId],[HeaderMessageId],[Uid], [MailDate], [Subject], [BodyHtml], [BodyText], [BodyRtf], [InReplyTo], [PartialId], [Importance], [MimeVersion], [RcptTo], [ReturnPath], [MailAccountId], [FolderId], [IsForward], [IsReply], [IsPartial], [IsEncrypted], [IsSigned], [IsLinked], [HasAttachments], [FromAddress], [FromName], [MailTo], [MailCC], [Seen],[Sincronizado])
VALUES (@MessageId,@HeaderMessageId,@Uid, @MailDate, @Subject, @BodyHtml, @BodyText, @BodyRtf, @InReplyTo, @PartialId, @Importance, @MimeVersion, @RcptTo, @ReturnPath, @MailAccountId, @FolderId, @IsForward, @IsReply, @IsPartial, @IsEncrypted, @IsSigned, @IsLinked, @HasAttachments, @FromAddress, @FromName, @MailTo ,@MailCC, @Seen,0)

RETURN 1

pNet_SaveEmailAttachments Stored

CREATE PROCEDURE [dbo].[pNet_SaveEmailAttachments]
@MessageId [dbo].[T_MailID],
@AttachmentId [NVARCHAR](100),
@FileName [NVARCHAR](250),
@ContentType [NVARCHAR](50),
@FilePath [NVARCHAR](250),
@Size [INT],
@IsEmbebed [Bit]
AS

Insert into Mails_Attachments ([MessageId], [AttachmentId], [FileName], [ContentType], [FilePath], [Size], [IsEmbebed])
VALUES (@MessageId, @AttachmentId, @FileName, @ContentType, @FilePath, @Size, @IsEmbebed)

RETURN 1

pNet_SaveEmails Stored

CREATE PROCEDURE [dbo].[pNet_SaveEmails]
@Tbl_Mails Tbl_Mails READONLY
AS

Insert into Mails ([MessageId],[HeaderMessageId],[Uid], [MailDate], [Subject], [BodyHtml], [BodyText], [BodyRtf], [InReplyTo], [PartialId], [Importance], [MimeVersion], [RcptTo], [ReturnPath], [MailAccountId], [FolderId], [IsForward], [IsReply], [IsPartial], [IsEncrypted], [IsSigned], [IsLinked], [HasAttachments], [FromAddress], [FromName], [MailTo], [MailCC], [Seen], [Sincronizado])
Select tbl.MessageId,tbl.HeaderMessageId,tbl.[Uid], tbl.MailDate, tbl.[Subject], tbl.BodyHtml, tbl.BodyText, tbl.BodyRtf, tbl.InReplyTo, tbl.PartialId, tbl.Importance, tbl.MimeVersion, tbl.RcptTo, tbl.ReturnPath, tbl.MailAccountId, tbl.FolderId, tbl.IsForward, tbl.IsReply, tbl.IsPartial, tbl.IsEncrypted, tbl.IsSigned, tbl.IsLinked, tbl.HasAttachments, tbl.FromAddress, tbl.FromName, tbl.MailTo ,tbl.MailCC, tbl.Seen, 1
From @Tbl_Mails tbl LEFT JOIN Mails on tbl.[MessageId] = Mails.[MessageId]
Where Mails.[MessageId] IS NULL

RETURN 1

pNet_SaveImage Stored

CREATE PROCEDURE [dbo].[pNet_SaveImage]
@ObjectName dbo.T_ObjectName,
@ObjectId nvarchar(170),
@Name nvarchar(255),
@Path nvarchar(300),
@ImageClassId nvarchar(50),
@CreationDate smalldatetime = NULL
AS
DECLARE @MainImage AS dbo.T_Boolean
DECLARE @OrderNumber AS INTEGER

IF @CreationDate IS NULL
SET @CreationDate = GETDATE()

SELECT @OrderNumber = ISNULL(MAX(OrderNumber) + 1, 0) FROM Objects_Images WHERE ObjectName = @ObjectName AND ObjectId = @ObjectId

IF (SELECT COUNT(ImageId) FROM Objects_Images WHERE ObjectName = @ObjectName AND ObjectId = @ObjectId) = 0
BEGIN
SELECT @MainImage = 1
END
ELSE
BEGIN
SELECT @MainImage = 0
END

INSERT INTO [dbo].[Objects_Images]
([ObjectName]
,[ObjectId]
,[Name]
,[ImageClassId]
,[MainImage]
,[OrderNumber]
,[Path]
,[CreationDate])
OUTPUT
inserted.ImageId
,inserted.ObjectName
,inserted.ObjectId
,inserted.Name
,inserted.Descrip
,inserted.[ImageClassId]
,inserted.MainImage
,inserted.OrderNumber
,inserted.Path
,inserted.CreationDate
VALUES
(@ObjectName
,@ObjectId
,@Name
,@ImageClassId
,@MainImage
,@OrderNumber
,@Path
,@CreationDate)


RETURN 1

pNet_SaveImageRecognition Stored

CREATE PROCEDURE [dbo].[pNet_SaveImageRecognition]
@ObjectName dbo.T_ObjectName,
@ObjectId nvarchar(170),
@Name nvarchar(255),
@Path nvarchar(300)
AS
DECLARE @OrderNumber AS INTEGER

SELECT @OrderNumber = ISNULL(MAX(OrderNumber) + 1, 0) FROM Objects_Images_Recognition WHERE ObjectName = @ObjectName AND ObjectId = @ObjectId



INSERT INTO [dbo].[Objects_Images_Recognition]
([ObjectName]
,[ObjectId]
,[Name]
,[OrderNumber]
,[Path])
OUTPUT
inserted.ImageId
,inserted.ObjectName
,inserted.ObjectId
,inserted.Name
,inserted.OrderNumber
,inserted.Path
VALUES
(@ObjectName
,@ObjectId
,@Name
,@OrderNumber
,@Path)


RETURN 1

pNet_SaveMails_Folders Stored

CREATE PROCEDURE [dbo].[pNet_SaveMails_Folders]
@MailAccountId nvarchar(100),
@FolderId nvarchar(50),
@Descrip nvarchar(500),
@IsInbox [T_Boolean],
@IsSent [T_Boolean],
@IsOutbox [T_Boolean],
@CanSelect [T_Boolean],
@Parent NVARCHAR(50) = NULL

AS

IF (Select COUNT(*) as Cuenta From Mails_Folders Where FolderId = @FolderId) = 0
BEGIN
INSERT INTO Mails_Folders(FolderId,Descrip,IsInbox,IsSent,IsOutbox,CanSelect,Parent)
VALUES(@FolderId,@Descrip,@IsInbox,@IsSent,@IsOutbox,@CanSelect,@Parent)
END

IF (Select COUNT(*) as Cuenta From Mails_Folders_Accounts Where FolderId = @FolderId and MailAccountId=@MailAccountId) = 0
BEGIN
INSERT INTO Mails_Folders_Accounts(MailAccountId,FolderId)
VALUES(@MailAccountId,@FolderId)
END

RETURN 1

pNet_SaveObjects_Search Stored



CREATE PROCEDURE [dbo].[pNet_SaveObjects_Search](
@SearchId VARCHAR(50) OUTPUT,
@FilterDescrip nvarchar(200),
@ObjectName T_ObjectName,
@Type nvarchar(100),
@Generic BIT,
@UserId T_UserId,
@FilterFields Tbl_Objects_Search_Properties readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveObjects_Search
--#CREATION
-- 09/03/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves search filter
--#PARAMETERS
-- @FilterId: Search filter Id.
-- @FilterDescrip: Filter name.
-- @FilterFields: Table with each field.
--#OBSERVATIONS
--
--#CHANGES
-- 09/03/2017- Rubén Pardo
-- 01/08/2017-JJR-Add type and generic parameter
----------------------------------------------------------------------------------
BEGIN TRY


--If filter is new insert it on BBDD
IF @SearchId is null BEGIN

DECLARE @Order INT
DECLARE @Inserted TABLE(Id UNIQUEIDENTIFIER)

SET @Order = ISNULL((SELECT MAX([order])+1 FROM Objects_Search WHERE objectName=@ObjectName),1)

INSERT INTO Objects_Search (ObjectName,Name,Generic,IsDefault,Type,[Order],UserId)
OUTPUT (Inserted.SearchId) INTO @Inserted
VALUES (@ObjectName,@FilterDescrip,@Generic,CASE WHEN @Generic = 1 THEN 1 ELSE 0 END,@Type,@Order,NULL)

SELECT TOP 1 @SearchId = CAST(Id AS VARCHAR(50)) FROM @Inserted

IF @Generic = 1 BEGIN
INSERT INTO Objects_Search_Users_Settings(SearchId,UserId,[Enabled],[Order])
SELECT @SearchId,@UserId,1,(SELECT ISNULL(MAX([Order]),-1)+1 FROM Objects_Search_Users_Settings WHERE UserId=@UserId)
END

--Else just update descrip and type, and reset SQLSentence
END ELSE BEGIN

UPDATE Objects_Search SET Name=@FilterDescrip,Type=@Type,SQLSentence=NULL WHERE SearchId=@SearchId

END

--Delete and reinsert all filter properties
DELETE Objects_Search_Properties WHERE Searchid=@SearchId

INSERT INTO Objects_Search_Properties (SearchId,ObjectName,PropertyName,ObjectPath,Size,[Order],Label,PropertySearchType)
SELECT @SearchId, ObjectName,PropertyName,ObjectPath,Size,[Order],Label,PropertySearchType FROM @FilterFields


RETURN 1

END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveSearchCriteria Stored





CREATE PROCEDURE [dbo].[pNet_SaveSearchCriteria](
@SearchId VARCHAR(50),
@FilterSqlSentence as T_SQLSentence
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveSearchCriteria
--#CREATION
-- 18/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves search criteria based on selected fields
--#PARAMETERS
-- @SearchId: Search criteria Id
-- @FilterSqlSentence: SQL Sentence to be updated
--#OBSERVATIONS
--
--#CHANGES
-- 18/12/2016- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

update Objects_Search set SQLSentence=@FilterSqlSentence where SearchId=@SearchId

RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveSetting Stored

CREATE PROCEDURE pNet_SaveSetting(
@SettingName as nvarchar(150),
@SettingValue AS nvarchar (1000),
@GroupName AS nvarchar (20),
@Descrip AS nvarchar (1000),
@IconName as nvarchar(100)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveSetting
--#CREATION
-- 18/12/2020
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves or updates Setting
--#PARAMETERS
--@SettingName as nvarchar(150)
--@SettingValue AS nvarchar (1000)
--@GroupName AS nvarchar (20)
--@Descrip AS nvarchar (1000)
--@IconName as nvarchar(100)

--#OBSERVATIONS
--
--#CHANGES
-- 18/12/2020- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY
declare @Exists as integer=0
Select @Exists=count(1) from Settings where SettingName=@SettingName

if @exists >0 Begin
Update Settings Set SettingValue=@Settingvalue, GroupName=@GroupName, [Description]=@Descrip,IconName=@IconName where SettingName=@SettingName
END
ELSE
BEGIN
Insert Into Settings (SettingName,SettingValue,IconName,[Description],GroupName,Active) values(@SettingName,@SettingValue,@IconName,@Descrip,@GroupName,1)
END

RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveToken Stored

CREATE PROCEDURE pNet_SaveToken

@Id nvarchar(256),
@TokenType nvarchar(128),
@AccessToken nvarchar(max),
@RefreshToken nvarchar(512),
@RefreshData nvarchar(max),
@Scope nvarchar(max),
@ExpiryDate smalldatetime,
@AppName nvarchar(512)

AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveToken
--#CREATION
-- 27/11/2020
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Save token into flexygo database
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

SET NOCOUNT ON;

insert into AspNetUsers_Tokens (Id,TokenType,AccessToken,RefreshToken,RefreshData,Scope,ExpiryDate,InsertedDate,AppName)
values (@Id,@TokenType,@AccessToken,@RefreshToken,@RefreshData,@Scope,@ExpiryDate,GETDATE(),@AppName)

return 1

END

pNet_SaveUserSearchCriteriasChecked Stored




CREATE PROCEDURE [dbo].[pNet_SaveUserSearchCriteriasChecked](
@UserId T_UserId,
@SearchId as uniqueidentifier,
@Enabled as T_BOOLEAN
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveUserSearchCriteriasChecked
--#CREATION
-- 18/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves user search criterias check values.
--#PARAMETERS
-- @UserId : The User Id.
-- @SearchId: The SearchId.
-- @Enabled: Enabled or not.
--#OBSERVATIONS
--
--#CHANGES
-- 18/12/2016- David MiralpeiX
-- 31/07/2017- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

if (select count(*) from Objects_Search_Users_Settings osus WHERE UserId=@UserId and osus.SearchId=@SearchId)=0
BEGIN
insert into Objects_Search_Users_Settings (SearchId,UserId,[Enabled],[order]) values(@SearchId,@UserId,@Enabled,-1)
END
ELSE
BEGIN
UPDATE osus
SET Enabled=@Enabled FROM Objects_Search_Users_Settings osus WHERE (osus.Enabled<>@Enabled) and UserId=@UserId and osus.SearchId=@SearchId
END
RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveUserSearchCriteriasOrder Stored




CREATE PROCEDURE [dbo].[pNet_SaveUserSearchCriteriasOrder](
@UserId T_UserId,
@OrderedObjects Tbl_KeyValuePairs readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveUserSearchCriteriasOrder
--#CREATION
-- 18/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves user ordered search criterias.
--#PARAMETERS
-- @UserId : The User Id.
-- @OrderedObjects: Table with the ordered objects.

--#OBSERVATIONS
--
--#CHANGES
-- 18/12/2016- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

UPDATE osus
SET [Order]=oob.value
FROM
Objects_Search_Users_Settings osus INNER JOIN @OrderedObjects oob
ON oob.[key]=osus.SearchId AND osus.UserId=@UserId
WHERE (oob.value<>osus.[Order])


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveView Stored


CREATE PROCEDURE [dbo].[pNet_SaveView](
@ObjectName T_ObjectName,
@ViewName nvarchar(255),
@Descrip nvarchar(255),
@ViewSQL T_SQlsentence,
@ViewFields Tbl_Objects_Search_Properties readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveView
--#CREATION
-- 12/04/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves object view
--#PARAMETERS
-- @ObjectName T_ObjectName,
-- @ObjectView nvarchar(255),
-- @Descrip nvarchar(255),
-- @ViewSQL T_SQlsentence,
-- @FilterFields Tbl_Objects_Search_Properties readonly
--#OBSERVATIONS
--
--#CHANGES
-- 09/03/2017- Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY


IF (select count(*) from Objects_Views where objectname=@ObjectName and ViewName=@ViewName) > 0 BEGIN
update Objects_views set SQLSentence=@ViewSQL where Objectname=@ObjectName and ViewName=@ViewName
END ELSE BEGIN
insert into Objects_views (ObjectName, ViewName, Descrip, ConnStringId, SQLSentence, NoFilter, Active, ShowAsGrid, IsDefault)
values (@ObjectName,@ViewName,@Descrip,(select ConnStringID from [Objects] where ObjectName=@ObjectName), @ViewSQL, 0, 1, 1, 1)
END

delete Objects_Views_Properties where ObjectName=@ObjectName and ViewName=@ViewName

insert into Objects_Views_Properties (ObjectName,ViewName,ObjectPropertyName,PropertyName,ObjectPath,[Order],Label)
select @ObjectName, @ViewName, ObjectName,PropertyName,ObjectPath,[Order],Label from @ViewFields

RETURN 1

END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SaveWorkflow Stored

CREATE PROCEDURE [dbo].[pNet_SaveWorkflow]
@WorkflowId [dbo].[T_ProcessName],
@Version SMALLINT OUTPUT,
@ModuleId NVARCHAR(50),
@AreaId NVARCHAR(50),
@Descrip NVARCHAR(255),
@WorkflowData NVARCHAR(MAX),
@Active BIT
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SaveWorkflow
--#CREATION
-- 19/02/2018
--#CLASIFICATION
-- GIPE
--#DESCRIPTION
-- Saves a workflow
--#PARAMETERS
-- @WorkflowId Workflow identifier
-- @Version Workflow version
-- @ModuleId Workflow module
-- @AreaId Workflow area
-- @Descrip Workflow descrip
-- @WorkflowData Workflow graphic representation
-- @Active Workflow active

--#OBSERVATIONS
--
-- If a standard workflow (OriginId<2) is modified, a new version is generated
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRAN

IF EXISTS(

SELECT 1
FROM Workflows
WHERE
WorkflowId = @WorkflowId AND Version = @Version AND OriginId < dbo.funNet_GetOrigin()
) BEGIN

--Modification of a standar process. Generate new version
SELECT @Version = MAX(Version)+1
FROM Workflows
WHERE
WorkflowId = @WorkflowId

IF @Active = 1 BEGIN

UPDATE Workflows SET Active = 0 WHERE WorkflowId = @WorkflowId
END
END


IF NOT EXISTS(
SELECT 1
FROM Workflows
WHERE
WorkflowId = @WorkflowId AND Version = @Version
) BEGIN

INSERT INTO Workflows(WorkflowId,Version,ModuleId,AreaId,Descrip,WorkflowData,Active)
SELECT @WorkflowId,@Version,@ModuleId,@AreaId,@Descrip,@WorkflowData,@Active


END ELSE BEGIN

--Update area, module, and description for all versions
UPDATE Workflows SET
ModuleId = @ModuleId,
AreaId = @AreaId,
Descrip = @Descrip,
WorkflowData = CASE WHEN Version = @Version THEN @WorkflowData ELSE WorkflowData END,
Active = CASE @Active WHEN 1 THEN --Deactive rest of workflows
CASE WHEN Version = @Version THEN 1 ELSE 0 END
ELSE
CASE WHEN Version = @Version THEN @Version ELSE Version END
END
WHERE
WorkflowId = @WorkflowId

END


COMMIT TRAN

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SecurityUnlockUser Stored



CREATE PROCEDURE [dbo].[pNet_SecurityUnlockUser](
@UserId nvarchar(128)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SecurityUnlockUser
--#CREATION
-- 17/11/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Unlocks a locked out user
--#PARAMETERS
-- @UserId: UserId

--#OBSERVATIONS
--
--#CHANGES
-- 07/06/2016- David Miralpeix
-- 05/09/2018- Alberto Criado Andrés
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction
update aspnetUsers set AccessFailedCount=0, LockoutEndDateUtc=null where Id=@UserId
COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetCultureEntries Stored


CREATE PROCEDURE [dbo].[pNet_SetCultureEntries](
@translated Tbl_Translate_Cuture_Entries readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SetCultureEntries
--#CREATION
-- 18/07/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Updates Trasnlation table with translated entries.
--#PARAMETERS
-- @translated: Table with the translated entries.

--#OBSERVATIONS
--
--#CHANGES
-- 18/07/2017- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

update t
set [Text]=n.[text]
from
Translate t inner join @translated n
on n.original=t.Original and
n.CultureId=t.CultureId and
n.Area=t.Area


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetLicenseActivationCode Stored

CREATE PROCEDURE [dbo].[pNet_SetLicenseActivationCode]
@LicenseId NVARCHAR(50),
@ActivationCode NVARCHAR(50)
AS
----------------------------------------------------------------------------------
--#NAME
--
--#CREATION
-- 08/11/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Stores license activation code into database
--#PARAMETERS
-- @LicenseId: License Id
-- @RequestData: Activation request Data

--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY

UPDATE License SET LicenseCode = @ActivationCode WHERE LicenseId = @LicenseId

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetLicenseData Stored

CREATE PROCEDURE [dbo].[pNet_SetLicenseData]
@RequestId NVARCHAR(50),
@LicenseId NVARCHAR(50),
@LicenseData NVARCHAR(MAX)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SetLicenseData
--#CREATION
-- 08/11/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Stores license data into database
--#PARAMETERS
-- @RequestId: Request Id
-- @LicenseId: License Id
-- @LicenseData: License Data
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY

IF EXISTS(
SELECT 1 FROM License
WHERE (
(LicenseId = @LicenseId)
OR
(LicenseId = '' AND RequestId = @RequestId)
)

) BEGIN

UPDATE License SET LicenseData = @LicenseData, LicenseId = CASE WHEN LicenseId = '' THEN @LicenseId ELSE LicenseId END
WHERE (
(LicenseId = @LicenseId)
OR
(LicenseId = '' AND RequestId = @RequestId)
)

END ELSE BEGIN

INSERT INTO License(RequestId,LicenseId,RequestData,LicenseData)
SELECT @RequestId,@LicenseId,@LicenseData,@LicenseData

END

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetPushMessageSent Stored


CREATE PROCEDURE [dbo].[pNet_SetPushMessageSent]
@NoticeId nvarchar(200),
@UserId T_UserId,
@CurrentReference nvarchar(100),
@NoticeUserId nvarchar(200),
@AllUsers bit,
@ErrorMsg nvarchar(max)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SetPushMessageSent
--#CREATION
-- 12/12/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Get pending push messages
--#PARAMETERS
--#OBSERVATIONS
--
--#CHANGES
---------------------------------------------------------------------------------
BEGIN TRY


BEGIN

if @AllUsers=1 BEGIN
update Notices set AllUsersIsSent=1,Error=case when @Errormsg is null then 0 else 1 end,ErrorMsg=@ErrorMsg where NoticeId=@NoticeId
insert into Notices_Users (NoticeId,UserId,CurrentReference,IsSent,IsRead,Error,ErrorMsg) Values (@NoticeId,@UserId,@CurrentReference,1,0,case when @Errormsg is null then 0 else 1 end,@ErrorMsg)
END ELSE BEGIN
if NOT @ErrorMsg is null BEGIN
update Notices set Error=case when @Errormsg is null then 0 else 1 end,ErrorMsg=@ErrorMsg where NoticeId=@NoticeId
END
Update Notices_Users set IsSent=1,Error=case when @Errormsg is null then 0 else 1 end,ErrorMsg=@ErrorMsg where id=@NoticeUserId
END


END

RETURN 1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetRequestData Stored

CREATE PROCEDURE [dbo].[pNet_SetRequestData]
@RequestId NVARCHAR(50),
@RequestData NVARCHAR(MAX)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SetRequestData
--#CREATION
-- 08/11/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Stores Request data into database
--#PARAMETERS
-- @RequestId: Request Id
-- @RequestData: Request Data
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

BEGIN TRY

IF EXISTS(
SELECT 1 FROM License WHERE RequestId = @RequestId
) BEGIN

UPDATE License SET RequestData = @RequestData WHERE RequestId = @RequestId

END ELSE BEGIN

DELETE FROM License

INSERT INTO License(RequestId,LicenseId,RequestData,LicenseData)
SELECT @RequestId,'',@RequestData,''

END

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetSecurity Stored

CREATE PROCEDURE [dbo].[pNet_SetSecurity](
@SecurityType varchar(100) ,
@SecurityKey varchar (100),
@SecurityKey2 varchar (255),
@SecurityItem varchar(100),
@SecurityItemValue T_Boolean,
@SecurityId varchar(128)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_SetRoleSecurity
--#CREATION
-- 28/12/2016
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Sets security option of a given type for a given element(object name, process Id,node Id..)
-- Using a security item (insert, update, view..) for a given User or Role
--#PARAMETERS
-- @SecurityType: sysSecObjectRole, sysSecObjectPropertyRole, sysSecProcessRole,sysSecNodeRole,
-- sysSecHelpRole,sysSecReportRole,sysSecPageRole,sysSecModuleRole,sysMasterTablesRols,
-- sysSecObjectUser, sysSecObjectPropertyUser, sysSecProcessUser,sysSecNodeUser,
-- sysSecHelpUser,sysSecReportUser,sysSecPageUser,sysSecModuleUser,,sysMasterTablesUser
-- sysSecObjectFaculty, sysSecObjectPropertyFaculty, sysSecProcessFaculty,sysSecNodeFaculty,
-- sysSecHelpFaculty,sysSecReportFaculty,sysSecPageFaculty,sysSecModuleFaculty

-- @SecurityKey: Identifier (object name, process Id,node Id..)
-- @SecurityKey2: Identifier (object name, process Id,node Id..) only for double keys
-- @SecurityItem: Insert, Update, view, delete, run....
-- @SecurityItemValue: True or false (1 or 0)
-- @SecurityId: Role or User or Faculty Identifier
--#OBSERVATIONS
--
--#CHANGES
-- 28/12/2016- David MiralpeiX
-- 05/12/2018- David MiralpeiX added templates
-- 20/11/2020- David Miralpeix added Faculties
----------------------------------------------------------------------------------
BEGIN TRY
declare @Count int
declare @sql nvarchar(2000);

---- OBJECT SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecObjectRole'
BEGIN
SELECT @Count=count(ObjectName) FROM Security_Objects_Roles WHERE ObjectName=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Object
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Roles]([ObjectName] ,[RoleId] ,[CanView],[ViewFilter] ,[CanViewCollection],[ViewFilterCollection] ,[CanInsert] ,[InsertFilter],[CanEdit],[EditFilter]
,[CanDelete],[DeleteFilter],[CanPrint]) VALUES (@SecurityKey,@SecurityId,1,Null,1,Null,1,Null, 1,Null,1,Null,1)
END
Else -- There is allready an entry for that Object and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecObjectFaculty'
BEGIN
SELECT @Count=count(ObjectName) FROM Security_Objects_Faculties WHERE ObjectName=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Object
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Faculties]([ObjectName] ,[FacultyId] ,[CanView],[ViewFilter] ,[CanViewCollection],[ViewFilterCollection] ,[CanInsert] ,[InsertFilter],[CanEdit],[EditFilter]
,[CanDelete],[DeleteFilter],[CanPrint]) VALUES (@SecurityKey,@SecurityId,1,Null,1,Null,1,Null, 1,Null,1,Null,1)
END
Else -- There is allready an entry for that Object and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecObjectUser'
BEGIN
SELECT @Count=count(ObjectName) FROM Security_Objects_Users

pNet_SetSecurity Stored

WHERE ObjectName=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that User and that Object
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Users]([ObjectName] ,[UserId] ,[CanView],[ViewFilter] ,[CanViewCollection],[ViewFilterCollection] ,[CanInsert] ,[InsertFilter],[CanEdit],[EditFilter]
,[CanDelete],[DeleteFilter],[CanPrint]) VALUES (@SecurityKey,@SecurityId,1,Null,1,Null,1,Null, 1,Null,1,Null,1)
END
Else -- There is allready an entry for that Object and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END OBJECT SECURITY FOR ROLES AND USERS------------------------------------------


---- OBJECT PROPERTY SECURITY FOR ROLES AND USERS-------------------------------------

IF @SecurityType='sysSecObjectPropertyRole'
BEGIN
SELECT @Count=count(PropertyName) FROM Security_Objects_Properties_Roles WHERE ObjectName=@SecurityKey and PropertyName=@SecurityKey2 and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Object property
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Properties_Roles]([ObjectName], [PropertyName] ,[RoleId] ,[CanView],[CanEdit]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,1)
END
Else -- There is allready an entry for that Object property and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Properties_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and PropertyName=''' + @SecurityKey2 + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecObjectPropertyFaculty'
BEGIN
SELECT @Count=count(PropertyName) FROM Security_Objects_Properties_Faculties WHERE ObjectName=@SecurityKey and PropertyName=@SecurityKey2 and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Object property
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Properties_Faculties]([ObjectName], [PropertyName] ,[FacultyId] ,[CanView],[CanEdit]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,1)
END
Else -- There is allready an entry for that Object property and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Properties_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and PropertyName=''' + @SecurityKey2 + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecObjectPropertyUser'
IF @SecurityType='sysSecObjectPropertyUser'
BEGIN
SELECT @Count=count(PropertyName) FROM Security_Objects_Properties_Users WHERE ObjectName=@SecurityKey and PropertyName=@SecurityKey2 and UserId=@SecurityId

if @Count=0 -- No security for that User and that Object property
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Properties_Users]([ObjectName] , [PropertyName] ,[userId],[CanView],[CanEdit]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,1)
END
Else -- There is all ready an entry for that Object property and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Properties_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and PropertyName=''' + @SecurityKey2 + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

pNet_SetSecurity Stored



---- END OBJECT PROPERTY SECURITY FOR ROLES AND USERS-------------------------------------


---- PROCESS SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecObjectProcessRole'
BEGIN
SELECT @Count=count(ProcessName) FROM Security_Objects_Processes_Roles WHERE ObjectName=@SecurityKey and ProcessName=@SecurityKey2 and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Object process
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Processes_Roles] ([ObjectName] ,[ProcessName],[RoleId] ,[CanView],[ViewFilter] ) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,Null)
END
Else -- There is allready an entry for that Object process and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Processes_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and ProcessName=''' + @SecurityKey2 + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecObjectProcessFaculty'
BEGIN
SELECT @Count=count(ProcessName) FROM Security_Objects_Processes_Faculties WHERE ObjectName=@SecurityKey and ProcessName=@SecurityKey2 and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Object process
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Processes_Faculties] ([ObjectName] ,[ProcessName],[FacultyId] ,[CanView],[ViewFilter] ) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,Null)
END
Else -- There is allready an entry for that Object process and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Processes_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and ProcessName=''' + @SecurityKey2 + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecObjectProcessUser'
BEGIN
SELECT @Count=count(ProcessName) FROM Security_Objects_Processes_Users WHERE ObjectName=@SecurityKey and ProcessName=@SecurityKey2 and UserId=@SecurityId

if @Count=0 -- No security for that User and that Object process
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Processes_Users]([ObjectName],[ProcessName] ,[UserId] ,[CanView],[ViewFilter]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1,Null)
END
Else -- There is allready an entry for that Object process and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Processes_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ObjectName=''' + @SecurityKey + ''' and ProcessName=''' + @SecurityKey2 + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END PROCESS SECURITY FOR ROLES AND USERS------------------------------------------

---- TEMPLATE SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecObjectTemplateRole'
BEGIN
SELECT @Count=count(TemplateId) FROM Security_Objects_Templates_Roles WHERE TemplateId=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Object template
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Templates_Roles] ([TemplateId],[RoleId] ,[CanView] ) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Object template and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Templates_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE TemplateId=''' + @Security

pNet_SetSecurity Stored

Key + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecObjectTemplateFaculty'
BEGIN
SELECT @Count=count(TemplateId) FROM Security_Objects_Templates_Faculties WHERE TemplateId=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Object template
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Templates_Faculties] ([TemplateId],[FacultyId] ,[CanView] ) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Object template and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Templates_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE TemplateId=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecObjectTemplateUser'
BEGIN
SELECT @Count=count(TemplateId) FROM Security_Objects_Templates_Users WHERE TemplateId=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that User and that Object template
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Objects_Templates_Users](TemplateId ,[UserId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Object template and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Objects_Templates_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE TemplateId=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END TEMPLATE SECURITY FOR ROLES AND USERS------------------------------------------

---- REPORTS SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecReportRole'
BEGIN
SELECT @Count=count(ReportName) FROM Security_Reports_Roles WHERE ReportName=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that report
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Reports_Roles] (ReportName,[RoleId] ,[CanPrint] ) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that report and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Reports_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ReportName=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecReportFaculty'
BEGIN
SELECT @Count=count(ReportName) FROM Security_Reports_Faculties WHERE ReportName=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that report
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Reports_Faculties] (ReportName,[FacultyId] ,[CanPrint] ) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that report and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Reports_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ReportName=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecReportUser'
BEGIN
SELECT @Count=count(ReportName) FROM Security_Reports_Users WHERE ReportName=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that User and that report
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Reports_Users]([ReportName] ,[UserId] ,[CanPrint]) VALUES (@SecurityKey,@SecurityId,1)

pNet_SetSecurity Stored

END
Else -- There is allready an entry for that report and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Reports_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ReportName=''' + @SecurityKey + + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- REPORTS PROCESS SECURITY FOR ROLES AND USERS------------------------------------------

---- NAVIGATION NODES SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecNodeRole'
BEGIN
SELECT @Count=count(NodeId) FROM Security_Navigation_Nodes_Roles WHERE NodeId=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Node
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Navigation_Nodes_Roles](NodeId ,[RoleId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Node and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Navigation_Nodes_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE NodeId=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecNodeFaculty'
BEGIN
SELECT @Count=count(NodeId) FROM Security_Navigation_Nodes_Faculties WHERE NodeId=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Node
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Navigation_Nodes_Faculties](NodeId ,[FacultyId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Node and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Navigation_Nodes_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE NodeId=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecNodeUser'
BEGIN
SELECT @Count=count(NodeId) FROM Security_Navigation_Nodes_Users WHERE NodeId=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that user and that Node
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Navigation_Nodes_Users](NodeId ,[UserId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Node and that user
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Navigation_Nodes_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE NodeId=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END NAVIGATION NODES SECURITY FOR ROLES AND USERS------------------------------------------

---- MODULE SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecModuleRole'
BEGIN
SELECT @Count=count(ModuleName) FROM Security_Modules_Roles WHERE ModuleName=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Modules_Roles](ModuleName ,[RoleId] ,[CanView], [ViewFilter]) VALUES (@SecurityKey,@SecurityId,1,null)
END
Else -- There is allready an entry for that Page and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Modules_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ModuleName=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecModuleFaculty'
BEGIN
SELECT

pNet_SetSecurity Stored

@Count=count(ModuleName) FROM Security_Modules_Faculties WHERE ModuleName=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Modules_Faculties](ModuleName ,[FacultyId] ,[CanView], [ViewFilter]) VALUES (@SecurityKey,@SecurityId,1,null)
END
Else -- There is allready an entry for that Page and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Modules_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ModuleName=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecModuleUser'
BEGIN
SELECT @Count=count(ModuleName) FROM Security_Modules_Users WHERE ModuleName=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that User and that Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Modules_Users](ModuleName ,[UserId] ,[CanView], [ViewFilter]) VALUES (@SecurityKey,@SecurityId,1,null)
END
Else -- There is allready an entry for that Module and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Modules_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE ModuleName=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END MODULE SECURITY FOR ROLES AND USERS------------------------------------------

---- PAGE SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecPageRole'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Roles WHERE PageName=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Page
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Roles]([PageName] ,[RoleId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Page and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecPageFaculty'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Faculties WHERE PageName=@SecurityKey and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Page
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Faculties]([PageName] ,[FacultyId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Page and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName=''' + @SecurityKey + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecPageUser'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Users WHERE PageName=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that User and that Page
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Users]([PageName] ,[UserId] ,[CanView]) VALUES (@SecurityKey,@SecurityId,1)
END
Else -- There is allready an entry for that Page and that Users
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''

pNet_SetSecurity Stored

''
exec sp_executesql @sql
END

RETURN 1
END

---- END PAGE SECURITY FOR ROLES AND USERS------------------------------------------

---- PAGE MODULE SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecPageModuleRole'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Modules_Roles WHERE PageName=@SecurityKey and ModuleName=@SecurityKey2 and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Page Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Modules_Roles]([PageName] ,[ModuleName],[RoleId] ,[CanView]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1)
END
Else -- There is allready an entry for that Page Module and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Modules_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName='''+ @SecurityKey + ''' and ModuleName=''' + @SecurityKey2 + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

IF @SecurityType='sysSecPageModuleFaculty'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Modules_Faculties WHERE PageName=@SecurityKey and ModuleName=@SecurityKey2 and FacultyId=@SecurityId

if @Count=0 -- No security for that Faculty and that Page Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Modules_Faculties]([PageName] ,[ModuleName],[FacultyId] ,[CanView]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1)
END
Else -- There is allready an entry for that Page Module and that Faculty
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Modules_Faculties] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName='''+ @SecurityKey + ''' and ModuleName=''' + @SecurityKey2 + ''' and FacultyId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END


IF @SecurityType='sysSecPageModuleUser'
BEGIN
SELECT @Count=count(PageName) FROM Security_Pages_Modules_Users WHERE PageName=@SecurityKey and ModuleName=@SecurityKey2 and UserId=@SecurityId

if @Count=0 -- No security for that user and that Page Module
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Pages_Modules_Users]([PageName] ,[ModuleName],[UserId] ,[CanView]) VALUES (@SecurityKey,@SecurityKey2,@SecurityId,1)
END
Else -- There is allready an entry for that Page Module and that User
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Pages_Modules_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE PageName='''+ @SecurityKey + ''' and ModuleName=''' + @SecurityKey2 + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END PAGE SECURITY FOR ROLES AND USERS------------------------------------------

---- MASTER TABLE SECURITY FOR ROLES AND USERS------------------------------------------

IF @SecurityType='sysSecMasterTableRole'
BEGIN
SELECT @Count=count(TableName) FROM Security_Master_Tables_Roles WHERE TableName=@SecurityKey and RoleId=@SecurityId

if @Count=0 -- No security for that Role and that Master_Table
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Master_Tables_Roles](TableName ,[RoleId] ,[CanView],[CanInsert] ,[CanUpdate],[CanDelete],[CanPrint]) VALUES (@SecurityKey,@SecurityId,1,1,1,1,1)
END
Else -- There is allready an entry for that Master_Table and that Role
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Master_Tables_Roles] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE TableName=''' + @SecurityKey + ''' and RoleId=''' + @SecurityId + ''''
exec sp_executesql @sql

pNet_SetSecurity Stored

END

RETURN 1
END


IF @SecurityType='sysSecMasterTableRole'
BEGIN
SELECT @Count=count(TableName) FROM Security_Master_Tables_Users WHERE TableName=@SecurityKey and UserId=@SecurityId

if @Count=0 -- No security for that user and that Master_Table
BEGIN -- Isert a row with basic Security set to true
INSERT INTO [Security_Master_Tables_Users](TableName ,UserId ,[CanView],[CanInsert] ,[CanUpdate],[CanDelete],[CanPrint]) VALUES (@SecurityKey,@SecurityId,1,1,1,1,1)
END
Else -- There is allready an entry for that Master_Table and that user
BEGIN -- Update coresponding field
set @sql='UPDATE [Security_Master_Tables_Users] set [' + @SecurityItem + ']= ' + convert(varchar(1),@SecurityItemValue) + ' WHERE TableName=''' + @SecurityKey + ''' and UserId=''' + @SecurityId + ''''
exec sp_executesql @sql
END

RETURN 1
END

---- END MASTER TABLE SECURITY FOR ROLES AND USERS------------------------------------------

declare @NotImplemented varchar(500)
Select @NotImplemented= 'Attention ' + @SecurityType + ' Not Implemented in pNet_SetSecurity'

RAISERROR(@NotImplemented,12,1)

END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_SetSecurityRoleObjectsReadableOnly Stored


CREATE PROCEDURE [dbo].[pNet_SetSecurityRoleObjectsReadableOnly]
(
@RoleId t_RoleId
)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pNet_SetSecurityRoleObjectsReadableOnly]
--#CREATION
-- 28/02/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Sets readonly mode for all NON System Objects for a given role
--#PARAMETERS
-- @RoleId the role with all objects in read mode
--#OBSERVATIONS
--
--#CHANGES
-- 28/02/2018- David MiralpeiX
----------------------------------------------------------------------------------
BEGIN TRY

---- OBJECT READ SECURITY FOR ROLE ------------------------------------------

BEGIN
Delete from Security_Objects_Roles where RoleId=@RoleId
INSERT INTO [Security_Objects_Roles]([ObjectName] ,[RoleId] ,[CanView],[ViewFilter] ,[CanViewCollection],[ViewFilterCollection] ,[CanInsert] ,[InsertFilter],[CanEdit],[EditFilter] ,[CanDelete],[DeleteFilter],[CanPrint])
SELECT ObjectName ,@RoleId as RoleId,1 as CanView,Null as ViewFilter,1 as CanviewCollection,Null as ViewFilterCollection,0 as CanInsert,Null as InsertFilter,0 as CanEdit,Null as EditFilter,0 as CanDelete,Null as DeleteFilter,0 as CanPrint
FROM Objects WHERE iscollection=0 and configDB=0

RETURN 1
END


END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_StartWorkflowExecution Stored

CREATE PROCEDURE [dbo].[pNet_StartWorkflowExecution]
@WorkflowId [dbo].[T_ProcessName],
@UserId [dbo].[T_UserId],
@ExecutionId BIGINT OUTPUT,
@ParentExecutionId BIGINT
AS
-- =============================================
-- #AUTOR:
-- ceesi\jjrodriguez

-- #NAME:
--- pNet_StartWorkflowExecution
-- #CREATION:
-- 05/02/2018
-- #CLASIFICATION:
-- -010-GENERAL
-- #DESCRIPTION:
-- Stores and registers a new workflow execution
-- #PARAMETERS:
-- @WorkflowId: Workflow id
-- @UserId: User executing the workflow
-- @ExecutionId: Returns the created execution Id
-- @ParentExecutionId: Parent execution Id
-- #OBSERVATIONS:
--
-- #CHANGES:
--
-- #EXAMPLE:
--
-- =============================================
BEGIN TRY

DECLARE @MasterExecutionId BIGINT
DECLARE @WorkflowNodeId NVARCHAR(50)
DECLARE @Version SMALLINT

SELECT @ExecutionId=ISNULL(MAX(ExecutionId),0)+1 FROM Workflows_Executions

IF ISNULL(@ParentExecutionId,0) <> 0 BEGIN

SELECT TOP 1 @MasterExecutionId = MasterExecutionId FROM Workflows_Executions WHERE ExecutionId = @ParentExecutionId

IF @MasterExecutionId IS NULL BEGIN
RAISERROR('ERROR. No parent execution found',12,1)
END

END ELSE BEGIN

SELECT @ParentExecutionId=@ExecutionId,@MasterExecutionId =@ExecutionId

END

SELECT @Version = Version FROM Workflows WHERE WorkflowId = @WorkflowId AND Active = 1

IF @Version IS NULL BEGIN
RAISERROR('ERROR. No active version found',12,1)
END

IF (
SELECT COUNT(1)
FROM
Workflows_Nodes WN
INNER JOIN Workflows W ON WN.WorkflowName = W.WorkflowId AND WN.Version = W.Version
WHERE
W.WorkflowId = @WorkflowId AND W.Version = @Version
AND WN.GraphId = 0 AND WN.WorkflowName = WN.ProcessName
) <> 1 BEGIN
RAISERROR('No workflow node found on workflow definition',12,1)
END

SELECT TOP 1 @WorkflowNodeId = WN.NodeId
FROM
Workflows_Nodes WN
INNER JOIN Workflows W ON WN.WorkflowName = W.WorkflowId AND WN.Version = W.Version
WHERE
W.WorkflowId = @WorkflowId AND W.Version = @Version
AND WN.GraphId = 0 AND WN.WorkflowName = WN.ProcessName



INSERT INTO Workflows_Executions(ExecutionId,ParentExecutionId,MasterExecutionId,WorkflowId,WorkflowVersion,StatusId,ResultId,Start)
SELECT @ExecutionId,@ParentExecutionId,@MasterExecutionId,@WorkflowId,@Version,0,0,GETDATE()


--Config returned to .NET executor
SELECT *
FROM
Workflows_Nodes WN
INNER JOIN Workflows W ON WN.WorkflowName = W.WorkflowId AND WN.Version = W.Version
WHERE
W.WorkflowId = @WorkflowId AND W.Version=@Version

SELECT WR.*
FROM
Workflows_Relations WR
INNER JOIN Workflows W ON WR.WorkflowName = W.WorkflowId AND WR.Version = W.Version
WHERE
W.WorkflowId = @WorkflowId AND W.Version = @Version
--Remove workflow relations as they are only parameter representation
AND WR.ChildGuid <> @WorkflowNodeId

SELECT WR.ParentGuid,WR.ChildGuid,WRP.*
FROM
Workflows_Relations_Parameters WRP
INNER JOIN Workflows_Relations WR ON WRP.RelationId = WR.RelationId
INNER JOIN Workflows W ON WR.WorkflowName = W.WorkflowId AND WR.Version = W.Version
WHERE
W.WorkflowId = @WorkflowId AND W.Version = @Version



RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_StorageLoad Stored





CREATE PROCEDURE [dbo].[pNet_StorageLoad](
@UserId T_userId ,
@InterfaceName T_InterfaceName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_StorageLoad
--#CREATION
-- 01/01/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Return User localStorage settings in Table
--#PARAMETERS
-- @UserId: User Id
-- @InterfaceName: Interface Id
--#OBSERVATIONS
--
--#CHANGES
-- 01/01/2017- David MiralpeiX
----------------------------------------------------------------------------------

BEGIN TRY



SELECT [Key],Value FROM localstorage where UserId=@UserId and InterfaceName=@InterfaceName

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_StorageSave Stored





CREATE PROCEDURE [dbo].[pNet_StorageSave](
@UserId T_userId ,
@InterfaceName T_InterfaceName,
@Properties Tbl_KeyValuePairs readonly
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_StorageSave
--#CREATION
-- 01/01/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Saves User localStorage settings in LocalStorage Table
--#PARAMETERS
-- @UserId: User Id
-- @InterfaceName: Interface Id
-- @Properties: Relation of Key pair values
--#OBSERVATIONS
--
--#CHANGES
-- 01/01/2017- David MiralpeiX
----------------------------------------------------------------------------------

BEGIN TRY


DELETE FROM localstorage WHERE UserId=@UserId and InterfaceName=@InterfaceName

INSERT INTO localStorage (UserId,InterfaceName,[Key],Value)
SELECT @UserId,@InterfaceName,[Key],Value FROM @Properties

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_TestCultureEntries Stored

CREATE PROCEDURE [dbo].[pNet_TestCultureEntries](
@CultureId nvarchar(8),
@Origin int
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_TestCultureEntries
--#CREATION
-- 17/08/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Used for testing purpouses
-- Checks to see if there are pendig translations
-- For given a culture and OriginId
--#PARAMETERS
-- @CultureId: Culture
-- @Origin: Origin Id

--#OBSERVATIONS
--
--#CHANGES
-- 17/08/2018- David Miralpeix
-- 22/10/2018- David Miralpeix añadido filtrado de nombre de plantillas
-- 27/11/2018- David Miralpeix procesos y botón de procesos
----------------------------------------------------------------------------------
BEGIN TRY



--Properties
Select Distinct @CultureId as CultureId, 'Properties' as Area, label as Value from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='Properties' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Properties' as Area, placeholder as Value from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='Properties' WHERE len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Properties' as Area, IsRequiredMessage as Value from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='Properties' WHERE len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Properties' as Area, RegExpText as Value from Objects_properties t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='Properties' WHERE len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Properties' as Area, Label as Value from Objects_Templates_Groups t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='Properties' WHERE len(t.Label) >0 and tr.Original is null and t.OriginId=@Origin

--Objects
UNION
Select Distinct @CultureId as CultureId, 'Objects' as Area,Descrip as Value from Objects t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Objects' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Objects' as Area,ParsedDescrip as Value from Objects t left join Translate tr on tr.CultureId=@CultureId and t.ParsedDescrip=tr.Original AND tr.Area ='Objects' where len(t.ParsedDescrip) >0 and tr.Original is null and t.OriginId=@Origin

--Nodes
UNION
SELECT DISTINCT @CultureId as CultureId, 'Nodes' AS Area,title as Value FROM navigation_Nodes t LEFT JOIN Translate tr ON tr.CultureId=@CultureId AND t.title=tr.Original AND tr.Area ='Nodes' where len(t.title) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Nodes' as Area,Descrip as Value from Master_Tables t left join Translate tr ON tr.CultureId=@CultureId AND t.Descrip=tr.Original AND tr.Area ='Nodes' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin
--Menus
UNION
Select Distinct @CultureId as CultureId, 'Menus' as Area,Descrip as Value from Menus t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Menus' WHERE len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin
--Offline menus
Select Distinct @CultureId as CultureId, 'Menus' as Area,Descrip as Value from Offline_Menus t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Menus' WHERE len(t.Descrip) >0 and tr.Original

pNet_TestCultureEntries Stored

is null and t.OriginId=@Origin

--Modules
UNION
Select Distinct @CultureId as CultureId, 'Modules' as Area,Title as Value from Modules t left join Translate tr on tr.CultureId=@CultureId and t.title=tr.Original AND tr.Area ='Modules' where len(t.title) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'Modules' as Area,Descrip as Value from Modules t left join Translate tr on tr.CultureId=@CultureId and t.Descrip=tr.Original AND tr.Area ='Modules' where len(t.Descrip) >0 and tr.Original is null and t.OriginId=@Origin

--Buttons
UNION
select Distinct @CultureId as CultureId, 'Buttons' as Area,t.[Text] as Value from Toolbars_Buttons t left join Translate tr on tr.CultureId=@CultureId and t.[Text]=tr.Original AND tr.Area ='Buttons' WHERE len(t.[Text]) >0 and tr.Original is null and t.OriginId=@Origin
UNION
select Distinct @CultureId as CultureId, 'Buttons' as Area,Tooltip as Value from Toolbars_Buttons t left join Translate tr on tr.CultureId=@CultureId and t.Tooltip=tr.Original AND tr.Area ='Buttons' where len(t.Tooltip) >0 and tr.Original is null and t.OriginId=@Origin

--Reports
UNION
select Distinct @CultureId as CultureId, 'Reports' as Area,t.ReportDescrip as Value from Reports t left join Translate tr on tr.CultureId=@CultureId and t.[ReportDescrip]=tr.Original AND tr.Area ='Reports' where len(t.[ReportDescrip]) >0 and tr.Original is null and t.OriginId=@Origin

--Process
UNION
select Distinct @CultureId as CultureId, 'Process' as Area,t.ConfirmText as Value from Processes t left join Translate tr on tr.CultureId=@CultureId and t.ConfirmText=tr.Original AND tr.Area ='Process' where len(t.ConfirmText) >0 and tr.Original is null and t.OriginId=@Origin
UNION
select Distinct @CultureId as CultureId, 'Process' as Area,t.ProcessDescrip as Value from Processes t left join Translate tr on tr.CultureId=@CultureId and t.ProcessDescrip=tr.Original AND tr.Area ='Process' where len(t.ProcessDescrip) >0 and tr.Original is null and t.OriginId=@Origin
UNION
select Distinct @CultureId as CultureId, 'Process' as Area,t.RunButtonText as Value from Processes t left join Translate tr on tr.CultureId=@CultureId and t.RunButtonText=tr.Original AND tr.Area ='Process' where len(t.RunButtonText) >0 and tr.Original is null and t.OriginId=@Origin


--Process Params
UNION
Select Distinct @CultureId as CultureId, 'ProcessParams' as Area, label as Value from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='ProcessParams' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ProcessParams' as Area, placeholder as value from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='ProcessParams' where len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ProcessParams' as Area, IsRequiredMessage as Value from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='ProcessParams' WHERE len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ProcessParams' as Area, RegExpText as Value from Processes_Params t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='ProcessParams' WHERE len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin

-- Report Params
UNION
Select Distinct @CultureId as CultureId, 'ReportsParams' as Area, label as Value from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.Label=tr.Original AND tr.Area ='ReportParams' where len(t.label) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ReportsParams' a

pNet_TestCultureEntries Stored

s Area, placeholder as Value from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.placeholder=tr.Original AND tr.Area ='ReportParams' where len(t.placeholder) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ReportsParams' as Area, IsRequiredMessage as Value from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.IsRequiredMessage=tr.Original AND tr.Area ='ReportParams' WHERE len(t.IsRequiredMessage) >0 and tr.Original is null and t.OriginId=@Origin
UNION
Select Distinct @CultureId as CultureId, 'ReportsParams' as Area, RegExpText as Value from Reports_Params t left join Translate tr on tr.CultureId=@CultureId and t.RegExpText=tr.Original AND tr.Area ='ReportParams' WHERE len(t.RegExpText) >0 and tr.Original is null and t.OriginId=@Origin

-- Filter Names
UNION
Select Distinct @CultureId as CultureId, 'FilterNames' as Area, Name as Value from Objects_Search t left join Translate tr on tr.CultureId=@CultureId and t.Name=tr.Original AND tr.Area ='FilterNames' where len(t.Name) >0 and tr.Original is null and t.OriginId=@Origin

UNION

Select Distinct @CultureId as CultureId, 'FilterNames' as Area, Title as Value from Objects_Presets t left join Translate tr on tr.CultureId=@CultureId and t.Title=tr.Original AND tr.Area ='FilterNames' where len(t.Title) >0 and tr.Original is null and t.OriginId=@Origin
UNION

-- Template Names
SELECT DISTINCT @CultureId AS CultureId, 'TemplateNames' AS Area, Descrip AS Value FROM Objects_Templates t LEFT JOIN Translate tr ON tr.CultureId=@CultureId AND t.Descrip=tr.Original AND tr.Area ='TemplateNames' WHERE LEN(t.Descrip) >0 AND tr.Original IS NULL AND t.OriginId=@Origin

UNION

-- Templates includes offline pages
select * FROM fNet_TestCultureEntries_Templates (@Origin,@cultureId)



UNION
--Exceptions
Select Distinct @CultureId, 'Exceptions' as Area, MSG as value from Exceptions t left join Translate tr on tr.CultureId=@CultureId and t.MSG=tr.Original AND tr.Area ='Exceptions' where len(t.MSG) >0 and tr.Original is null and t.OriginId=@Origin

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_ToolbarClone Stored

CREATE PROCEDURE [dbo].[pNet_ToolbarClone](
@ToolbarName T_ToolbarName,
@NewToolbarName T_ToolbarName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_ToolbarClone
--#CREATION
-- 01/11/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Clones existing toolbar with new name
--#PARAMETERS
-- @ToolbarName T_ToolbarName,
-- @NewToolbarName T_ToolbarName
--#OBSERVATIONS
--
--#CHANGES
-- 01/11/2017- David MiralpeiX
----------------------------------------------------------------------------------

BEGIN TRY

begin Tran
INSERT INTO [dbo].[ToolBars] ([ToolbarName],[Descrip] )
SELECT @NewToolbarName,[Descrip] FROM Toolbars where ToolbarName=@ToolbarName

INSERT INTO [dbo].[ToolBars_Buttons]
([ButtonId],[ToolbarName],[ParentButtonId],[Order],[TypeId],[PositionId],[Text] ,[Tooltip],[IconName],[HideText] ,[CssClass] ,[SQlSentence] ,[ProcessName] ,[TargetId] ,[ReportName] ,[HelpId] ,[Disabled])
SELECT NEWID() ,@NewToolbarName ,[ParentButtonId] ,[Order] ,[TypeId] ,[PositionId],[Text] ,[Tooltip],[IconName],[HideText],[CssClass] ,[SQlSentence] ,[ProcessName] ,[TargetId] ,[ReportName] ,[HelpId] ,[Disabled] from ToolBars_Buttons where ToolbarName=@ToolbarName

select 'flexygo.nav.openPage(''edit'',''sysToolbar'',''(ToolbarName=\''' + @NewToolbarName+'\'')'',null,''popup'',false,' + NCHAR(36) + '(this))' as Javascript
commit
RETURN 1

END TRY

BEGIN CATCH

Rollback
DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_UpdateDatabase_ApplyUserChanges Stored

CREATE PROCEDURE [dbo].[pNet_UpdateDatabase_ApplyUserChanges]
@Version NVARCHAR(255) = NULL,
@OnlyUser BIT = 0
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_UpdateDatabase_ApplyUserChanges
--#CREATION
-- 12/09/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Applies the differences found in update process
--#PARAMETERS
-- @Version: Version being installed
-- @OnlyUser Only "user values"
--#OBSERVATIONS
--
--#CHANGES
-- 12/09/2017-JJR-First version
----------------------------------------------------------------------------------
BEGIN TRY


DECLARE @SQL NVARCHAR(MAX)

BEGIN TRAN

IF EXISTS(
SELECT 1
FROM
Versions_Differences VD
INNER JOIN sys.columns SC on OBJECT_NAME(SC.object_id) = VD.TableName AND SC.name = VD.FieldName
INNER JOIN sys.types ST ON sc.system_type_id = ST.system_type_id AND st.system_type_id = st.user_type_id
WHERE
VD.VersionNumber = @Version
AND (
(@OnlyUser = 0)
OR
(@OnlyUser = 1 AND VD.Action = 1)
)
AND VD.Revised = 1 --Revised changes
AND VD.Applied = 0 --Non-applied changes
) BEGIN

SELECT @SQL = N''

SELECT
@SQL = @SQL +
N'BEGIN TRAN;' +
N'ALTER TABLE ' + QUOTENAME(VD.TableName) + + N' DISABLE TRIGGER ALL;' +
N'UPDATE ' + QUOTENAME(VD.TableName) +
N' SET ' + QUOTENAME(VD.FieldName) + N' = ' +
CASE WHEN
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
IS NULL THEN
N'NULL'
ELSE
CASE WHEN ST.NAME IN ('char','varchar') THEN
NCHAR(39)+REPLACE(
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
,NCHAR(39),NCHAR(39)+NCHAR(39))+NCHAR(39)
ELSE CASE WHEN ST.NAME IN ('nchar','nvarchar','uniqueidentifier','xml') THEN
+N'N' + NCHAR(39) + REPLACE(
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
,NCHAR(39),NCHAR(39)+NCHAR(39))+NCHAR(39)
ELSE CASE WHEN ST.NAME IN ('bit','tinyint','smallint','int','nvarchar','bigint') THEN
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
ELSE CASE WHEN ST.NAME IN ('real','money','float','decimal','numeric','smallmoney') THEN
REPLACE(
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
,N',',N'.')
--date,time,datetime2,datetimeoffset,smalldatetime,datetime,timestamp
ELSE --image,text,sql_variant,ntext,varbinary,binary
NCHAR(39)+
CASE [Action]
WHEN 0 THEN CurrentValue
WHEN 1 THEN UserValue
WHEN 2 THEN ManualValue
END
+NCHAR(39)
END END END END
END +
N' WHERE ' + VD.ROWKEY + ';' +
N'ALTER TABLE ' + QUOTENAME(VD.TableName) + + N' ENABLE TRIGGER ALL;' +
N'UPDATE Versions_Differences SET Applied = 1 WHERE DifferenceId = ' + QUOTENAME(VD.DifferenceId,'''') + ';' +
N'COMMIT TRAN;' +
NCHAR(13)+NCHAR(10)
FROM
Versions_Differences VD
INNER JOIN sys.columns SC on OBJECT_NAME(SC.object_id) = VD.TableName AND SC.name = VD.FieldName
INNER JOIN sys.types ST ON sc.system_type_id = ST.system_type_id AND st.system_type_id = st.user_type_id
WHERE
VD.VersionNumber = @Version
AND (
(@OnlyUser = 0)
OR
(@OnlyUser = 1 AND VD.Action = 1)
)
AND VD.Revised = 1 --Revised changes
AND VD.Applied = 0 --Non-applied changes

IF @SQL IS NULL RAISERROR('Error generating update script for user changes.',16,1)

UPDATE Versions SET UpdateLog = @SQL WHERE VersionNumber=@Version

EXEC sp_executesql @SQL

END

COMMIT TRAN

RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR

pNet_UpdateDatabase_ApplyUserChanges Stored

(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_UpdateDatabase_FindChanges Stored

CREATE PROCEDURE [dbo].[pNet_UpdateDatabase_FindChanges]
@Database NVARCHAR(255) = NULL,
@Version NVARCHAR(255) = NULL
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_UpdateDatabase_FindChanges
--#CREATION
-- 12/09/2017
--#CLASIFICATION
-- System
--#DESCRIPTION
-- Compares the current data into the database with the copy of the original version, to find differences
--#PARAMETERS
-- @DatabaseName: If parameter value is not empty and not equals current database name, the procedure compares data between parametrized and current database

-- @Version: Version being installed
--#OBSERVATIONS
--
--#CHANGES
-- 12/09/2017-JJR-First version
-- 26/09/2017-JJR-Only compare tables/fields existing in both databases
-- 26/09/2017-JJR-Collate queries between databases to avoid collation errors
-- 27/09/2017-JJR-Compare only rows with OriginId<2. Clarify queries
-- 27/10/2017-JJR-Allways convert the RowKey to VARCHAR to allow queries between different data types in old versions
----------------------------------------------------------------------------------
BEGIN TRY

DECLARE @TableName NVARCHAR(1000)
DECLARE @CopyTable NVARCHAR(1000)
DECLARE @Fields NVARCHAR(MAX)
DECLARE @RowKey NVARCHAR(MAX)
DECLARE @TemplateSQL NVARCHAR(MAX)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @DBOLD NVARCHAR(1000)
DECLARE @DBNEW NVARCHAR(1000)
DECLARE @Error NVARCHAR(MAX)

SET @TemplateSQL =N'

CREATE TABLE #Table1(RowKey VARCHAR(1000),Field VARCHAR(256),OriginId SMALLINT,Value NVARCHAR(MAX))
CREATE INDEX #T1 ON #Table1(RowKey,Field)
CREATE TABLE #Table2(RowKey VARCHAR(1000),Field VARCHAR(256),OriginId SMALLINT,Value NVARCHAR(MAX))
CREATE INDEX #T2 ON #Table2(RowKey,Field)
CREATE TABLE #Table3(RowKey VARCHAR(1000),Field VARCHAR(256),OriginId SMALLINT,Value NVARCHAR(MAX))
CREATE INDEX #T3 ON #Table3(RowKey,Field)

DECLARE @Data1 xml, @Data2 xml, @Data3 xml

SELECT @Data1 = ( --Rows added/modified into current table
SELECT * FROM (
SELECT {{@rowkey@}}, {{@fields@}} FROM {{@dbold@}}.dbo.{{@table@}} WHERE OriginId IN (0,1)
EXCEPT
SELECT {{@rowkey@}}, {{@fields@}} FROM {{@dbold@}}.dbo.{{@copy@}} WHERE OriginId IN (0,1)
) AS A
FOR XML RAW(''Data'')
)

SELECT @Data2 = ( --Rows modififed/deleted from original table
SELECT * FROM (
SELECT {{@rowkey@}},{{@fields@}} FROM {{@dbold@}}.dbo.{{@copy@}} WHERE OriginId IN (0,1)
EXCEPT
SELECT {{@rowkey@}},{{@fields@}} FROM {{@dbold@}}.dbo.{{@table@}} WHERE OriginId IN (0,1)
) AS A
FOR XML RAW(''Data'')
)

INSERT INTO #Table1(RowKey,OriginId,Field,Value)
SELECT
T.C.value(''../@RowKey'', ''nvarchar(max)'') as RowKey,
T.C.value(''../@OriginId'', ''smallint'') as OriginId,
T.C.value(''local-name(.)'', ''nvarchar(max)'') as Field,
T.C.value(''.'', ''nvarchar(max)'') as Value
FROM
@Data1.nodes(''Data/@*'') as T(C)

INSERT INTO #Table2(RowKey,OriginId,Field,Value)
SELECT
T.C.value(''../@RowKey'', ''nvarchar(max)'') as RowKey,
T.C.value(''../@OriginId'', ''smallint'') as OriginId,
T.C.value(''local-name(.)'', ''nvarchar(max)'') as Field,
T.C.value(''.'', ''nvarchar(max)'') as Value
FROM
@Data2.nodes(''Data/@*'') as T(C)

--Delete added/deleted rows
DELETE T1 FROM #Table1 T1 LEFT JOIN #Table2 T2 ON T1.RowKey = T2.RowKey WHERE T2.RowKey IS NULL
DELETE T2 FROM #Table2 T2 LEFT JOIN #Table1 T1 ON T2.RowKey = T1.RowKey WHERE T1.RowKey IS NULL

--Insert missing fields for NULL vlaues
INSERT INTO #Table1(RowKey,OriginId,Field,Value)
SELECT T2.RowKey,T11.OriginId,T2.Field,NULL
FROM #Table2 T2
LEFT JOIN #Table1 T1 ON T2.RowKey = T1.RowKey AND T2.Field = T1.Field
OUTER APPLY (
SELECT TOP 1 OriginId FROM #Table1 WHERE RowKey = T1.RowKey
) T11
WHERE
T1.RowKey IS NULL

INSERT INTO #Table2(RowKey,OriginId,Fie

pNet_UpdateDatabase_FindChanges Stored

ld,Value)
SELECT T1.RowKey,T22.OriginId,T1.Field,NULL
FROM #Table1 T1
LEFT JOIN #Table2 T2 ON T1.RowKey = T2.RowKey AND T1.Field = T2.Field
OUTER APPLY (
SELECT TOP 1 OriginId FROM #Table2 WHERE RowKey = T2.RowKey
) T22
WHERE
T2.RowKey IS NULL


IF EXISTS(
SELECT 1
FROM #Table1 T1
) BEGIN

SELECT @Data3 = ( --All data in new database
SELECT * FROM (
SELECT {{@rowkey@}},{{@fields@}} FROM {{@dbnew@}}.dbo.{{@table@}} WHERE OriginId IN (0,1)

) AS A
WHERE
EXISTS ( --Filter only by modified rows
SELECT RowKey FROM #Table1 WHERE RowKey = A.RowKey COLLATE DATABASE_DEFAULT
)
FOR XML RAW(''Data'')

)

INSERT INTO #Table3(RowKey,OriginId,Field,Value)
SELECT
T.C.value(''../@RowKey'', ''nvarchar(max)'') as RowKey,
T.C.value(''../@OriginId'', ''smallint'') as OriginId,
T.C.value(''local-name(.)'', ''nvarchar(max)'') as Field,
T.C.value(''.'', ''nvarchar(max)'') as Value
FROM
@Data3.nodes(''Data/@*'') as T(C)

--Delete unneded fields
DELETE T3 FROM #Table3 T3 LEFT JOIN #Table1 T1 ON T3.RowKey = T1.RowKey AND T3.Field = T1.Field WHERE T1.RowKey IS NULL

--Insert missing fields for NULL vlaues
INSERT INTO #Table3(RowKey,OriginId,Field,Value)
SELECT T1.RowKey,T33.OriginId,T1.Field,NULL
FROM #Table1 T1
LEFT JOIN #Table3 T3 ON T1.RowKey = T3.RowKey AND T1.Field = T3.Field
OUTER APPLY (
SELECT TOP 1 OriginId FROM #Table3 WHERE RowKey = T1.RowKey
) T33
WHERE
T3.RowKey IS NULL

--select ''t1'',* from #table1 --T1 Holds User Values (Current values in database before update)
--select ''t2'',* from #table2 --T2 Holds Old Version Values
--select ''t3'',* from #table3 --T3 Holds New Version Values

INSERT INTO Versions_Differences(VersionNumber,TableName,FieldName,RowKey,SystemValue,UserValue,CurrentValue,RowOriginId,Action,Revised,Applied)
SELECT
''{{@version@}}'',''{{@table@}}'', T1.Field, T1.RowKey, T2.Value, T1.Value, T3.Value,T3.OriginId,
--Action
CASE WHEN (T2.Value IS NULL AND T3.Value IS NULL) OR (T2.Value IS NOT NULL AND T3.Value IS NOT NULL AND T2.Value = T3.Value) THEN
1 --If both versions values are identical, always restore user value
ELSE
CASE WHEN (T1.Value IS NULL AND T3.Value IS NULL) OR (T1.Value IS NOT NULL AND T3.Value IS NOT NULL AND T1.Value = T3.Value) THEN
0 --User value is the same as the new version value, apply version value
ELSE
FDA.ActionId -- If value versions are different, check configuration for defined action
END
END,
0,
0

FROM
#Table1 T1
INNER JOIN #Table2 T2 ON T2.RowKey = T1.RowKey and T2.Field = T1.Field
INNER JOIN #Table3 T3 ON T1.RowKey = T3.RowKey AND T1.Field = T3.Field --RUBÉN: LEFT cambiado por inner para que no de RowOriginId a Null al refactorizar campos.
CROSS APPLY dbo.fNet_GetDefaultAction(T3.OriginId,''{{@table@}}'',T1.Field) FDA
WHERE
NOT
( --Only values modified by user
(T1.Value IS NULL AND T2.Value IS NULL)
OR
(T1.Value IS NOT NULL AND T2.Value IS NOT NULL AND T1.Value = T2.Value)
)
AND NOT T3.OriginId IS NULL --RUBÉN: Filtro añadido para que si eliminamos una propiedad que ha sido personalizada por el usuario no falle la actualización.

END

DROP TABLE #Table1
DROP TABLE #Table2
DROP TABLE #Table3
'

DELETE FROM Versions_Differences WHERE VersionNumber = @Version


IF ISNULL(@Database,'')='' OR ISNULL(@Database,'')=DB_NAME() BEGIN

SELECT @DbOld = DB_NAME(), @DbNew = DB_NAME()

END ELSE BEGIN

SELECT @DbOld = @Database, @DbNew = DB_NAME()

END


--26/09/2017-Only compare tables/fields existing in both databases
CREATE TABLE #OldTables(TableName NVARCHAR(256))
CREATE TABLE #OldFields(TableName NVARCHAR(256),FieldName NVARCHAR(256))

SELECT @SQL = N'

INSERT INTO #

pNet_UpdateDatabase_FindChanges Stored

OldTables(TableName)
SELECT
ST.Table_Name
FROM
Configuration_Tables CT
INNER JOIN INFORMATION_SCHEMA.TABLES ST ON CT.TableName COLLATE DATABASE_DEFAULT = ST.Table_Name COLLATE DATABASE_DEFAULT
INNER JOIN ' + @DBOld + N'.INFORMATION_SCHEMA.TABLES OST ON ST.Table_Name COLLATE DATABASE_DEFAULT = OST.Table_Name COLLATE DATABASE_DEFAULT AND ST.Table_Type COLLATE DATABASE_DEFAULT = OST.Table_Type COLLATE DATABASE_DEFAULT
INNER JOIN ' + @DBOld + N'.INFORMATION_SCHEMA.TABLES ZOSC ON ST.Table_Type COLLATE DATABASE_DEFAULT = ZOSC.Table_Type COLLATE DATABASE_DEFAULT AND ''zVersion_'' + ST.Table_Name COLLATE DATABASE_DEFAULT = ZOSC.Table_Name COLLATE DATABASE_DEFAULT
WHERE
CT.CompareMode = 1

INSERT INTO #OldFields(TableName,FieldName)
SELECT
SC.Table_Name,SC.Column_Name
FROM
#OldTables CT
INNER JOIN INFORMATION_SCHEMA.COLUMNS SC ON CT.TableName COLLATE DATABASE_DEFAULT = SC.Table_Name COLLATE DATABASE_DEFAULT
INNER JOIN ' + @DBOld + N'.INFORMATION_SCHEMA.COLUMNS OSC ON SC.Table_Name COLLATE DATABASE_DEFAULT = OSC.Table_Name COLLATE DATABASE_DEFAULT AND SC.Column_Name COLLATE DATABASE_DEFAULT = OSC.Column_Name COLLATE DATABASE_DEFAULT

'

EXEC sp_executesql @SQL


DECLARE curTables CURSOR FOR

SELECT
CT.TableName
FROM
Configuration_Tables CT
INNER JOIN #OldTables OT ON CT.TableName COLLATE DATABASE_DEFAULT = OT.TableName COLLATE DATABASE_DEFAULT
WHERE
CT.CompareMode = 1
ORDER BY
CT.TableName


OPEN curTables
FETCH NEXT FROM curTables INTO @TableName
WHILE @@FETCH_STATUS <> -1 BEGIN

PRINT 'Checking '+@TableName+ ' diferences...'

SELECT @Fields=N'',@RowKey=N'',@CopyTable = N'zVersion_' + @TableName

SELECT
@RowKey = @RowKey + QUOTENAME(sc.name) + N'=N'''''' + ' +

CASE WHEN STY.name IN ('varchar','nvarchar','uniqueidentifier','tinyint','smallint','int','bit') THEN
N'CONVERT(NVARCHAR(MAX),Replace(' + SC.NAME + N',NCHAR(39),NCHAR(39)+NCHAR(39)))'
ELSE
SC.NAME
END
+
N' + '''''' AND '
FROM
sys.tables ST
INNER JOIN sys.columns SC ON st.object_id = SC.object_id
INNER JOIN sys.indexes SI on ST.object_id = si.object_id AND SI.is_primary_key = 1
INNER JOIN sys.index_columns SIC on si.object_id = SIC.object_id AND si.index_id = SIC.index_id and sc.column_id= sic.column_id
INNER JOIN sys.types STY ON SC.system_type_id = STY.system_type_id AND STY.system_type_id = STY.user_type_id

WHERE
st.name=@TableName
ORDER BY
sic.key_ordinal






SELECT
@Fields = @Fields +
CASE WHEN STY.name IN ('uniqueidentifier','tinyint','smallint','int','bit') THEN
N'CONVERT(NVARCHAR(MAX),' + QUOTENAME(SC.NAME) + N') AS ' + QUOTENAME(SC.NAME) + N','
ELSE
QUOTENAME(SC.NAME) + N','
END
FROM
sys.tables ST
INNER JOIN sys.columns SC ON st.object_id = SC.object_id
INNER JOIN sys.types STY ON SC.system_type_id = STY.system_type_id AND STY.system_type_id = STY.user_type_id
INNER JOIN #OldFields OFI ON st.name COLLATE DATABASE_DEFAULT = OFI.TableName COLLATE DATABASE_DEFAULT AND SC.name COLLATE DATABASE_DEFAULT = OFI.FieldName COLLATE DATABASE_DEFAULT

WHERE
st.name=@TableName
ORDER BY
SC.COLUMN_ID


SELECT @RowKey= + N'''' + LEFT(@RowKey,LEN(@RowKey)-5)+N''''' AS RowKey'

SELECT @Fields=LEFT(@Fields,LEN(@Fields)-1)

SELECT @sql=REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@TemplateSql,N'{{@table@}}',@TableName),N'{{@copy@}}',@CopyTable),N'{{@rowkey@}}',@RowKey),N'{{@version@}}',@Version),N'{{@fields@}}',@Fields),N'{{@dbold@}}',@DbOld),N'{{@dbnew@}}',@Dbnew)


BEGIN TRY

EXEC sp_executesql @SQL

END TRY
BEGIN CATCH
SELECT @Error = 'Table:' + @TableName +'RowKey: ' + @RowKey + ' ' + ERROR_MESSAGE()
--DEBUG
--SELECT @SQL
--FOR XML PATH(''),TYPE
RAISERROR(@Error,12,1)
END CATCH

FETCH NEXT FROM curTables INTO @TableNam

pNet_UpdateDatabase_FindChanges Stored

e
END

CLOSE curTables
DEALLOCATE curTables


--Mark as revised all changes that user does not have to manually validate
-- Only mark as not revised changes where exists conflicts (Value was changed by user (UserValue <> OldValue) and value was changed between versions (OldValue <> NewValue) and current user value not equals new version value ( UserValue <> NewValue))
-- And in case of conflict, if there is a configured default action for user value
UPDATE Versions_Differences
SET Revised =
CASE WHEN (
( --UserValue <> SystemValue
(UserValue IS NULL AND SystemValue IS NOT NULL)
OR (UserValue IS NOT NULL AND SystemValue IS NULL)
OR (UserValue IS NOT NULL AND SystemValue IS NOT NULL AND UserValue <> SystemValue)
)
AND ( --SystemValue <> CurrentValue
(SystemValue IS NULL AND CurrentValue IS NOT NULL)
OR (SystemValue IS NOT NULL AND CurrentValue IS NULL)
OR (SystemValue IS NOT NULL AND CurrentValue IS NOT NULL AND SystemValue <> CurrentValue)
)
AND
( --UserValue <> CurrentValue
(UserValue IS NULL AND CurrentValue IS NOT NULL)
OR (UserValue IS NOT NULL AND CurrentValue IS NULL)
OR (UserValue IS NOT NULL AND CurrentValue IS NOT NULL AND UserValue <> CurrentValue)
)
)
THEN
CASE WHEN [Action] = 1 THEN
1
ELSE
0
END
ELSE
1
END
WHERE
VersionNumber = @Version

--Mark as applied all changes revised and with action = 0 (changes are allready applied by post-deployment script)
UPDATE Versions_Differences
SET Applied = 1
WHERE
VersionNumber = @Version
AND [Action] = 0
AND Revised = 1


RETURN -1

END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(), @@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_UpdateObject Stored


CREATE PROCEDURE [dbo].[pNet_UpdateObject](
@ObjectName T_ObjectName,
@CollectionName T_ObjectName,
@ObjectDescrip nvarchar(255),
@CollectionDescrip nvarchar(255),
@ObjectParsedDescrip nvarchar(255),
@ObjectIconName t_IconName,
@CollectionIconName T_IconName
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_UpdateObject
--#CREATION
-- 12/06/2017
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Update entries in objects Table using stored procedure parameter info
--#PARAMETERS
-- @ObjectName: Object Name
-- @CollectionName: collection name
-- @ObjectDescrip: Object description
-- @CollectionDescrip: collection Description
-- @ObjectParsedDescrip: Object Parseable description
-- @ObjectIconName: Object Icon Name
-- @CollectionIconName: Collection Icon Name

--#OBSERVATIONS
-- Updates EntityObject and Entitycollection entries in object Table
--#CHANGES
-- 12/06/2017 - Rubén Pardo
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN Transaction
--Object
Update Objects set Descrip=@ObjectDescrip, ParsedDescrip=@ObjectParsedDescrip, IconName=@ObjectIconName where ObjectName=@ObjectName

--Collection
Update Objects set Descrip=@CollectionDescrip, ParsedDescrip=@CollectionDescrip, IconName=@CollectionIconName where ObjectName=@CollectionName

COMMIT transaction

RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_UpdateScriptsJobs Stored


CREATE PROCEDURE [dbo].[pNet_UpdateScriptsJobs](
@StartDate SMALLDATETIME,
@EndDate SMALLDATETIME,
@ScriptId nvarchar(100),
@ErrorMessage NVARCHAR(MAX)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_UpdateScriptsJobs
--#CREATION
-- 28/05/2019
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Update results of database scripts jobs
--#PARAMETERS
-- @ScriptId: Database script job ID
-- @ErrorMessage: Error description
-- @StartDate: Object description
-- @EndDate: collection Description

--#OBSERVATIONS
-- Updates only scripts states P (Pending) or E (Error)
-- If ScriptId parameter <> -1 Updates only the script related explain error and set state on error
--#CHANGES
-- 28/05/2019 - Daniel Lutz
----------------------------------------------------------------------------------
BEGIN TRY

BEGIN TRANSACTION

IF @ScriptId = '-1' BEGIN
--All right
UPDATE Scripts_Jobs
SET State='S', ErrorMessage=NULL , StartDate = @StartDate, EndDate = @EndDate
WHERE State='P' OR State= 'E'
END ELSE BEGIN
--an error
UPDATE Scripts_Jobs
SET State='P', ErrorMessage=NULL , StartDate = null, EndDate = null
WHERE State='P' OR State= 'E'

UPDATE Scripts_Jobs
SET State='E', ErrorMessage=@ErrorMessage, StartDate = @StartDate, EndDate = @EndDate
WHERE ScriptId=@ScriptId
END
COMMIT TRANSACTION
RETURN 1
END TRY

BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pNet_UserLoginLog Stored

CREATE PROCEDURE [dbo].[pNet_UserLoginLog] (
@UserName AS NVARCHAR(512),
@IP NVARCHAR(100),
@Browser NVARCHAR(512),
@Culture nvarchar(200),
@Success BIT
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pNet_UserLoginLog
--#CREATION
-- 26/10/2018
--#CLASIFICATION
-- Configuration
--#DESCRIPTION
-- Add user login attempt to sysUserLog
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

declare @UserId as T_UserId

SELECT @UserId=Id FROM AspnetUsers WHERE Username=@UserName or Email=@UserName

IF NOT @UserId IS NULL BEGIN

INSERT INTO AspNetUsers_Log ([Date],UserId,[IP],Browser,Culture,Success)
VALUES (GETDATE(),@UserId,@IP,@Browser,@Culture,@Success)

END


RETURN 1
END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pOffline_CreateSync Stored

CREATE PROCEDURE [dbo].[pOffline_CreateSync](
@SyncId [nvarchar](100),
@AppName [nvarchar](50),
@UserName [nvarchar](150)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pOffline_CreateSync
--#CREATION
-- 22/02/2021 - Rubén Pardo
--#CLASIFICATION
-- Flexygo/Offline processes
--#DESCRIPTION
-- Create new Sync
--#PARAMETERS
-- @SyncId: Sync Unique Identificator
-- @AppName: App name
-- @UserName: User name
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

if NOT EXISTS(select 1 from Offline_Sync where syncId=@SyncId) BEGIN
Insert into Offline_Sync (SyncId,AppName,UserName) values (@SyncId,@AppName,@UserName)
END


RETURN 1

END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pOffline_GetAppConfig Stored

----------------------------------------------------------------------------------
--#NAME
-- pOffline_GetAppConfig
--#CREATION
-- 05/12/2019
--#CLASIFICATION
-- Offline Apps
--#DESCRIPTION
-- Get APP Data Configuration.
--#PARAMETERS
--
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[pOffline_GetAppConfig]
@AppName NVARCHAR(100)
AS

--Get Objects Configuration
SELECT OO.ObjectName, O.Descrip, O.ParsedDescrip, OO.BufferSize, OO.UpdateRelatedPrimaryKeys, OO.SyncImmediately, OO.SendData, OO.GetData, ISNULL(OO.TableName,O.TableName) as TableName
FROM Offline_Objects OO inner join Objects O ON OO.ObjectName=O.ObjectName WHERE AppName=@AppName ORDER BY OO.ObjectName

--Get Objects Views Configuration
SELECT V.ObjectName,V.ViewName as TableName, V.PrimaryKeys, V.IndexFields, V.IsDefault
FROM Objects_Views V
INNER JOIN Offline_Objects OO ON V.ObjectName=OO.ObjectName
Where v.Offline=1 AND v.ACTIVE=1 AND OO.AppName=@AppName


--Get Templates Configuration
SELECT T.ObjectName,
T.PageName,
T.TypeId,
T.Title,
T.Body,
T.Header,
T.Footer,
T.Empty,
T.IsDefault,
T.SQLSentence,
T.SQLAdditionalWhere,
T.SQLOrderBy,
T.SQLSearchFilter,
T.ShowSearchBar,
T.JSAfterLoad
FROM Offline_Pages T
Where T.AppName=@AppName

--Get Menu Configuration
select
MenuId, ParentMenuId, Title, Descrip, TypeId, [Url], ProcessName, PageTypeId, PageName, ObjectName, ObjectWhere,
I.CSSClass as IconClass
from Offline_Menus
inner join Icons I on Offline_Menus.IconName=I.IconName
where [Enabled]=1 and AppName=@AppName
order by [Order] asc

--Get related object configuration
SELECT rel.ObjectName,Childs.ObjectChildName,rel.ObjectRelation
FROM Offline_Objects O
INNER JOIN Objects_Objects Rel ON o.ObjectName=rel.ObjectName
INNER JOIN Objects Childs ON Rel.ChildCollection=Childs.ObjectName

--Get scripts configuration
SELECT [Name],JSScript,[Order],LastChange
FROM Offline_Scripts
WHERE [Enabled]=1 AND AppName=@AppName
ORDER BY [Order]

--Get scripts configuration
SELECT [Name],CSSCode,[Order],LastChange
FROM Offline_Styles
WHERE [Enabled]=1 AND AppName=@AppName
ORDER BY [Order]

--Get document configuration
SELECT C.ObjectName,C.ObjectPK,C.ERPObjectName,C.TypeId,C.DefaultCategoryId,C.CategoryFilter,C.OfflineFilter
FROM Offline_Objects O
INNER JOIN Documents_Objects_Config C ON o.ObjectName=C.ObjectName

--Get image configuration
select C.ObjectName,C.KeyProperty,C.ERPObjectName,C.TypeId,C.DefaultCategoryId,C.OfflineFilter
from Offline_Objects O
inner join [Objects_Images_Settings] C on o.ObjectName=C.ObjectName

--Get files configuration
select [FileName], [FileDate]
from Offline_Files where AppName=@AppName and [enabled]=1

--Get Pages Groups
select PageName,GroupField,[Order],OrderType,Header,Footer
FROM Offline_Pages_Groups Where AppName=@AppName
order by AppName,PageName,[Order]

RETURN 1

pOffline_MessageRead Stored

CREATE PROCEDURE [dbo].[pOffline_MessageRead](
@UserId [dbo].[T_UserId],
@NoticeId NVARCHAR(250)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pOffline_MessageRead
--#CREATION
-- 07/09/2020 - Rubén Pardo
--#CLASIFICATION
-- Flexygo/Offline processes
--#DESCRIPTION
-- Set message as readed
--#PARAMETERS
-- @UserId: User Identificator
-- @NoticeId: Message
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

UPDATE Notices_Users SET IsRead=1 where NoticeId=@NoticeId AND UserId=@UserId

RETURN 1

END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pOffline_RegisterDevice Stored

CREATE PROCEDURE [dbo].[pOffline_RegisterDevice](
@UserId [dbo].[T_UserId],
@DeviceToken NVARCHAR(250),
@Platform NVARCHAR (50),
@OldToken NVARCHAR(250)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pOffline_RegisterDevice
--#CREATION
-- 04/09/2020 - Rubén Pardo
--#CLASIFICATION
-- Flexygo/Offline processes
--#DESCRIPTION
-- Register device to allow push notifications
--#PARAMETERS
-- @UserId: User Id
-- @DeviceToken: Device Token Identifier
-- @Platform: ios/android/web
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

delete AspNetUsers_Devices WHERE DeviceToken=@OldToken

if EXISTS(select 1 from AspNetUsers_Devices where DeviceToken=@DeviceToken) BEGIN
UPDATE AspNetUsers_Devices SET UserId=@UserId, Platform=@Platform, LastRegisterDate=getdate() where DeviceToken=@DeviceToken
END ELSE BEGIN
INSERT INTO AspNetUsers_Devices (UserId,DeviceToken,Platform) VALUES (@UserId,@DeviceToken,@Platform)
END

RETURN 1

END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pOffline_SendTable Stored

CREATE PROCEDURE [dbo].[pOffline_SendTable](
@SyncId [nvarchar](100),
@AppName [nvarchar](50),
@UserName [nvarchar](150),
@TableName NVARCHAR(250),
@PageNumber nvarchar(250),
@JsonValue NVARCHAR(max)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pOffline_SendTable
--#CREATION
-- 21/02/2020 - Rubén Pardo
--#CLASIFICATION
-- Flexygo/Offline processes
--#DESCRIPTION
-- Send mobile table to system.
--#PARAMETERS
-- @SyncId: Sync Unique Identificator
-- @AppName: App name
-- @UserName: User name
-- @TableName: Sending table
-- @PageNumber: Number of package
-- @JsonValue: JSON table data.
--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

if NOT EXISTS(select 1 from Offline_Sync where syncId=@SyncId) BEGIN
Insert into Offline_Sync (SyncId,AppName,UserName) values (@SyncId,@AppName,@UserName)
END

Delete [Offline_Sync_Tables] where SyncId=@SyncId and TableName=@TableName AND PageNumber=@PageNumber

Insert into [Offline_Sync_Tables] (SyncId,TableName,JsonValue,PageNumber) Values (@SyncId,@TableName,@JsonValue,@PageNumber)

RETURN 1

END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pSlackExtendedMessage Stored

CREATE PROCEDURE [dbo].[pSlackExtendedMessage](
@WebhookUrl nvarchar(max),
@text nvarchar(max),
@author_name nvarchar(max) = '',
@author_link nvarchar(max) = '',
@title nvarchar(max) = '',
@title_link nvarchar(max) = '',
@descrip nvarchar(max) = '',
@subtitle1 nvarchar(max) = '',
@subtext1 nvarchar(max) = '',
@footer nvarchar(max) = '',
@color_line nvarchar(50) = '#36a64f'
)
AS
----------------------------------------------------------------------------------
--#NAME
-- [pSlackExtendedMessage]
--#CREATION
-- 07/02/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Post message to slack webhook
-- SAMPLE: exec pSlackExtendedMessage @WebhookUrl='',@text='@text',@author_name='@author_name',@author_link='@author_link',@title='@title',@title_link='@title_link',@descrip='@descrip',@subtitle1='@subtitle1',@subtext1='@subtext1',@footer='@footer',@color_line = '#36a64f'
--#PARAMETERS
-- @WebhookUrl: The slack incomming webhook url
-- @Text: Text message
-- @author_name: message author name
-- @author_link: link on author click
-- @title: attach title
-- @title_link: link on attach title click
-- @descrip: attack description
-- @subtitle1: additional title
-- @subtext1: addition text
-- @footer: footer message text
-- @color_line: separator color in hexa

--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

Declare @SlackBody as varchar(max) = ''
Set @SlackBody = @SlackBody + '{'
Set @SlackBody = @SlackBody + ' "attachments": ['
Set @SlackBody = @SlackBody + ' {'
Set @SlackBody = @SlackBody + ' "fallback": "{{text}}",'
Set @SlackBody = @SlackBody + ' "color": "{{color}}",'
Set @SlackBody = @SlackBody + ' "pretext": "{{text}}",'
Set @SlackBody = @SlackBody + ' "author_name": "{{author_name}}",'
Set @SlackBody = @SlackBody + ' "author_link": "{{author_link}}",'
Set @SlackBody = @SlackBody + ' "author_icon": "",'
Set @SlackBody = @SlackBody + ' "title": "{{title}}",'
Set @SlackBody = @SlackBody + ' "title_link": "{{title_link}}",'
Set @SlackBody = @SlackBody + ' "text": "{{descrip}}",'
Set @SlackBody = @SlackBody + ' "fields": ['
Set @SlackBody = @SlackBody + ' {'
Set @SlackBody = @SlackBody + ' "title": "{{subtitle1}}",'
Set @SlackBody = @SlackBody + ' "value": "{{subtext1}}",'
Set @SlackBody = @SlackBody + ' "short": false'
Set @SlackBody = @SlackBody + ' }'
Set @SlackBody = @SlackBody + ' ],'
Set @SlackBody = @SlackBody + ' "footer": "{{footer}}"'
Set @SlackBody = @SlackBody + ' }'
Set @SlackBody = @SlackBody + ' ]'
Set @SlackBody = @SlackBody + '}'

set @SlackBody = REPLACE(@SlackBody,'{{text}}',@text)
set @SlackBody = REPLACE(@SlackBody,'{{author_name}}',@author_name)
set @SlackBody = REPLACE(@SlackBody,'{{author_link}}',@author_link)
set @SlackBody = REPLACE(@SlackBody,'{{title}}',@title)
set @SlackBody = REPLACE(@SlackBody,'{{title_link}}',@title_link)
set @SlackBody = REPLACE(@SlackBody,'{{descrip}}',@descrip)
set @SlackBody = REPLACE(@SlackBody,'{{subtitle1}}',@subtitle1)
set @SlackBody = REPLACE(@SlackBody,'{{subtext1}}',@subtext1)
set @SlackBody = REPLACE(@SlackBody,'{{footer}}',@footer)


Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
EXEC sp_OAMethod @Object, 'open', NULL, 'post',@WebhookUrl, 'false'

Exec sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
Exec sp_OAMethod @Object, 'send', null, @SlackBody

Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Exec sp_OADestroy @Object

if @Response

pSlackExtendedMessage Stored

Text='ok' BEGIN
Return 1
end else begin
EXEC pSlackMessage @WebhookUrl,@Text
end

RETURN 1

END TRY

BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

pSlackMessage Stored

CREATE PROCEDURE [dbo].[pSlackMessage](
@WebhookUrl nvarchar(max),
@Text nvarchar(max)
)
AS
----------------------------------------------------------------------------------
--#NAME
-- pSlackMessage
--#CREATION
-- 07/02/2018
--#CLASIFICATION
-- Framework/systemObjects
--#DESCRIPTION
-- Post message to slack webhook
-- SAMPLE: exec pSlackMessage @SlackUrl,'Message line 1 \n Message link 2<https://www.flexygo.es|Link Example>'
--#PARAMETERS
-- @WebhookUrl: The slack incomming webhook url
-- @Text: Text message

--#OBSERVATIONS
--
--#CHANGES
----------------------------------------------------------------------------------
BEGIN TRY

Declare @SlackBody as varchar(max) = '{"text": "{{text}}"}'
set @SlackBody = REPLACE(@SlackBody,'{{text}}',@Text)


Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
EXEC sp_OAMethod @Object, 'open', NULL, 'post',@WebhookUrl, 'false'

Exec sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
Exec sp_OAMethod @Object, 'send', null, @SlackBody

Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Exec sp_OADestroy @Object

if @ResponseText <> 'ok' BEGIN
RAISERROR(@ResponseText,12,1)
RETURN 0
end

RETURN 1

END TRY

BEGIN CATCH


DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

sp_generate_inserts Stored

CREATE PROCEDURE [dbo].[sp_generate_inserts]
(
@table_name varchar(776), -- The table/view for which the INSERT statements will be generated using the existing data
@target_table varchar(776) = NULL, -- Use this parameter to specify a different table name into which the data will be inserted
@include_column_list bit = 1, -- Use this parameter to include/ommit column list in the generated INSERT statement
@from varchar(800) = NULL, -- Use this parameter to filter the rows based on a filter condition (using WHERE)
@include_timestamp bit = 0, -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
@debug_mode bit = 0, -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
@owner varchar(64) = NULL, -- Use this parameter if you are not the owner of the table
@ommit_images bit = 0, -- Use this parameter to generate INSERT statements by omitting the 'image' columns
@ommit_identity bit = 0, -- Use this parameter to ommit the identity columns
@top int = NULL, -- Use this parameter to generate INSERT statements only for the TOP n rows
@cols_to_include varchar(8000) = NULL, -- List of columns to be included in the INSERT statement
@cols_to_exclude varchar(8000) = NULL, -- List of columns to be excluded from the INSERT statement
@disable_constraints bit = 0, -- When 1, disables foreign key constraints and enables them after the INSERT statements
@ommit_computed_cols bit = 0 -- When 1, computed columns will not be included in the INSERT statement

)
AS
BEGIN

/***********************************************************************************************************
Procedure: sp_generate_inserts (Build 22)
(Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.)

Purpose: To generate INSERT statements from existing data.
These INSERTS can be executed to regenerate the data at some other location.
This procedure is also useful to create a database setup, where in you can
script your data along with your table definitions.

Written by: Narayana Vyas Kondreddi
http://vyaskn.tripod.com

Acknowledgements:
Divya Kalra -- For beta testing
Mark Charsley -- For reporting a problem with scripting uniqueidentifier columns with NULL values
Artur Zeygman -- For helping me simplify a bit of code for handling non-dbo owned tables
Joris Laperre -- For reporting a regression bug in handling text/ntext columns

Tested on: SQL Server 7.0 and SQL Server 2000

Date created: January 17th 2001 21:52 GMT

Date modified: May 1st 2002 19:50 GMT

Email: vyaskn@hotmail.com

NOTE: This procedure may not work with tables with too many columns.
Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results
IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed
you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
like nchar and nvarchar


Example 1: To generate INSERT statements for table 'titles':

EXEC sp_generate_inserts 'titles'

Example 2: To ommit the column list in the INSERT statement: (Column list is included by default)
IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
to avoid erroneous results

EXEC sp_generate_inserts 'titles', @include_column_list = 0

Example 3: To generate INSERT statements for 'titlesCopy' table from 'titles' table:

EXEC sp_generate_inserts 'titles', 'titlesCopy'

Example 4: To generate INSERT statements for 'titles' table for only those titles
which contain the word 'Computer' in them

sp_generate_inserts Stored

:
NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"

Example 5: To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
(By default TIMESTAMP column's data is not scripted)

EXEC sp_generate_inserts 'titles', @include_timestamp = 1

Example 6: To print the debug information:

EXEC sp_generate_inserts 'titles', @debug_mode = 1

Example 7: If you are not the owner of the table, use @owner parameter to specify the owner name
To use this option, you must have SELECT permissions on that table

EXEC sp_generate_inserts Nickstable, @owner = 'Nick'

Example 8: To generate INSERT statements for the rest of the columns excluding images
When using this otion, DO NOT set @include_column_list parameter to 0.

EXEC sp_generate_inserts imgtable, @ommit_images = 1

Example 9: To generate INSERT statements excluding (ommiting) IDENTITY columns:
(By default IDENTITY columns are included in the INSERT statement)

EXEC sp_generate_inserts mytable, @ommit_identity = 1

Example 10: To generate INSERT statements for the TOP 10 rows in the table:

EXEC sp_generate_inserts mytable, @top = 10

Example 11: To generate INSERT statements with only those columns you want:

EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"

Example 12: To generate INSERT statements by omitting certain columns:

EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:

EXEC sp_generate_inserts titles, @disable_constraints = 1

Example 14: To exclude computed columns from the INSERT statement:
EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1
***********************************************************************************************************/

SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
BEGIN
RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_include property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_exclude property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
BEGIN
RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
END

--Checking for the existence of 'user table' or 'view'
--This procedure is n

sp_generate_inserts Stored

ot written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
BEGIN
IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL))
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END
ELSE
BEGIN
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END

--Variable declarations
DECLARE @Column_ID int,
@Column_List varchar(max),
@Column_Name varchar(128),
@Start_Insert varchar(786),
@Data_Type varchar(128),
@Actual_Values varchar(max), --This is the string that will be finally executed to generate INSERT statements
@IDN varchar(128) --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL
BEGIN
SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END
ELSE
BEGIN
SET @Start_Insert = 'INSERT INTO ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END


--To get the first column's ID

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
BEGIN
SELECT @Column_Name = QUOTENAME(COLUMN_NAME),
@Data_Type = DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE ORDINAL_POSITION = @Column_ID AND
TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



IF @cols_to_include IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0
BEGIN
GOTO SKIP_LOOP
END
END

IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0
BEGIN
GOTO SKIP_LOOP
END
END

--Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1
BEGIN
IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
SET @IDN = @Column_Name
ELSE
GOTO SKIP_LOOP
END

--Making sure whether to output computed columns or not
IF @ommit_computed_cols = 1
BEGIN
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1
BEGIN
GOTO SKIP_LOOP
END
END

--Tables with columns of IMAGE data type are not supported for obvious reasons
IF(@Data_Type in ('image'))
BEGIN
IF (@ommit_images = 0)
BEGIN
RAISERROR('Tables with image colum

sp_generate_inserts Stored

ns are not supported.',16,1)
PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
RETURN -1 --Failure. Reason: There is a column with image data type
END
ELSE
BEGIN
GOTO SKIP_LOOP
END
END

--Determining the data type of the column and depending on the data type, the VALUES part of
--the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
--making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
SET @Actual_Values = @Actual_Values +
CASE
WHEN @Data_Type IN ('char','varchar')
THEN
'COALESCE('''''''' + REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(' + @Column_Name + '),'''''''',''''''''''''), CHAR(13) + CHAR(10), '''''' + CHAR(13) + CHAR(10) + ''''''),CHAR(13),'''''' + CHAR(13) + ''''''), CHAR(10), '''''' + CHAR(10) + '''''') +'''''''',''NULL'')'
WHEN @Data_Type IN ('nchar','nvarchar')
THEN
'COALESCE(''N'''''' + REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(' + @Column_Name + '),'''''''',''''''''''''), NCHAR(13) + NCHAR(10), N'''''' + NCHAR(13) + NCHAR(10) + N''''''),NCHAR(13), N'''''' + NCHAR(13) + N''''''),NCHAR(10), N'''''' + NCHAR(10) + N'''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('datetime','smalldatetime')
THEN
'COALESCE('''''''' + RTRIM(CONVERT(varchar,' + @Column_Name + ',109))+'''''''',''NULL'')'
WHEN @Data_Type IN ('uniqueidentifier')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('text','ntext')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('binary','varbinary')
THEN
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
WHEN @Data_Type IN ('timestamp','rowversion')
THEN
CASE
WHEN @include_timestamp = 0
THEN
'''DEFAULT'''
ELSE
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
END
WHEN @Data_Type IN ('float','real','money','smallmoney')
THEN
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')'
ELSE
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + ')),''NULL'')'
END + '+' + ''',''' + ' + '

--Generating the column list for the INSERT statement
SET @Column_List = @Column_List + @Column_Name + ','

SKIP_LOOP: --The label used in GOTO

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
ORDINAL_POSITION > @Column_ID AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)


--Loop ends here!
END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = ''
BEGIN
RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
BEGIN
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
'''' + RTRIM(@Start_Insert) +
' ''+' + '''(' + RTRIM(@Column_List) + '''+' + ''')''' +
' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' +
COALESCE(@from,' FROM ' + CASE W

sp_generate_inserts Stored

HEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
END
ELSE IF (@include_column_list = 0)
BEGIN
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
'''' + RTRIM(@Start_Insert) +
' '' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' +
COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
END

--Determining whether to ouput any debug information
IF @debug_mode =1
BEGIN
PRINT '/*****START OF DEBUG INFORMATION*****'
PRINT 'Beginning of the INSERT statement:'
PRINT @Start_Insert
PRINT ''
PRINT 'The column list:'
PRINT @Column_List
PRINT ''
PRINT 'The SELECT statement executed to generate the INSERTs'
PRINT @Actual_Values
PRINT ''
PRINT '*****END OF DEBUG INFORMATION*****/'
PRINT ''
END

PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ vyaskn@hotmail.com'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''


--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
PRINT 'GO'
PRINT ''
END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END

PRINT 'GO'
END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END

PRINT 'GO'
END

PRINT ''
IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
PRINT 'GO'
END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

sp_generate_inserts_with_exists Stored

CREATE PROCEDURE [dbo].[sp_generate_inserts_with_exists]
(
@table_name varchar(776), -- The table/view for which the INSERT statements will be generated using the existing data
@target_table varchar(776) = NULL, -- Use this parameter to specify a different table name into which the data will be inserted
@include_column_list bit = 1, -- Use this parameter to include/ommit column list in the generated INSERT statement
@from varchar(800) = NULL, -- Use this parameter to filter the rows based on a filter condition (using WHERE)
@include_timestamp bit = 0, -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
@debug_mode bit = 0, -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
@owner varchar(64) = NULL, -- Use this parameter if you are not the owner of the table
@ommit_images bit = 0, -- Use this parameter to generate INSERT statements by omitting the 'image' columns
@ommit_identity bit = 0, -- Use this parameter to ommit the identity columns
@top int = NULL, -- Use this parameter to generate INSERT statements only for the TOP n rows
@cols_to_include varchar(max) = NULL, -- List of columns to be included in the INSERT statement
@cols_to_exclude varchar(max) = NULL, -- List of columns to be excluded from the INSERT statement
@disable_constraints bit = 0, -- When 1, disables foreign key constraints and enables them after the INSERT statements
@ommit_computed_cols bit = 0 -- When 1, computed columns will not be included in the INSERT statement

)
AS
BEGIN

/***********************************************************************************************************
Procedure: sp_generate_inserts (Build 22)
(Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.)

Purpose: To generate INSERT statements from existing data.
These INSERTS can be executed to regenerate the data at some other location.
This procedure is also useful to create a database setup, where in you can
script your data along with your table definitions.

Written by: Narayana Vyas Kondreddi
http://vyaskn.tripod.com

Acknowledgements:
Divya Kalra -- For beta testing
Mark Charsley -- For reporting a problem with scripting uniqueidentifier columns with NULL values
Artur Zeygman -- For helping me simplify a bit of code for handling non-dbo owned tables
Joris Laperre -- For reporting a regression bug in handling text/ntext columns

Tested on: SQL Server 7.0 and SQL Server 2000

Date created: January 17th 2001 21:52 GMT

Date modified: May 1st 2002 19:50 GMT

Email: vyaskn@hotmail.com

NOTE: This procedure may not work with tables with too many columns.
Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results
IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed
you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
like nchar and nvarchar


Example 1: To generate INSERT statements for table 'titles':

EXEC sp_generate_inserts 'titles'

Example 2: To ommit the column list in the INSERT statement: (Column list is included by default)
IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
to avoid erroneous results

EXEC sp_generate_inserts 'titles', @include_column_list = 0

Example 3: To generate INSERT statements for 'titlesCopy' table from 'titles' table:

EXEC sp_generate_inserts 'titles', 'titlesCopy'

Example 4: To generate INSERT statements for 'titles' table for only those titles
which contain the word 'Compute

sp_generate_inserts_with_exists Stored

r' in them:
NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"

Example 5: To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
(By default TIMESTAMP column's data is not scripted)

EXEC sp_generate_inserts 'titles', @include_timestamp = 1

Example 6: To print the debug information:

EXEC sp_generate_inserts 'titles', @debug_mode = 1

Example 7: If you are not the owner of the table, use @owner parameter to specify the owner name
To use this option, you must have SELECT permissions on that table

EXEC sp_generate_inserts Nickstable, @owner = 'Nick'

Example 8: To generate INSERT statements for the rest of the columns excluding images
When using this otion, DO NOT set @include_column_list parameter to 0.

EXEC sp_generate_inserts imgtable, @ommit_images = 1

Example 9: To generate INSERT statements excluding (ommiting) IDENTITY columns:
(By default IDENTITY columns are included in the INSERT statement)

EXEC sp_generate_inserts mytable, @ommit_identity = 1

Example 10: To generate INSERT statements for the TOP 10 rows in the table:

EXEC sp_generate_inserts mytable, @top = 10

Example 11: To generate INSERT statements with only those columns you want:

EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"

Example 12: To generate INSERT statements by omitting certain columns:

EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:

EXEC sp_generate_inserts titles, @disable_constraints = 1

Example 14: To exclude computed columns from the INSERT statement:
EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1
***********************************************************************************************************/

SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
BEGIN
RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_include property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_exclude property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
BEGIN
RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
END

--Checking for the existence of 'user table' or 'view'
--This proc

sp_generate_inserts_with_exists Stored

edure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
BEGIN
IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL))
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END
ELSE
BEGIN
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END

--Variable declarations
DECLARE @Column_ID int,
@Column_List varchar(max),
@Column_Name varchar(128),
@Start_Insert varchar(max),
@Data_Type varchar(128),
@Actual_Values varchar(max),--(8000), --This is the string that will be finally executed to generate INSERT statements
@IDN varchar(128), --Will contain the IDENTITY column's name in the table
@Sql varchar(max)

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''


exec sp_generate_inserts_with_exists_SQL @sql OUTPUT,@table_name,@target_table,@include_timestamp,@owner

IF @owner IS NULL
BEGIN
SET @Start_Insert = @sql + ' INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END
ELSE
BEGIN
SET @Start_Insert = @sql + ' INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'
END


--To get the first column's ID

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
BEGIN
SELECT @Column_Name = QUOTENAME(COLUMN_NAME),
@Data_Type = DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE ORDINAL_POSITION = @Column_ID AND
TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



IF @cols_to_include IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0
BEGIN
GOTO SKIP_LOOP
END
END

IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0
BEGIN
GOTO SKIP_LOOP
END
END

--Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1
BEGIN
IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
SET @IDN = @Column_Name
ELSE
GOTO SKIP_LOOP
END

--Making sure whether to output computed columns or not
IF @ommit_computed_cols = 1
BEGIN
IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1
BEGIN
GOTO SKIP_LOOP
END
END

--Tables with columns of IMAGE data

sp_generate_inserts_with_exists Stored

type are not supported for obvious reasons
IF(@Data_Type in ('image'))
BEGIN
IF (@ommit_images = 0)
BEGIN
RAISERROR('Tables with image columns are not supported.',16,1)
PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
RETURN -1 --Failure. Reason: There is a column with image data type
END
ELSE
BEGIN
GOTO SKIP_LOOP
END
END

--Determining the data type of the column and depending on the data type, the VALUES part of
--the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
--making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
SET @Actual_Values = @Actual_Values +
CASE
WHEN @Data_Type IN ('char','varchar')
THEN
'COALESCE('''''''' + REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(' + @Column_Name + '),'''''''',''''''''''''), CHAR(13) + CHAR(10), '''''' + CHAR(13) + CHAR(10) + ''''''),CHAR(13),'''''' + CHAR(13) + ''''''), CHAR(10), '''''' + CHAR(10) + '''''') +'''''''',''NULL'')'
WHEN @Data_Type IN ('nchar','nvarchar')
THEN
'COALESCE(''N'''''' + REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(' + @Column_Name + '),'''''''',''''''''''''), NCHAR(13) + NCHAR(10), N'''''' + NCHAR(13) + NCHAR(10) + N''''''),NCHAR(13), N'''''' + NCHAR(13) + N''''''),NCHAR(10), N'''''' + NCHAR(10) + N'''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('datetime','smalldatetime')
THEN
'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
WHEN @Data_Type IN ('uniqueidentifier')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('text','ntext')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('binary','varbinary')
THEN
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
WHEN @Data_Type IN ('timestamp','rowversion')
THEN
CASE
WHEN @include_timestamp = 0
THEN
'''DEFAULT'''
ELSE
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
END
WHEN @Data_Type IN ('float','real','money','smallmoney')
THEN
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')'
ELSE
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + ')),''NULL'')'
END + '+' + ''',''' + ' + '

--Generating the column list for the INSERT statement
SET @Column_List = @Column_List + @Column_Name + ','

SKIP_LOOP: --The label used in GOTO

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND
ORDINAL_POSITION > @Column_ID AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)


--Loop ends here!
END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = ''
BEGIN
RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
BEGIN
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
'

sp_generate_inserts_with_exists Stored

''' + RTRIM(@Start_Insert) +
' ''+' + '''(' + RTRIM(@Column_List) + '''+' + ''')''' +
' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' +
COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
END
ELSE IF (@include_column_list = 0)
BEGIN
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
'''' + RTRIM(@Start_Insert) +
' '' +''VALUES(''+ ' + @Actual_Values + '+'')''' + ' ' +
COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
END

--Determining whether to ouput any debug information
IF @debug_mode =1
BEGIN
PRINT '/*****START OF DEBUG INFORMATION*****'
PRINT 'Beginning of the INSERT statement:'
PRINT @Start_Insert
PRINT ''
PRINT 'The column list:'
PRINT @Column_List
PRINT ''
PRINT 'The SELECT statement executed to generate the INSERTs'
PRINT @Actual_Values
PRINT ''
PRINT '*****END OF DEBUG INFORMATION*****/'
PRINT ''
END

/*PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ vyaskn@hotmail.com'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''
*/

--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
PRINT 'GO'
--PRINT ''
END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
END

PRINT 'GO'
END

--PRINT ''
--PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
--print @Actual_Values

EXEC (@Actual_Values)

--PRINT 'PRINT ''Done'''
--PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
BEGIN
IF @owner IS NULL
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END
ELSE
BEGIN
SELECT 'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
END

PRINT 'GO'
END

--PRINT ''
IF (@IDN <> '')
BEGIN
PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
PRINT 'GO'
END

--PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

sp_generate_inserts_with_exists_SQL Stored

CREATE PROCEDURE [dbo].[sp_generate_inserts_with_exists_SQL]
@sql varchar(max) OUTPUT,
@table_name varchar(776),
@target_table varchar(776) = NULL,
@include_timestamp bit = 0,
@owner varchar(64) = NULL

AS
BEGIN

DECLARE @Column_ID int,
@Column_ID1 int,
@Column_Name varchar(128),
@Start_Insert varchar(786),
@Data_Type varchar(128),
@Actual_Values varchar(8000)


SET @Column_ID = 0
SET @Column_Name = ''
SET @Actual_Values = ''

IF @owner IS NULL
BEGIN
SET @Start_Insert = 'IF NOT EXISTS (SELECT * FROM ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + '] WHERE '
END
ELSE
BEGIN
SET @Start_Insert = 'IF NOT EXISTS (SELECT * FROM ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + '] WHERE '
END


--primera clave
SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND (@owner IS NULL OR TABLE_SCHEMA = @owner)
AND column_name IN
(select column_name from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where table_name=@table_name and constraint_name=
(select constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name=@table_name and constraint_type='PRIMARY KEY')) -- NO_TRADUCIR_TAG

SELECT @Column_ID1=@Column_ID


--bucle con las claves
WHILE @Column_ID IS NOT NULL BEGIN

IF @Column_ID1<>@Column_ID

SELECT @Start_Insert= @Start_Insert + ' + '' AND '


SELECT @Column_Name = QUOTENAME(COLUMN_NAME) , @Data_Type = DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE ORDINAL_POSITION = @Column_ID AND TABLE_NAME = @table_name AND (@owner IS NULL OR TABLE_SCHEMA = @owner)
AND column_name IN
(select column_name from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where table_name=@table_name and constraint_name=
(select constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name=@table_name and constraint_type='PRIMARY KEY')) -- NO_TRADUCIR_TAG

SELECT @Start_Insert= @Start_Insert + @Column_Name + '='' +'

SET @Actual_Values = --@Actual_Values +
CASE
WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')' -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
WHEN @Data_Type IN ('datetime','smalldatetime') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')' -- NO_TRADUCIR_TAG
WHEN @Data_Type IN ('uniqueidentifier') -- NO_TRADUCIR_TAG
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')' -- NO_TRADUCIR_TAG
WHEN @Data_Type IN ('text','ntext') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
'COALESCE('''''''' + REPLACE(CONVERT(varchar(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')' -- NO_TRADUCIR_TAG
WHEN @Data_Type IN ('binary','varbinary') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')' -- NO_TRADUCIR_TAG
WHEN @Data_Type IN ('timestamp','rowversion') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
CASE
WHEN @include_timestamp = 0
THEN
'''DEFAULT''' -- NO_TRADUCIR_TAG
ELSE
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')' -- NO_TRADUCIR_TAG
END
WHEN @Data_Type IN ('float','real','money','smallmoney') -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
THEN
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')' -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
ELSE
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name +

sp_generate_inserts_with_exists_SQL Stored

')' + ')),''NULL'')' -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
END + '+' + ''',''' + ' + '


SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)
SELECT @Start_Insert= @Start_Insert + @Actual_Values


SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND ORDINAL_POSITION > @Column_ID AND (@owner IS NULL OR TABLE_SCHEMA = @owner)
AND column_name IN
(select column_name from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where table_name=@table_name and constraint_name=
(select constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name=@table_name and constraint_type='PRIMARY KEY')) -- NO_TRADUCIR_TAG

END

--cadena final
SELECT @Start_Insert=@Start_Insert + ' + '') '

SELECT @sql=@Start_Insert
RETURN -1
END

sp_generate_merge Stored

CREATE PROCEDURE [dbo].[sp_generate_merge]
(
@table_name varchar(776), -- The table/view for which the MERGE statement will be generated using the existing data
@target_table varchar(776) = NULL, -- Use this parameter to specify a different table name into which the data will be inserted/updated/deleted
@from varchar(800) = NULL, -- Use this parameter to filter the rows based on a filter condition (using WHERE)
@include_timestamp bit = 0, -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the MERGE statement
@debug_mode bit = 0, -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
@schema varchar(64) = NULL, -- Use this parameter if you are not the owner of the table
@ommit_images bit = 0, -- Use this parameter to generate MERGE statement by omitting the 'image' columns
@ommit_identity bit = 0, -- Use this parameter to ommit the identity columns
@top int = NULL, -- Use this parameter to generate a MERGE statement only for the TOP n rows
@cols_to_include varchar(8000) = NULL, -- List of columns to be included in the MERGE statement
@cols_to_exclude varchar(8000) = NULL, -- List of columns to be excluded from the MERGE statement
@update_only_if_changed bit = 1, -- When 1, only performs an UPDATE operation if an included column in a matched row has changed.
@delete_if_not_matched bit = 1, -- When 1, deletes unmatched source rows from target, when 0 source rows will only be used to update existing rows or insert new.
@disable_constraints bit = 0, -- When 1, disables foreign key constraints and enables them after the MERGE statement
@ommit_computed_cols bit = 0, -- When 1, computed columns will not be included in the MERGE statement
@include_use_db bit = 0, -- When 1, includes a USE [DatabaseName] statement at the beginning of the generated batch
@results_to_text bit = 0, -- When 1, outputs results to grid/messages window. When 0, outputs MERGE statement in an XML fragment.
@include_rowsaffected bit = 0, -- When 1, a section is added to the end of the batch which outputs rows affected by the MERGE
@nologo bit = 1, -- When 1, the "About" comment is suppressed from output
@batch_separator VARCHAR(50) = 'GO', -- Batch separator to use
@OriginId int = 0, --Default filter for OriginId fields
@ReturnSql bit = 0, --return to variable
@OutputSQL nvarchar(max) = null OUTPUT --return variable

)
AS
BEGIN

/***********************************************************************************************************

--2017.09.12.Customized for FlexyGo Use Cases:
-- If table contains an OriginId Field, DELETE clause WILL NOT delete records with OriginId = 2



Procedure: sp_generate_merge (Version 0.93)
(Adapted by Daniel Nolan for SQL Server 2008/2012)

Adapted from: sp_generate_inserts (Build 22)
(Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.)

Purpose: To generate a MERGE statement from existing data, which will INSERT/UPDATE/DELETE data based
on matching primary key values in the source/target table.

The generated statements can be executed to replicate the data in some other location.

Typical use cases:
* Generate statements for static data tables, store the .SQL file in source control and use
it as part of your Dev/Test/Prod deployment. The generated statements are re-runnable, so
you can make changes to the file and migrate those changes between environments.

* Generate statements from your Production tables and then run those statements in your
Dev/Test environments. Schedule this as part of a SQL Job to keep all of your environments
in-sync.

* Enter test data into your Dev environment, and then generate statements from the Dev
tables so that you can always reproduce your test database with valid sample data.


Written by: Narayana Vyas Kondreddi
http://vyaskn.tripod.com

Daniel Nolan
http://

sp_generate_merge Stored

danere.com
@dan3r3

Acknowledgements (sp_generate_merge):
Nathan Skerl -- StackOverflow answer that provided a workaround for the output truncation problem
http://stackoverflow.com/a/10489767/266882

Bill Gibson -- Blog that detailed the static data table use case; the inspiration for this proc
http://blogs.msdn.com/b/ssdt/archive/2012/02/02/including-data-in-an-sql-server-database-project.aspx

Bill Graziano -- Blog that provided the groundwork for MERGE statement generation
http://weblogs.sqlteam.com/billg/archive/2011/02/15/generate-merge-statements-from-a-table.aspx

Acknowledgements (sp_generate_inserts):
Divya Kalra -- For beta testing
Mark Charsley -- For reporting a problem with scripting uniqueidentifier columns with NULL values
Artur Zeygman -- For helping me simplify a bit of code for handling non-dbo owned tables
Joris Laperre -- For reporting a regression bug in handling text/ntext columns

Tested on: SQL Server 2008 (10.50.1600), SQL Server 2012 (11.0.2100)

Date created: January 17th 2001 21:52 GMT
Modified: May 1st 2002 19:50 GMT
Last Modified: September 27th 2012 10:00 AEDT

Email: dan@danere.com, vyaskn@hotmail.com

NOTE: This procedure may not work with tables with a large number of columns (> 500).
Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
IMPORTANT: This procedure has not been extensively tested with international data (Extended characters or Unicode). If needed
you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
like nchar and nvarchar

Get Started: Ensure that your SQL client is configured to send results to grid (default SSMS behaviour).
This ensures that the generated MERGE statement can be output in full, getting around SSMS's 4000 nchar limit.
After running this proc, click the hyperlink within the single row returned to copy the generated MERGE statement.

Example 1: To generate a MERGE statement for table 'titles':

EXEC sp_generate_merge 'titles'

Example 2: To generate a MERGE statement for 'titlesCopy' table from 'titles' table:

EXEC sp_generate_merge 'titles', 'titlesCopy'

Example 3: To generate a MERGE statement for table 'titles' that will unconditionally UPDATE matching rows
(ie. not perform a "has data changed?" check prior to going ahead with an UPDATE):

EXEC sp_generate_merge 'titles', @update_only_if_changed = 0

Example 4: To generate a MERGE statement for 'titles' table for only those titles
which contain the word 'Computer' in them:
NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

EXEC sp_generate_merge 'titles', @from = "from titles where title like '%Computer%'"

Example 5: To specify that you want to include TIMESTAMP column's data as well in the MERGE statement:
(By default TIMESTAMP column's data is not scripted)

EXEC sp_generate_merge 'titles', @include_timestamp = 1

Example 6: To print the debug information:

EXEC sp_generate_merge 'titles', @debug_mode = 1

Example 7: If the table is in a different schema to the default, use @schema parameter to specify the schema name
To use this option, you must have SELECT permissions on that table

EXEC sp_generate_merge 'Nickstable', @schema = 'Nick'

Example 8: To generate a MERGE statement for the rest of the columns excluding images

EXEC sp_generate_merge 'imgtable', @ommit_images = 1

Example 9: To generate a MERGE statement excluding (omitting) IDENTITY columns:
(By default IDENTITY columns are included in the MERGE statement)

EXEC sp_generate_merge 'mytable', @ommit_identity = 1

Example 10: To generate a MERGE statement for the TOP 10 rows in the table:

EXEC sp_generate_merge 'mytable', @top = 10

Example 11: To generate a MERGE statement with only those columns you want:

EXEC sp_generate_merge 'tit

sp_generate_merge Stored

les', @cols_to_include = "'title','title_id','au_id'"

Example 12: To generate a MERGE statement by omitting certain columns:

EXEC sp_generate_merge 'titles', @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with a MERGE statement:

EXEC sp_generate_merge 'titles', @disable_constraints = 1

Example 14: To exclude computed columns from the MERGE statement:

EXEC sp_generate_merge 'MyTable', @ommit_computed_cols = 1

***********************************************************************************************************/


SET NOCOUNT ON


--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
BEGIN
RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
END


--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_include property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_merge titles, @cols_to_include = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
BEGIN
RAISERROR('Invalid use of @cols_to_exclude property',16,1)
PRINT 'Specify column names surrounded by single quotes and separated by commas'
PRINT 'Eg: EXEC sp_generate_merge titles, @cols_to_exclude = "''title_id'',''title''"'
RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate a MERGE statement
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
BEGIN
RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
END


--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead
IF @schema IS NULL
BEGIN
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = SCHEMA_NAME())
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'You may see this error if the specified table is not in your default schema (' + SCHEMA_NAME() + '). In that case use @schema parameter to specify the schema name.'
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END
ELSE
BEGIN
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @schema)
BEGIN
RAISERROR('User table or view not found.',16,1)
PRINT 'Make sure you have SELECT permission on that table or view.'
RETURN -1 --Failure. Reason: There is no user table or view with this name
END
END


--Variable declarations
DECLARE @Column_ID int,
@Column_List varchar(8000),
@Column_List_For_Update varchar(max),
@Column_List_For_Check varchar(max),
@Column_Name varchar(128),
@Column_Name_Unquoted varchar(128),
@Data_Type varchar(128),
@Actual_Values nvarchar(max), --This is the string that will be fina

sp_generate_merge Stored

lly executed to generate a MERGE statement
@IDN varchar(128), --Will contain the IDENTITY column's name in the table
@Target_Table_For_Output varchar(776),
@Source_Table_Qualified varchar(776),
@HasOriginId bit


DECLARE @b CHAR(2) = CHAR(13)+CHAR(10)

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_Name_Unquoted = ''
SET @Column_List = ''
SET @Column_List_For_Update = ''
SET @Column_List_For_Check = ''
SET @Actual_Values = ''

--Variable Defaults
IF @schema IS NULL
BEGIN
SET @Target_Table_For_Output = QUOTENAME(COALESCE(@target_table, @table_name))
END
ELSE
BEGIN
SET @Target_Table_For_Output = QUOTENAME(@schema) + '.' + QUOTENAME(COALESCE(@target_table, @table_name))
END

SET @Source_Table_Qualified = QUOTENAME(COALESCE(@schema,SCHEMA_NAME())) + '.' + QUOTENAME(@table_name)

--To get the first column's ID
SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name
AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())

IF EXISTS(
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name AND COLUMN_NAME='OriginId'
) SET @HasOriginId = 1

--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
BEGIN
SELECT @Column_Name = QUOTENAME(COLUMN_NAME),
@Column_Name_Unquoted = COLUMN_NAME,
@Data_Type = DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE ORDINAL_POSITION = @Column_ID
AND TABLE_NAME = @table_name
AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())

IF @cols_to_include IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0
BEGIN
GOTO SKIP_LOOP
END
END

IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
BEGIN
IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0
BEGIN
GOTO SKIP_LOOP
END
END

--Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
IF (SELECT COLUMNPROPERTY( OBJECT_ID(@Source_Table_Qualified),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1
BEGIN
IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
SET @IDN = @Column_Name
ELSE
GOTO SKIP_LOOP
END

--Making sure whether to output computed columns or not
IF @ommit_computed_cols = 1
BEGIN
IF (SELECT COLUMNPROPERTY( OBJECT_ID(@Source_Table_Qualified),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1
BEGIN
GOTO SKIP_LOOP
END
END

--Tables with columns of IMAGE data type are not supported for obvious reasons
IF(@Data_Type in ('image'))
BEGIN
IF (@ommit_images = 0)
BEGIN
RAISERROR('Tables with image columns are not supported.',16,1)
PRINT 'Use @ommit_images = 1 parameter to generate a MERGE for the rest of the columns.'
RETURN -1 --Failure. Reason: There is a column with image data type
END
ELSE
BEGIN
GOTO SKIP_LOOP
END
END

--Determining the data type of the column and depending on the data type, the VALUES part of
--the MERGE statement is generated. Care is taken to handle columns with NULL values. Also
--making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
SET @Actual_Values = @Actual_Values +
CASE
WHEN @Data_Type IN ('char','nchar')
THEN
'COALESCE(''N'''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('varchar','nvarchar')
THEN
'COALESCE(''N'''''' + REPLACE(' + @Column_Name + ','''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('datetime','smalldatetime','datetime2','date')
THEN
'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',127))+'''''''',''NULL'')'
WHEN @Data_Type IN ('uniqueid

sp_generate_merge Stored

entifier')
THEN
'COALESCE(''N'''''' + REPLACE(CONVERT(char(36),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('text')
THEN
'COALESCE(''N'''''' + REPLACE(CONVERT(varchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('ntext')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(nvarchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('xml')
THEN
'COALESCE('''''''' + REPLACE(CONVERT(nvarchar(max),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
WHEN @Data_Type IN ('binary','varbinary')
THEN
'COALESCE(RTRIM(CONVERT(varchar(max),' + @Column_Name + ', 1))),''NULL'')'
WHEN @Data_Type IN ('timestamp','rowversion')
THEN
CASE
WHEN @include_timestamp = 0
THEN
'''DEFAULT'''
ELSE
'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'
END
WHEN @Data_Type IN ('float','real','money','smallmoney')
THEN
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ',2)' + ')),''NULL'')'
WHEN @Data_Type IN ('hierarchyid')
THEN
'COALESCE(''hierarchyid::Parse(''+'''''''' + LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + '))+''''''''+'')'',''NULL'')'
ELSE
'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' + @Column_Name + ')' + ')),''NULL'')'
END + '+' + ''',''' + ' + '

--Generating the column list for the MERGE statement
SET @Column_List = @Column_List + @Column_Name + ','

--Don't update Primary Key or Identity columns
IF NOT EXISTS(
SELECT 1
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @table_name
AND pk.TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
AND c.COLUMN_NAME = @Column_Name_Unquoted
)
BEGIN
SET @Column_List_For_Update = @Column_List_For_Update + @Column_Name + ' = Source.' + @Column_Name + ',
'
SET @Column_List_For_Check = @Column_List_For_Check +
CASE @Data_Type
WHEN 'text' THEN @b + CHAR(9) + 'NULLIF(CAST(Source.' + @Column_Name + ' AS VARCHAR(MAX)), CAST(Target.' + @Column_Name + ' AS VARCHAR(MAX))) IS NOT NULL OR NULLIF(CAST(Target.' + @Column_Name + ' AS VARCHAR(MAX)), CAST(Source.' + @Column_Name + ' AS VARCHAR(MAX))) IS NOT NULL OR '
WHEN 'ntext' THEN @b + CHAR(9) + 'NULLIF(CAST(Source.' + @Column_Name + ' AS NVARCHAR(MAX)), CAST(Target.' + @Column_Name + ' AS NVARCHAR(MAX))) IS NOT NULL OR NULLIF(CAST(Target.' + @Column_Name + ' AS NVARCHAR(MAX)), CAST(Source.' + @Column_Name + ' AS NVARCHAR(MAX))) IS NOT NULL OR '
ELSE @b + CHAR(9) + 'NULLIF(Source.' + @Column_Name + ', Target.' + @Column_Name + ') IS NOT NULL OR NULLIF(Target.' + @Column_Name + ', Source.' + @Column_Name + ') IS NOT NULL OR '
END
END

SKIP_LOOP: --The label used in GOTO

SELECT @Column_ID = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS (NOLOCK)
WHERE TABLE_NAME = @table_name
AND TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
AND ORDINAL_POSITION > @Column_ID

END --Loop ends here!


--To get rid of the extra characters that got concatenated during the last run through the loop
IF LEN(@Column_List_For_Update) <> 0
BEGIN
SET @Column_List_For_Update = ' ' + LEFT(@Column_List_For_Update,len(@Column_List_For_Update) - 4)
END

IF LEN(@Column_List_For_Check) <> 0
BEGIN
SET @Column_List_For_Check = LEFT(@Column_List_For_Check,len(@Column_List_For_Check) - 3)
END

SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
IF LEN(LTRIM(@Column_List)) = 0
BEGIN
RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using

sp_generate_merge Stored

the @cols_to_exclude parameter
END


--Get the join columns ----------------------------------------------------------
DECLARE @PK_column_list VARCHAR(8000)
DECLARE @PK_column_joins VARCHAR(8000)
SET @PK_column_list = ''
SET @PK_column_joins = ''

SELECT TOP 100 PERCENT @PK_column_list = @PK_column_list + '[' + c.COLUMN_NAME + '], '
, @PK_column_joins = @PK_column_joins + 'Target.[' + c.COLUMN_NAME + '] = Source.[' + c.COLUMN_NAME + '] AND '
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @table_name
AND pk.TABLE_SCHEMA = COALESCE(@schema, SCHEMA_NAME())
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
ORDER BY
c.ORDINAL_POSITION
IF IsNull(@PK_column_list, '') = ''
BEGIN
RAISERROR('Table has no primary keys. There should at least be one column in order to have a valid join.',16,1)
RETURN -1 --Failure. Reason: looks like table doesn't have any primary keys
END

SET @PK_column_list = LEFT(@PK_column_list, LEN(@PK_column_list) -1)
SET @PK_column_joins = LEFT(@PK_column_joins, LEN(@PK_column_joins) -4)


--Forming the final string that will be executed, to output the a MERGE statement
SET @Actual_Values =
'SELECT ' +
CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END +
'''' +
' '' + CASE WHEN ROW_NUMBER() OVER (ORDER BY ' + @PK_column_list + ') = 1 THEN '' '' ELSE '','' END + ''(''+ ' + @Actual_Values + '+'')''' + ' ' +
COALESCE(@from,' FROM ' + @Source_Table_Qualified + ' (NOLOCK) ORDER BY ' + @PK_column_list)

DECLARE @output VARCHAR(MAX) = ''


--Determining whether to ouput any debug information
IF @debug_mode =1
BEGIN
SET @output += @b + '/*****START OF DEBUG INFORMATION*****'
SET @output += @b + ''
SET @output += @b + 'The primary key column list:'
SET @output += @b + @PK_column_list
SET @output += @b + ''
SET @output += @b + 'The INSERT column list:'
SET @output += @b + @Column_List
SET @output += @b + ''
SET @output += @b + 'The UPDATE column list:'
SET @output += @b + @Column_List_For_Update
SET @output += @b + ''
SET @output += @b + 'The SELECT statement executed to generate the MERGE:'
SET @output += @b + @Actual_Values
SET @output += @b + ''
SET @output += @b + '*****END OF DEBUG INFORMATION*****/'
SET @output += @b + ''
END

IF (@include_use_db = 1)
BEGIN
SET @output += @b + 'USE ' + DB_NAME()
SET @output += @b + @batch_separator
SET @output += @b + @b
END

IF (@nologo = 0)
BEGIN
SET @output += @b + '--MERGE generated by ''sp_generate_merge'' stored procedure, Version 0.93'
SET @output += @b + '--Originally by Vyas (http://vyaskn.tripod.com): sp_generate_inserts (build 22)'
SET @output += @b + '--Adapted for SQL Server 2008/2012 by Daniel Nolan (http://danere.com)'
SET @output += @b + '--Adapted for FlexyGo by JJR'
SET @output += @b + ''
END

SET @output += @b
SET @output += @b + 'BEGIN TRY'


IF (@include_rowsaffected = 1) -- If the caller has elected not to include the "rows affected" section, let MERGE output the row count as it is executed.
SET @output += @b + 'SET NOCOUNT ON'
SET @output += @b + ''


--Determining whether to print IDENTITY_INSERT or not
IF (LEN(@IDN) <> 0)
BEGIN
SET @output += @b + 'SET IDENTITY_INSERT ' + @Target_Table_For_Output + ' ON'
SET @output += @b + ''
END


--Temporarily disable constraints on the target table
IF @disable_constraints = 1 AND (OBJECT_ID(@Source_Table_Qualified, 'U') IS NOT NULL)
BEGIN
SET @output += @b + 'ALTER TABLE ' + @Target_Table_For_Output + ' NOCHECK CONSTRAINT ALL' --Code to disable constraints temporarily
END


--Output the start of the MERGE statement, qualifying with the schema name only if the caller explicitly specified it
SET @output += @b + 'MERGE INTO ' + @Target_Table_For_Output + ' AS Target'
SET @outpu

sp_generate_merge Stored

t += @b + 'USING (VALUES'


--All the hard work pays off here!!! You'll get your MERGE statement, when the next line executes!
DECLARE @tab TABLE (ID INT NOT NULL PRIMARY KEY IDENTITY(1,1), val NVARCHAR(max));
INSERT INTO @tab (val)
EXEC (@Actual_Values)

IF (SELECT COUNT(*) FROM @tab) <> 0 -- Ensure that rows were returned, otherwise the MERGE statement will get nullified.
BEGIN
SET @output += CAST((SELECT @b + val FROM @tab ORDER BY ID FOR XML PATH('')) AS XML).value('.', 'VARCHAR(MAX)');
END

--Output the columns to correspond with each of the values above--------------------
SET @output += @b + ') AS Source (' + @Column_List + ')'


--Output the join columns ----------------------------------------------------------
SET @output += @b + 'ON (' + @PK_column_joins + ')'


--When matched, perform an UPDATE on any metadata columns only (ie. not on PK)------
IF LEN(@Column_List_For_Update) <> 0
BEGIN
SET @output += @b + 'WHEN MATCHED ' + CASE WHEN @update_only_if_changed = 1 THEN 'AND (' + @Column_List_For_Check + ') ' ELSE '' END + 'THEN'
SET @output += @b + ' UPDATE SET'
SET @output += @b + ' ' + LTRIM(@Column_List_For_Update)
END


--When NOT matched by target, perform an INSERT------------------------------------
SET @output += @b + 'WHEN NOT MATCHED BY TARGET THEN';
SET @output += @b + ' INSERT(' + @Column_List + ')'
SET @output += @b + ' VALUES(' + REPLACE(@Column_List, '[', 'Source.[') + ')'


--When NOT matched by source, DELETE the row
IF @delete_if_not_matched=1 BEGIN
IF @HasOriginId = 1 BEGIN
SET @output += @b + 'WHEN NOT MATCHED BY SOURCE AND TARGET.OriginId = ' + CAST(@OriginId AS VARCHAR(5)) + ' THEN '
END ELSE BEGIN
SET @output += @b + 'WHEN NOT MATCHED BY SOURCE THEN '
END
SET @output += @b + ' DELETE'
END;
SET @output += @b + ';'



--Display the number of affected rows to the user, or report if an error occurred---
IF @include_rowsaffected = 1
BEGIN
SET @output += @b + 'DECLARE @mergeCount int'
SET @output += @b + 'SELECT @mergeCount = @@ROWCOUNT'
SET @output += @b + ' PRINT ''' + @Target_Table_For_Output + ' rows affected by MERGE: '' + CAST(@mergeCount AS VARCHAR(100));';
SET @output += @b + @b
END



SET @output += @b + 'END TRY'
SET @output += @b + 'BEGIN CATCH'

SET @output += @b + ' DECLARE @ERRORNUMBER INT,@ERRORMSG VARCHAR(MAX),@ERRORSTATE INT'
SET @output += @b + ' SELECT @ERRORNUMBER = 50000 + ERROR_NUMBER(),@ERRORMSG = ERROR_MESSAGE(), @ERRORSTATE = ERROR_STATE();'
SET @output += @b + ' THROW @ERRORNUMBER, @ERRORMSG, @ERRORSTATE'
SET @output += @b + 'END CATCH'


SET @output += @b + @batch_separator
SET @output += @b + @b

--Re-enable the previously disabled constraints-------------------------------------
IF @disable_constraints = 1 AND (OBJECT_ID(@Source_Table_Qualified, 'U') IS NOT NULL)
BEGIN
SET @output += 'ALTER TABLE ' + @Target_Table_For_Output + ' CHECK CONSTRAINT ALL' --Code to enable the previously disabled constraints
SET @output += @b + @batch_separator
SET @output += @b
END


--Switch-off identity inserting------------------------------------------------------
IF (LEN(@IDN) <> 0)
BEGIN
SET @output += 'SET IDENTITY_INSERT ' + @Target_Table_For_Output + ' OFF'
SET @output += @b + @batch_separator
SET @output += @b
END

IF (@include_rowsaffected = 1)
BEGIN
SET @output += 'SET NOCOUNT OFF'
SET @output += @b + @batch_separator
SET @output += @b
END

SET @output += @b + ''
SET @output += @b + ''

SET @output = replace(@output,'$',''' + convert(nvarchar(max),NCHAR(36)) + N''')

IF @results_to_text = 1
BEGIN
--output the statement to the Grid/Messages tab
SET @output += @b+@b
SELECT @output as MergeText, @table_name as Tablename;
END
ELSE
BEGIN
--output the statement as xml (to overcome SSMS 4000/8000 char limitation)
IF @ReturnSql = 1 BEGIN
SELECT @OutputSQL = @output
END ELSE BEGIN
SELECT [processing-instruction(x)

sp_generate_merge Stored

]=@output FOR XML PATH(''),TYPE;
END

PRINT 'MERGE statement has been wrapped in an XML fragment and output successfully.'
PRINT 'Ensure you have Results to Grid enabled and then click the hyperlink to copy the statement within the fragment.'
PRINT ''
PRINT 'If you would prefer to have results output directly (without XML) specify @results_to_text = 1, however please'
PRINT 'note that the results may be truncated by your SQL client to 4000 nchars.'
END

SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

sp_SearchTables Stored

CREATE PROCEDURE [dbo].[sp_SearchTables]
@Tablenames VARCHAR(500)
,@SearchStr NVARCHAR(60)
,@GenerateSQLOnly Bit = 0
AS

/*
Parameters and usage

@Tablenames -- Provide a single table name or multiple table name with comma seperated.
If left blank , it will check for all the tables in the database
Provide wild card tables names with comma seperated
EX :'%tbl%,Dim%' -- This will search the table having names comtains "tbl" and starts with "Dim"

@SearchStr -- Provide the search string. Use the '%' to coin the search. Also can provide multiple search with comma seperated
EX : X%--- will give data staring with X
%X--- will give data ending with X
%X%--- will give data containig X
%X%,Y%--- will give data containig X or starting with Y
%X%,%,,% -- Use a double comma to search comma in the data
@GenerateSQLOnly -- Provide 1 if you only want to generate the SQL statements without seraching the database.
By default it is 0 and it will search.

Samples :

1. To search data in a table

EXEC SP_SearchTables @Tablenames = 'T1'
,@SearchStr = '%TEST%'

The above sample searches in table T1 with string containing TEST.

2. To search in a multiple table

EXEC SP_SearchTables @Tablenames = 'T2'
,@SearchStr = '%TEST%'

The above sample searches in tables T1 & T2 with string containing TEST.

3. To search in a all table

EXEC SP_SearchTables @Tablenames = '%'
,@SearchStr = '%TEST%'

The above sample searches in all table with string containing TEST.

4. Generate the SQL for the Select statements

EXEC SP_SearchTables @Tablenames = 'T1'
,@SearchStr = '%TEST%'
,@GenerateSQLOnly = 1

5. To Search in tables with specfic name

EXEC SP_SearchTables @Tablenames = '%T1%'
,@SearchStr = '%TEST%'
,@GenerateSQLOnly = 0

6. To Search in multiple tables with specfic names

EXEC SP_SearchTables @Tablenames = '%T1%,Dim%'
,@SearchStr = '%TEST%'
,@GenerateSQLOnly = 0

7. To specify multiple search strings

EXEC SP_SearchTables @Tablenames = '%T1%,Dim%'
,@SearchStr = '%TEST%,TEST1%,%TEST2'
,@GenerateSQLOnly = 0


8. To search comma itself in the tables use double comma ",,"

EXEC SP_SearchTables @Tablenames = '%T1%,Dim%'
,@SearchStr = '%,,%'
,@GenerateSQLOnly = 0

EXEC SP_SearchTables @Tablenames = '%T1%,Dim%'
,@SearchStr = '%with,,comma%'
,@GenerateSQLOnly = 0
*/

SET NOCOUNT ON

DECLARE @MatchFound BIT

SELECT @MatchFound = 0

DECLARE @CheckTableNames Table
(
Tablename sysname
)

DECLARE @SearchStringTbl TABLE
(
SearchString VARCHAR(500)
)

DECLARE @SQLTbl TABLE
(
Tablename SYSNAME
,WHEREClause VARCHAR(MAX)
,SQLStatement VARCHAR(MAX)
,Execstatus BIT
)

DECLARE @SQL VARCHAR(MAX)
DECLARE @TblSQL VARCHAR(MAX)
DECLARE @tmpTblname sysname
DECLARE @ErrMsg VARCHAR(100)

IF LTRIM(RTRIM(@Tablenames)) IN ('' ,'%')
BEGIN

INSERT INTO @CheckTableNames
SELECT Name
FROM sys.tables
END
ELSE
BEGIN

IF CHARINDEX(',',@Tablenames) > 0
SELECT @SQL = 'SELECT ''' + REPLACE(@Tablenames,',','''as TblName UNION SELECT ''') + ''''
ELSE
SELECT @SQL = 'SELECT ''' + @Tablenames + ''' as TblName '

SELECT @TblSQL = 'SELECT T.NAME
FROM SYS.TABLES T
JOIN (' + @SQL + ') tblsrc
ON T.name LIKE tblsrc.tblname '




INSERT INTO @CheckTableNames
EXEC(@TblSQL)

END

IF NOT EXISTS(SELECT 1 FROM @CheckTableNames)
BEGIN

SELECT @ErrMsg = 'No tables are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT @ErrMsg
RETURN

END


IF LTRIM(RTRIM(@SearchStr)) =''
BEGIN

SELECT @ErrMsg = 'Please specify the search string in @SearchStr Parameter'
PRINT @ErrMsg
RETURN
END
ELSE
BEGIN
SELECT @Searc

sp_SearchTables Stored

hStr = REPLACE(@SearchStr,',,,',',#DOUBLECOMMA#')
SELECT @SearchStr = REPLACE(@SearchStr,',,','#DOUBLECOMMA#')

SELECT @SQL = 'SELECT ''' + REPLACE(@SearchStr,',','''as SearchString UNION SELECT ''') + ''''

INSERT INTO @SearchStringTbl
(SearchString)
EXEC(@SQL)

UPDATE @SearchStringTbl
SET SearchString = REPLACE(SearchString ,'#DOUBLECOMMA#',',')
END



INSERT INTO @SQLTbl
( Tablename,WHEREClause)
SELECT QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME),
(
SELECT '[' + SC.Name + ']' + ' LIKE ''' + SearchSTR.SearchString + ''' OR ' + CHAR(10)
FROM SYS.columns SC
JOIN SYS.types STy
ON STy.system_type_id = SC.system_type_id
AND STy.user_type_id =SC.user_type_id
CROSS JOIN @SearchStringTbl SearchSTR
WHERE STY.name in ('varchar','char','nvarchar','nchar','text')
AND SC.object_id = ST.object_id
ORDER BY SC.name
FOR XML PATH('')
)
FROM SYS.tables ST
JOIN @CheckTableNames chktbls
ON chktbls.Tablename = ST.name
JOIN SYS.schemas SCh
ON ST.schema_id = SCh.schema_id
WHERE ST.name <> 'SearchTMP'
GROUP BY ST.object_id, QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME) ;


UPDATE @SQLTbl
SET SQLStatement = 'SELECT * INTO ##SearchTMP FROM ' + Tablename + ' WHERE ' + substring(WHEREClause,1,len(WHEREClause)-5)



DELETE FROM @SQLTbl
WHERE WHEREClause IS NULL

WHILE EXISTS (SELECT 1 FROM @SQLTbl WHERE ISNULL(Execstatus ,0) = 0)
BEGIN

SELECT TOP 1 @tmpTblname = Tablename , @SQL = SQLStatement
FROM @SQLTbl
WHERE ISNULL(Execstatus ,0) = 0

IF @GenerateSQLOnly = 0
BEGIN

IF 1=0 BEGIN --Solo por evitar error ssdt
CREATE TABLE ##SearchTMP (DUMMY INT)
END

IF OBJECT_ID('tempdb..##SearchTMP','U') IS NOT NULL
DROP TABLE ##SearchTMP
EXEC (@SQL)

IF EXISTS(SELECT 1 FROM ##SearchTMP)
BEGIN
SELECT Tablename=@tmpTblname,* FROM ##SearchTMP
SELECT @MatchFound = 1
END

END
ELSE
BEGIN
PRINT REPLICATE('-',100)
PRINT @tmpTblname
PRINT REPLICATE('-',100)
PRINT replace(@SQL,'INTO ##SearchTMP','')
END

UPDATE @SQLTbl
SET Execstatus = 1
WHERE Tablename = @tmpTblname

END

IF @MatchFound = 0
BEGIN
SELECT @ErrMsg = 'No Matches are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT @ErrMsg
RETURN
END

SET NOCOUNT OFF

sprintf Stored

CREATE procedure [dbo].[sprintf] @Msg nvarchar(4000) output, @Cadena nvarchar(4000),
@P0 nvarchar(1000)='',
@P1 nvarchar(1000)='',
@P2 nvarchar(1000)='',
@P3 nvarchar(1000)='',
@P4 nvarchar(1000)='',
@P5 nvarchar(1000)='',
@P6 nvarchar(1000)='',
@P7 nvarchar(1000)='',
@P8 nvarchar(1000)='',
@P9 nvarchar(1000)=''
AS
--
-- Este Store reemplaza los caracteres '%v' por el parametro correspondiente
-- y los '\n' por char(cr) + char(lf)
--
BEGIN
SET NOCOUNT ON

declare @s nvarchar(4000)
declare @sub nvarchar(2)
declare @i smallint
declare @p smallint
declare @Valor nvarchar(1000)
declare @Sql as nvarchar(1000)

SET @s=@Cadena
set @i=1
set @p=0

WHILE @i <= len(@s) BEGIN
SET @sub = lower(substring(@s,@i,2))
IF @sub='%v' BEGIN
SELECT @Valor=
CASE @p
when 0 then @P0
when 1 then @P1
when 2 then @P2
when 3 then @P3
when 4 then @P4
when 5 then @P5
when 6 then @P6
when 7 then @P7
when 8 then @P8
when 9 then @P9
END
SET @s = substring(@s,1,@i-1) + @Valor + substring(@s, @i+2, len(@s))
set @i = @i + len(@Valor)
set @p = @p+1
END
ELSE BEGIN
IF @Sub='\n' BEGIN
SET @s=substring(@s,1,@i-1) + char(13) + char(10) + substring(@s,@i +2,len(@s))
set @i = @i + 2
END
ELSE
SET @i=@i+1
END
END
set @Msg = @s
end

zMerge Stored

CREATE PROCEDURE [dbo].[zMerge](
@table varchar(776),
@from varchar(800) = NULL
)
AS
----------------------------------------------------------------------------------
--#NAME
-- ZMerge
--#CREATION
-- 16/01/2018
--#CLASIFICATION
-- Framework/Utils
--#DESCRIPTION
-- Create a merge sentence from table. Lite version of sp_generate_merge
--#PARAMETERS
-- @table varchar(776) The table/view for which the MERGE statement will be generated using the existing data
-- @from varchar(800) = NULL Use this parameter to filter the rows based on a filter condition (using WHERE)
--#OBSERVATIONS
--
--#CHANGES
--
----------------------------------------------------------------------------------
BEGIN

exec sp_generate_merge @table_name=@table,@from=@from

END

ZP_Extract_Objects Stored

CREATE PROCEDURE ZP_Extract_Objects
@ExcludedTables Varchar(max),
@ExcludedObjects Varchar(max)

AS
-- =============================================
-- #AUTOR:
-- Carmen

-- #NAME:
--- ZP_Extract_Objects
-- #CREATION:
-- 02/02/2017
-- #CLASIFICATION:
-- --010-GENERAL
-- #DESCRIPTION:
-- Prepares statements to insert objects and the data of objects that appear in the related tables
-- #PARAMETERS:
-- @ExcludedTables : String of table separated by commas that we want excluded from execution , by example 'ActionsLog'
-- @ExcludedObjects : String of table separated by commas that we want excluded from execution, by example 'sysUsers,sysSecObjectUser'
-- @OriginId identificador del origen para filtrar por el origen
-- #OBSERVATIONS:
-- Returns a temporary table with all the insert statements of all the database objects
-- #CHANGES:
--
-- #EXAMPLE:
-- Execute ZP_Extract_Objects 'ActionsLog', 'sysUsers,sysSecObjectUser'

-- =============================================


BEGIN TRY
SET NOCOUNT ON

DECLARE @NombreObjeto varchar(50)
DECLARE @TablaSql table (Sentencia VARCHAR(MAX), Tabla varchar(255), IdDoc int IDENTITY )
DECLARE @LsqlSearch nvarchar(max)
DECLARE @LsqlInsert Varchar(max )
DECLARE @Tabla varchar(255)
DECLARE @IdDoc int
DECLARE @CuentaReg int=0
DECLARE @CuentaRegOut int =0
DECLARE @ParmDefinition nvarchar(max)

IF OBJECT_ID ('TempDb..#TempCadenasInsercion') IS NOT NULL DROP TABLE #TempCadenasInsercion

CREATE TABLE #TempCadenasInsercion (Cadena Varchar(max), Tabla Varchar(255) , Objeto Varchar(50))
IF OBJECT_ID ('TempDb..#TempRelaciones') IS NOT NULL DROP TABLE #TempRelaciones
IF OBJECT_ID ('TempDb..#TempObjetos') IS NOT NULL DROP TABLE #TempObjetos

; WITH BusquedaDeRelaciones AS (

SELECT F.name FKName, object_name(f.referenced_object_id) TablaBuscada, SC.name CampoTablaBuscada, Object_name(f.Parent_Object_id) TablaEncontrada, sco.name CampoTablaEncontrado
FROM SYS.foreign_keys F
INNER JOIN sys.foreign_key_columns c on F.object_id=C.constraint_object_id AND object_name(f.referenced_object_id) ='Objects'
INNER JOIN sys.syscolumns SC ON F.referenced_object_id =Sc.id AND sc.name ='ObjectName' and sc.colid=C.referenced_column_id
INNER JOIN sys.syscolumns SCO ON F.parent_object_id =Sco.id AND sco.colid =C.parent_column_id

UNION

SELECT f.name FKname , Object_name(f.Parent_Object_id) TablaBuscada, sco.name CampoTablaBuscada, object_name(f.referenced_object_id) TablaEncontrada , SCD.name CampoTablaEncontrado
FROM SYS.foreign_keys F
INNER JOIN sys.foreign_key_columns c on F.object_id=C.constraint_object_id AND Object_name(f.parent_object_id )='Objects'
INNER JOIN sys.syscolumns SCO ON F.parent_object_id =SCO.id AND SCO.name ='ObjectName' and SCO.colid=C.parent_column_id
INNER JOIN sys.syscolumns SCD ON F.referenced_object_id =SCD.id and SCD.colid =C.referenced_column_id

),
Distintas AS (SELECT Distinct TablaEncontrada, CampoTablaEncontrado FROM BusquedaDeRelaciones)


SELECT C2.TablaEncontrada, CamposTablaEncontrado=
STUFF((SELECT N',' +C3.CampoTablaEncontrado
FROM Distintas C3
WHERE C2.TablaEncontrada =C3.TablaEncontrada
ORDER BY C3.TablaEncontrada
FOR XML PATH (N'')),1,1,N'')
INTO #TempRelaciones
FROM Distintas C2
GROUP BY C2.TablaEncontrada



-- Borrar las tablas excluidas
DELETE T FROM #TempRelaciones T INNER JOIN string_split (@ExcludedTables, ',') K ON T.TablaEncontrada =K.value

--- Insertar los objetos menos los excluidos.
SELECT ObjectName INTO #TempObjetos FROM Objects O WHERE NOT EXISTS (SELECT Value FROM string_split (@ExcludedObjects,',') T WHERE O.ObjectName =T.Value )


WHILE EXISTS (SELECT

ZP_Extract_Objects Stored

* FROM #TempObjetos ) BEGIN
--- Recorrido de objetos
SELECT TOP 1 @NombreObjeto =ObjectName FROM #TempObjetos

INSERT INTO @TABLASQL (Sentencia , Tabla )
SELECT N' SELECT* FROM ' + TablaEncontrada + ' WHERE ' + REPLACE (CamposTablaEncontrado,',','='''+@nombreobjeto + ''' OR ' ) + '= ''' + @NombreObjeto +'''' , TablaEncontrada from #TempRelaciones


WHILE Exists (SELECT * FROM @TablaSql) BEGIN
SELECT TOP 1 @LsqlSearch = N' SELECT @CuentaRegOut=COUNT(*) FROM ( ' + Sentencia + ') K' , @IdDoc =IdDoc,@Tabla =Tabla,@LsqlInsert =SENTENCIA FROM @tABLAsql
SET @ParmDefinition = N'@CuentaRegOut int OUTPUT'
EXECUTE sp_executesql
@LsqlSearch
,@ParmDefinition
,@CuentaRegOut = @CuentaReg OUTPUT;

IF @CuentaReg >0 BEGIN

SELECT @LsqlInsert =SUBSTRING (@LsqlInsert ,PATINDEX ('%FROM%',@LsqlInsert ), Len(@LsqlInsert ))

INSERT INTO #TempCadenasInsercion (Cadena )
EXEC sp_generate_inserts_with_exists @Table_name=@Tabla , @From=@LsqlInsert , @ommit_identity=1 --@cols_to_exclude='''InsertUpdate'',''Usuario'',''FechaInsertUpdate'''

UPDATE #TempCadenasInsercion SET Objeto =@NombreObjeto ,Tabla =@Tabla WHERE Objeto IS NULL AND Tabla IS NULL


END


DELETE FROM @TablaSql where IdDoc =@IdDoc
END
DELETE FROM #TempObjetos WHERE ObjectName =@NombreObjeto
SELECT @NombreObjeto =NULL
END
SELECT * from #TempCadenasInsercion
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0 BEGIN
ROLLBACK TRAN
END

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

RETURN 0

END CATCH

zReplace Stored

CREATE PROCEDURE dbo.zReplace
@stringToFind VARCHAR(100),
@stringToReplace VARCHAR(100),
@ExecuteUpdate bit,
@PrintResult bit
AS

SET NOCOUNT ON

DECLARE @schema sysname
DECLARE @table sysname
DECLARE @count INT
DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @where NVARCHAR(4000)
DECLARE @columnName sysname
DECLARE @object_id INT

DECLARE TAB_CURSOR CURSOR FOR
SELECT B.NAME AS SCHEMANAME,
A.NAME AS TABLENAME,
A.OBJECT_ID
FROM sys.objects A
INNER JOIN sys.schemas B
ON A.SCHEMA_ID = B.SCHEMA_ID
WHERE TYPE = 'U'
ORDER BY 1

OPEN TAB_CURSOR

FETCH NEXT FROM TAB_CURSOR
INTO @schema,
@table,
@object_id

WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE COL_CURSOR CURSOR FOR
SELECT A.NAME
FROM sys.columns A
INNER JOIN sys.types B
ON A.SYSTEM_TYPE_ID = B.SYSTEM_TYPE_ID
WHERE OBJECT_ID = @object_id
AND IS_COMPUTED = 0
AND B.NAME IN ('char','nchar','nvarchar','varchar','text','ntext')

OPEN COL_CURSOR

FETCH NEXT FROM COL_CURSOR
INTO @columnName

WHILE @@FETCH_STATUS = 0
BEGIN




SET @sqlCommand = 'SELECT @cnt=count(1) FROM ' + @schema + '.' + @table + ' WHERE [' + @columnName + '] LIKE ''%' + @stringToFind + '%'''

EXECUTE sp_executesql @sqlCommand, N'@cnt int OUTPUT', @cnt=@count OUTPUT

IF @count > 0 BEGIN

SET @sqlCommand = 'UPDATE ' + @schema + '.' + @table + ' SET [' + @columnName
+ '] = REPLACE(convert(nvarchar(max),[' + @columnName + ']),'''
+ @stringToFind + ''',''' + @stringToReplace + ''')'

SET @where = ' WHERE [' + @columnName + '] LIKE ''%' + @stringToFind + '%'''

IF @ExecuteUpdate=1 BEGIN
EXEC( @sqlCommand + @where)
SET @count = @@ROWCOUNT
END

IF @count > 0 and @PrintResult=1
BEGIN
PRINT @sqlCommand + @where
PRINT 'Updated: ' + CONVERT(VARCHAR(10),@count)
PRINT '----------------------------------------------------'
END
END

FETCH NEXT FROM COL_CURSOR
INTO @columnName
END

CLOSE COL_CURSOR
DEALLOCATE COL_CURSOR

FETCH NEXT FROM TAB_CURSOR
INTO @schema,
@table,
@object_id
END

CLOSE TAB_CURSOR
DEALLOCATE TAB_CURSOR

zScript Stored

CREATE PROCEDURE [dbo].[zScript]
@OriginId INT = null,
@OutputPath NVARCHAR(256) = NULL
AS
BEGIN TRY

DECLARE @tabla NVARCHAR(128)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @Count INT
DECLARE @Mode SMALLINT
DECLARE @msg table(msg nvarchar(max))
DECLARE @ExistsFile int, @Filepath nvarchar (max)
SET NOCOUNT ON

if @OriginId is null BEGIN
select @OriginId=OriginId from Origins where active=1
END

DECLARE curTablas CURSOR FOR
SELECT TableName,CompareMode FROM Configuration_Tables WHERE Autoscripting=1 and ((CompareMode = 1) OR (@OriginId=0))


IF LEN(ISNULL(@OutputPath,''))>0 BEGIN
SET @OutputPath=RTRIM(LTRIM(@OutputPath))
IF RIGHT(@OutputPath,1)<>N'\' SET @OutputPath=@OutputPath + N'\'
END


OPEN curTablas
FETCH NEXT FROM curTablas INTO @tabla,@Mode
WHILE @@FETCH_STATUS <> -1 BEGIN

SELECT @Filepath =@OutputPath + LOWER(@tabla) + '.sql'

SELECT @ExistsFile =dbo.fnet_fileExists (@Filepath )

SELECT @Count = 0

IF @Mode = 1
SELECT @SQL = N'SELECT @Count = COUNT(1) FROM ' + @tabla + N' WHERE OriginId = ' + CAST(@OriginId AS nvarchar(5))
ELSE
SELECT @SQL = N'SELECT @Count = COUNT(1) FROM ' + @tabla

EXEC sp_executesql @SQL, @Params = N'@Count INT OUTPUT', @Count = @Count OUTPUT

IF @Count>0 OR @ExistsFile<>0 BEGIN

IF @OutputPath IS NULL BEGIN

IF @Mode =1
SELECT @SQL = N'exec sp_generate_merge @results_to_text=1,@Table_Name = ''' + @tabla + N''', @From = ''FROM ' + @tabla + N' WHERE OriginId = ' + CAST(@OriginId AS nvarchar(5)) + N''', @OriginId = ' + CAST(@OriginId AS nvarchar(5))
ELSE
SELECT @SQL = N'exec sp_generate_merge @results_to_text=1,@Table_Name = ''' + @tabla + N''''

exec (@SQL)

END ELSE BEGIN

IF @Mode=1
SELECT @SQL = N'DECLARE @sql varchar(max);exec sp_generate_merge @ReturnSQL = 1, @OutputSQL = @sql OUTPUT, @Table_Name = ''' + @tabla + N''', @From = ''FROM ' + @tabla + N' WHERE OriginId = ' + CAST(@OriginId AS nvarchar(5)) + N''', @OriginId = ' + CAST(@OriginId AS nvarchar(5)) + N';SELECT @sql'
ELSE
SELECT @SQL = N'DECLARE @sql varchar(max);exec sp_generate_merge @ReturnSQL = 1, @OutputSQL = @sql OUTPUT, @Table_Name = ''' + @tabla + N''';SELECT @sql'
--- Carmen : 2019-09-03 Modificación para que si no existen registros pero si existe el fichero borre el contenido.
IF @Count =0 AND @ExistsFile <>0 SELECT @SQL ='Select '''' Line '

/*


-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE with override;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE with override;
GO
*/

DECLARE @OutputFile NVARCHAR(100)
SET @OutputFile = LOWER(@tabla) + '.sql'

declare @bcpCommand NVARCHAR(1000)

----Deleting file if exists
--set @bcpCommand = 'powershell -Command "If (Test-Path ''' + @outputpath + @outputfile + '''){Remove-Item ''' + @outputpath + @outputfile + '''}"'

--DELETE @Msg
--INSERT INTO @msg
--EXEC master.sys.xp_cmdshell @bcpCommand

--IF EXISTS(SELECT 1 FROM @Msg WHERE MSG LIKE '%ERROR%') BEGIN
-- SELECT @SQL=N'Error deleting file: ' + @Tabla+NCHAR(13)+NCHAR(10)
-- SELECT @SQL=@SQL + ISNULL(MSG,'') +NCHAR(13)+NCHAR(10) FROM @MSG
-- RAISERROR(@SQL,12,1)
--END

----Generating file

SET @bcpCommand = 'bcp "USE ' + DB_NAME() + ';' + @SQL + ' " queryout '
SET @bcpCommand = @bcpCommand + '"'+@outputPath + @OutputFile + '" -T -c -C 65001 -S'+ @@servername


DELETE @Msg
INSERT INTO @msg
EXEC master.sys.xp_cmdshell @bcpCommand

IF EXISTS(SELECT 1 FROM @Msg WHERE MSG LIKE '%ERROR%') BEGIN
SELECT @SQL=N'Error processing tabl

zScript Stored

e: ' + @Tabla+NCHAR(13)+NCHAR(10)
SELECT @SQL=@SQL + ISNULL(MSG,'') +NCHAR(13)+NCHAR(10) FROM @MSG
RAISERROR(@SQL,12,1)
END

----PowerShell script to add BOM mark to start of file

set @bcpCommand = 'powershell -Command "(239 -as [char])+(187 -as [char])+(191 -as [char])+(Get-Content -path ''' + @outputpath + @outputfile + ''' -Raw) | Set-Content ''' + @outputpath + @outputfile + ''' "'


DELETE @Msg
INSERT INTO @msg
EXEC master.sys.xp_cmdshell @bcpCommand

IF EXISTS(SELECT 1 FROM @Msg WHERE MSG IS NOT NULL) BEGIN
SELECT @SQL=N'Error encoding file: ' + @Tabla+NCHAR(13)+NCHAR(10)
SELECT @SQL=@SQL + ISNULL(MSG,'') +NCHAR(13)+NCHAR(10) FROM @MSG
RAISERROR(@SQL,12,1)
END


END
END


FETCH NEXT FROM curTablas INTO @tabla,@Mode
END


CLOSE curTablas
DEALLOCATE curTablas

RETURN 0

END TRY
BEGIN CATCH

DECLARE @CatchError NVARCHAR(MAX)
SET @CatchError=dbo.funPrintError(ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_PROCEDURE(),@@PROCID ,ERROR_LINE())
RAISERROR(@CatchError,12,1)

END CATCH

zSearch Stored

CREATE PROCEDURE [dbo].[zSearch]
@SearchStr NVARCHAR(60)
AS
BEGIN

set @SearchStr = concat('%',@SearchStr,'%')

exec SP_SearchTables '', @SearchStr, 0
END

ZSetCredentials Stored

CREATE PROCEDURE [dbo].[ZSetCredentials]
@ObjName nVarchar(255) ,
@MsjFinal Bit = 1
AS

-----------------------------------------------------------------
--DA PERMISOS PARA UN OBJETO A TODOS LOS GRUPOS DADOS DE ALTA
-- Da permisos a todos los grupos excepto el Public
-----------------------------------------------------------------

DECLARE @Grupo Varchar(100)
DECLARE @Msg Varchar(255)
DECLARE @ListaGrupos Varchar(255)
DECLARE @Type varchar(3)
DECLARE @P0 nvarchar(1000)
DECLARE @P1 nvarchar(1000)
DECLARE @CadenaStr nvarchar(4000)
DECLARE @EsTipo bit

IF NOT EXISTS
(SELECT * FROM SysObjects WHERE Name=@ObjName And Type in ('P', 'U', 'V','FN','TF','IF')) -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
BEGIN
IF NOT EXISTS
(SELECT * FROM SysTypes WHERE Name = @ObjName)
BEGIN
PRINT 'Impossible to assign credentials to this object'
RETURN 0
END ELSE
SET @Type = 'UDT' -- NO_TRADUCIR_TAG
END
ELSE
SELECT @Type=Type FROM SysObjects WHERE Name=@ObjName


DECLARE Grupos CURSOR FOR
--SELECT Name FROM SysUsers WHERE Uid=Gid And Gid<>0
SELECT name FROM sys.database_principals WHERE type='R' AND is_fixed_role=0
OPEN Grupos

SELECT @ListaGrupos=''
FETCH NEXT FROM Grupos INTO @Grupo
WHILE @@FETCH_STATUS<>-1 BEGIN

IF @Type='U' OR @Type='V'
EXECUTE (N'GRANT DELETE, INSERT, REFERENCES, SELECT,VIEW DEFINITION, UPDATE ON [' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG
IF @Type='P'
EXECUTE (N'GRANT EXECUTE ON [' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
IF @Type='FN' -- NO_TRADUCIR_TAG
EXECUTE (N'GRANT EXECUTE, REFERENCES ON [' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG -- NO_TRADUCIR_TAG
IF @Type='TF' OR @Type='IF' -- NO_TRADUCIR_TAG
EXECUTE (N'GRANT REFERENCES, SELECT ON [' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG
IF @Type='UDT' BEGIN-- NO_TRADUCIR_TAG
EXECUTE (N'GRANT REFERENCES ON TYPE::[' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG
EXECUTE (N'GRANT EXECUTE ON TYPE::[' + @ObjName + '] TO ' + @Grupo) -- NO_TRADUCIR_TAG
END

IF @@ERROR<>0 BEGIN
--SELECT @Msg='Error asignando permisos al grupo: '+ @Grupo
SET @P0 = @Grupo
SET @CadenaStr = 'Error assigning Credential to group: %v'
exec sprintf @Msg OUT, @CadenaStr, @P0

PRINT @Msg
END
SELECT @ListaGrupos= @ListaGrupos + ' -- ' + @Grupo

FETCH NEXT FROM Grupos INTO @Grupo
END

CLOSE Grupos
DEALLOCATE Grupos

IF @MsjFinal=1 BEGIN
SELECT @ListaGrupos= @ListaGrupos + ' -- '
--SELECT @Msg='Permisos asignados para el objeto: ' + @ObjName + ' en los grupos: ' + @ListaGrupos
SET @P0 = @ObjName
SET @P1 = @ListaGrupos
SET @CadenaStr = 'Credentials assigned to object: %v for roles: %v'
exec sprintf @Msg OUT, @CadenaStr, @P0, @P1

PRINT @Msg
END
RETURN -1

ZSetCredentialsToEverything Stored

CREATE PROCEDURE [dbo].[ZSetCredentialsToEverything]
AS

-----------------------------------------------------------------
-- ASIGNA PERMISOS A TODOS LOS OBJETOS
-----------------------------------------------------------------


DECLARE @Select Varchar(255)
DECLARE @Msg Varchar(255)
DECLARE @Tabla nVarchar(100)

DECLARE @Prt nvarchar(4000)
DECLARE @P0 nvarchar(1000)
DECLARE @CadenaStr nvarchar(4000)



-------------------------------
-- Obtencion de las tablas
-------------------------------
DECLARE Tablas INSENSITIVE CURSOR FOR
SELECT name
FROM sys.objects
WHERE name not in ('sysconstraints','syssegments') AND (Type='U' OR Type ='V' OR Type='P' OR Type ='FN' or Type ='TF' or Type ='IF') -- NO_TRADUCIR_TAG
UNION
SELECT name
FROM sys.types
WHERE is_user_defined=1 -- name LIKE 'T[_]%'

OPEN Tablas
FETCH NEXT FROM Tablas INTO @Tabla
WHILE @@FETCH_STATUS<>-1 BEGIN

--SELECT @Select = 'Permisos asignados a:' + @Tabla
EXEC('ZSetCredentials N''' + @Tabla +'''' ) -- NO_TRADUCIR_TAG
IF @@ERROR<>0 BEGIN
--PRINT 'Error en Objeto '''+@tabla+''''
SET @P0 = @tabla
SET @CadenaStr = 'Error in Object ''%v'''
exec sprintf @Prt OUT, @CadenaStr, @P0
PRINT @Prt
END

--print @Select
FETCH NEXT FROM Tablas INTO @Tabla
END
CLOSE Tablas
DEALLOCATE Tablas

zSQL_OPT_GetForeingKeysWithoutIndex Stored



CREATE PROCEDURE zSQL_OPT_GetForeingKeysWithoutIndex
AS
BEGIN

SET NOCOUNT ON;

;WITH Alerts (TheTable,Descrip,rowcnt,cols)
AS (SELECT OBJECT_NAME(keys.Parent_Object_ID) AS TheTable,
keys.Name AS Descrip,ssir.rowcnt,col.name
FROM sys.foreign_keys keys
INNER JOIN sys.foreign_key_columns TheColumns
ON keys.Object_ID = constraint_object_id
LEFT OUTER JOIN sys.index_columns ic
ON ic.object_ID = TheColumns.parent_Object_Id
AND ic.column_ID = TheColumns.parent_Column_Id
AND TheColumns.constraint_column_ID = ic.key_ordinal
inner join sys.columns col on col.object_id=TheColumns.parent_object_id and col.column_id=TheColumns.parent_column_id
left join sys.indexes sir on keys.referenced_object_id = sir.object_id and sir.is_primary_key = 1
left join sys.sysindexes ssir on sir.object_id = ssir.id and sir.index_id = ssir.indid
WHERE ic.object_ID IS NULL)


Select distinct TheTable,Descrip,rowcnt, left(S,len(s)-1) as cols,
'CREATE NONCLUSTERED INDEX [Idx_'+TheTable+'_'+replace(left(S,len(s)-1),',','_')+'] ON [dbo].['+TheTable+'] ('+left(S,len(s)-1)+') WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] '+char(13)+char(10)+'GO'+char(13)+char(10) as Script
from
(SELECT TheTable,Descrip,rowcnt,replace(replace(convert(varchar(max),(SELECT convert(varchar(max),cols)
FROM Alerts A
WHERE A.Descrip = B.Descrip
FOR XML PATH('cols'), TYPE)),'<cols>',''),'</cols>',',') S
FROM Alerts B) Oper
order by rowcnt desc

END

zSQL_OPT_GetHeaps Stored



CREATE PROCEDURE zSQL_OPT_GetHeaps
AS
BEGIN

SET NOCOUNT ON;

SELECT DISTINCT OBJECT_SCHEMA_NAME(t.Object_ID) + '.'
+ OBJECT_NAME(t.Object_ID) AS TheTable, 'heap' AS smell
FROM sys.indexes /* see whether the table is a heap */
INNER JOIN sys.tables t ON t.object_ID = sys.indexes.object_ID
WHERE sys.indexes.type = 0;


END