Example #1
0
        public Error.Types Update(
            SiteSettings ss,
            IEnumerable <string> permissions = null,
            bool permissionChanged           = false,
            RdsUser rdsUser          = null,
            SqlParamCollection param = null,
            List <SqlStatement> additionalStatements = null,
            bool paramAll = false,
            bool get      = true)
        {
            SetBySession();
            var timestamp  = Timestamp.ToDateTime();
            var statements = new List <SqlStatement>();

            UpdateStatements(statements, timestamp, param, paramAll, additionalStatements);
            var count = Rds.ExecuteScalar_int(
                rdsUser: rdsUser,
                transactional: true,
                statements: statements.ToArray());

            if (count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            if (get)
            {
                Get(ss);
            }
            SiteInfo.Reflesh();
            return(Error.Types.None);
        }
 /// <summary>
 /// Fixed:
 /// </summary>
 public void Approval(Context context)
 {
     Rds.ExecuteScalar_response(
         context: context,
         transactional: true,
         selectIdentity: true,
         statements: new SqlStatement[]
     {
         Rds.InsertUsers(
             selectIdentity: true,
             param: Rds.UsersParam()
             .TenantId(TenantId)
             .LoginId(LoginId)
             .Password(Password)
             .Name(Name)
             .Language(Language)
             ),
         Rds.InsertMailAddresses(
             param: Rds.MailAddressesParam()
             .OwnerId(raw: Def.Sql.Identity)
             .OwnerType("Users")
             .MailAddress(MailAddress))
     }).Id.ToInt();
     SiteInfo.Reflesh(
         context: context,
         force: true);
 }
 /// <summary>
 /// Fixed:
 /// </summary>
 public static void CreateInBackground()
 {
     if (Parameters.BackgroundTask.Enabled)
     {
         var hash = new Dictionary <long, SiteModel>();
         Rds.ExecuteTable(statements: Rds.SelectItems(
                              column: Rds.ItemsColumn()
                              .ReferenceId()
                              .SiteId()
                              .Updator()
                              .UpdatedTime(),
                              where : Rds.ItemsWhere().Add(
                                  raw: "[SearchIndexCreatedTime] is null or [SearchIndexCreatedTime]<>[UpdatedTime]"),
                              top: Parameters.BackgroundTask.CreateSearchIndexLot))
         .AsEnumerable()
         .Select(o => new
         {
             ReferenceId = o["ReferenceId"].ToLong(),
             SiteId      = o["SiteId"].ToLong(),
             Updator     = o["Updator"].ToInt(),
             UpdatedTime = o.Field <DateTime>("UpdatedTime")
                           .ToString("yyyy/M/d H:m:s.fff")
         })
         .ForEach(data =>
         {
             var siteModel = hash.Get(data.SiteId) ??
                             new SiteModel().Get(where : Rds.SitesWhere().SiteId(data.SiteId));
             System.Web.HttpContext.Current.Session["TenantId"] =
                 siteModel.TenantId;
             System.Web.HttpContext.Current.Session["RdsUser"] =
                 Rds.ExecuteTable(statements: Rds.SelectUsers(
                                      column: Rds.UsersColumn().UserId().DeptId(),
                                      where : Rds.UsersWhere().UserId(data.Updator)))
                 .AsEnumerable()
                 .Select(o => new RdsUser()
             {
                 DeptId = o["DeptId"].ToInt(),
                 UserId = o["UserId"].ToInt()
             })
                 .FirstOrDefault();
             if (!SiteInfo.TenantCaches.ContainsKey(Sessions.TenantId()))
             {
                 SiteInfo.Reflesh();
             }
             if (!hash.ContainsKey(data.SiteId))
             {
                 siteModel.SiteSettings = SiteSettingsUtilities.Get(
                     siteModel, siteModel.SiteId);
                 hash.Add(data.SiteId, siteModel);
             }
             Libraries.Search.Indexes.Create(
                 siteModel.SiteSettings, data.ReferenceId, force: true);
             Rds.ExecuteNonQuery(statements: Rds.UpdateItems(
                                     where : Rds.ItemsWhere().ReferenceId(data.ReferenceId),
                                     param: Rds.ItemsParam().SearchIndexCreatedTime(data.UpdatedTime),
                                     addUpdatorParam: false,
                                     addUpdatedTimeParam: false));
         });
     }
 }
 /// <summary>
 /// Fixed:
 /// </summary>
 private void SetSiteInfo()
 {
     SiteInfo.Reflesh();
     if (Self())
     {
         SetSession();
     }
 }
        public Error.Types Update(
            SiteSettings ss,
            IEnumerable <string> permissions = null,
            bool permissionChanged           = false,
            bool extendedSqls                  = true,
            bool synchronizeSummary            = true,
            bool forceSynchronizeSourceSummary = false,
            bool notice              = false,
            RdsUser rdsUser          = null,
            SqlParamCollection param = null,
            List <SqlStatement> additionalStatements = null,
            bool paramAll = false,
            bool get      = true)
        {
            if (Contract.Notice() && notice)
            {
                CheckNotificationConditions(ss, before: true);
            }
            SetBySession();
            var timestamp  = Timestamp.ToDateTime();
            var statements = new List <SqlStatement>();

            if (extendedSqls)
            {
                statements.OnUpdatingExtendedSqls(SiteId, WikiId, timestamp);
            }
            UpdateStatements(statements, timestamp, param, paramAll, additionalStatements);
            if (permissionChanged)
            {
                statements.UpdatePermissions(ss, WikiId, permissions);
            }
            var count = Rds.ExecuteScalar_int(
                rdsUser: rdsUser,
                transactional: true,
                statements: statements.ToArray());

            if (count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            if (Contract.Notice() && notice)
            {
                CheckNotificationConditions(ss);
                Notice(ss, "Updated");
            }
            if (get)
            {
                Get(ss);
            }
            UpdateRelatedRecords(ss, extendedSqls);
            if (get && Rds.ExtendedSqls(SiteId, WikiId)?.Any(o => o.OnUpdated) == true)
            {
                Get(ss);
            }
            SiteInfo.Reflesh();
            return(Error.Types.None);
        }
Example #6
0
        private void InitializeLog()
        {
            var log = new SysLogModel();

            SiteInfo.TenantCaches.Add(0, new TenantCache(0));
            SiteInfo.Reflesh();
            UsersInitializer.Initialize();
            ItemsInitializer.Initialize();
            StatusesMigrator.Migrate();
            SiteSettingsMigrator.Migrate();
            StatusesInitializer.Initialize();
            log.Finish();
        }
        protected void Application_Start()
        {
            Initialize();
            Context context = ApplicationStartContext();
            var     log     = new SysLogModel(context: context);

            UsersInitializer.Initialize(context: context);
            StatusesMigrator.Migrate(context: context);
            StatusesInitializer.Initialize(context: context);
            SetConfigrations();
            SiteInfo.Reflesh(context: context);
            log.Finish(context: context);
        }
Example #8
0
        private void InitializeLog()
        {
            ContextImplement context = ApplicationStartContext();
            var log = new SysLogModel(context: context);

            UsersInitializer.Initialize(context: context);
            ItemsInitializer.Initialize(context: context);
            StatusesMigrator.Migrate(context: context);
            SiteSettingsMigrator.Migrate(context: context);
            StatusesInitializer.Initialize(context: context);
            SetConfigrations(context: context);
            SiteInfo.Reflesh(context: context);
            log.Finish(context: context);
        }
Example #9
0
 public void SetTenantCaches()
 {
     if (TenantId != 0 && !SiteInfo.TenantCaches.ContainsKey(TenantId))
     {
         try
         {
             SiteInfo.TenantCaches.Add(TenantId, new TenantCache(context: this));
             SiteInfo.Reflesh(context: this);
         }
         catch (Exception)
         {
         }
     }
 }
Example #10
0
        /// <summary>
        /// Fixed:
        /// </summary>
        private static void Initialize(
            this DemoModel demoModel,
            Context context,
            Dictionary <string, long> idHash,
            string password)
        {
            demoModel.InitializeTimeLag();
            InitializeDepts(
                context: context,
                demoModel: demoModel,
                idHash: idHash);
            InitializeUsers(
                context: context,
                demoModel: demoModel,
                idHash: idHash,
                password: password);
            var userModel = new UserModel(
                context: context,
                ss: SiteSettingsUtilities.UsersSiteSettings(context: context),
                loginId: LoginId(demoModel, "User1"));

            userModel.SetSession();
            context.SetBySession();
            SiteInfo.Reflesh(context: context);
            InitializeSites(context: context, demoModel: demoModel, idHash: idHash);
            Def.DemoDefinitionCollection
            .Where(o => o.Type == "Sites")
            .OrderBy(o => o.Id)
            .ForEach(o =>
            {
                InitializeIssues(
                    context: context, demoModel: demoModel, parentId: o.Id, idHash: idHash);
                InitializeResults(
                    context: context, demoModel: demoModel, parentId: o.Id, idHash: idHash);
            });
            InitializeLinks(
                context: context,
                demoModel: demoModel,
                idHash: idHash);
            InitializePermissions(
                context: context,
                idHash: idHash);
            Rds.ExecuteNonQuery(
                context: context,
                statements: Rds.UpdateDemos(
                    param: Rds.DemosParam().Initialized(true),
                    where : Rds.DemosWhere().Passphrase(demoModel.Passphrase)));
            Libraries.Migrators.SiteSettingsMigrator.Migrate(context: context);
        }
Example #11
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var context = new Context(
                sessionStatus: false,
                sessionData: false,
                item: false);

            if (context.Controller != "errors" && Parameters.SyntaxErrors?.Any() == true)
            {
                filterContext.Result = new RedirectResult(
                    Locations.ParameterSyntaxError(context: context));
            }
            if (context.Authenticated &&
                !context.ContractSettings.AllowedIpAddress(context.UserHostAddress))
            {
                Authentications.SignOut(context: context);
                filterContext.Result = new RedirectResult(
                    Locations.InvalidIpAddress(context: context));
                return;
            }
            if (context.Authenticated &&
                context.ContractSettings.OverDeadline(context: context))
            {
                Authentications.SignOut(context: context);
                filterContext.Result = new RedirectResult(
                    Locations.Login(context: context) + "?expired=1");
                return;
            }
            if (!context.LoginId.IsNullOrEmpty())
            {
                if (!context.Authenticated)
                {
                    if (Authentications.Windows())
                    {
                        filterContext.Result = new EmptyResult();
                        return;
                    }
                    else
                    {
                        Authentications.SignOut(context: context);
                        filterContext.Result = new RedirectResult(
                            Locations.Login(context: context));
                        return;
                    }
                }
            }
            SiteInfo.Reflesh(context: context);
        }
Example #12
0
        protected void Application_Start()
        {
            Application["StartTime"]      = DateTime.Now;
            Application["LastAccessTime"] = Application["StartTime"];
            Initialize();
            var log = new SysLogModel();

            SiteInfo.TenantCaches.Add(0, new TenantCache(0));
            SiteInfo.Reflesh();
            UsersInitializer.Initialize();
            ItemsInitializer.Initialize();
            StatusesMigrator.Migrate();
            SiteSettingsMigrator.Migrate();
            StatusesInitializer.Initialize();
            SetConfigrations();
            log.Finish();
        }
Example #13
0
        public Error.Types Update(
            SiteSettings ss,
            IEnumerable <string> permissions   = null,
            bool permissionChanged             = false,
            bool synchronizeSummary            = true,
            bool forceSynchronizeSourceSummary = false,
            bool notice              = false,
            RdsUser rdsUser          = null,
            SqlParamCollection param = null,
            bool paramAll            = false,
            bool get = true)
        {
            if (Contract.Notice() && notice)
            {
                CheckNotificationConditions(ss, before: true);
            }
            SetBySession();
            var statements = UpdateStatements(param, paramAll);

            if (permissionChanged)
            {
                statements.UpdatePermissions(ss, WikiId, permissions);
            }
            var count = Rds.ExecuteScalar_int(
                rdsUser: rdsUser,
                transactional: true,
                statements: statements.ToArray());

            if (count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            if (Contract.Notice() && notice)
            {
                CheckNotificationConditions(ss);
                Notice(ss, "Updated");
            }
            if (get)
            {
                Get(ss);
            }
            UpdateRelatedRecords(ss);
            SiteInfo.Reflesh();
            return(Error.Types.None);
        }
Example #14
0
        public ErrorData Update(
            Context context,
            SiteSettings ss,
            IEnumerable <string> permissions         = null,
            bool permissionChanged                   = false,
            SqlParamCollection param                 = null,
            List <SqlStatement> additionalStatements = null,
            bool otherInitValue = false,
            bool setBySession   = true,
            bool get            = true)
        {
            if (setBySession)
            {
                SetBySession(context: context);
            }
            var statements = new List <SqlStatement>();

            statements.AddRange(UpdateStatements(
                                    context: context,
                                    ss: ss,
                                    permissions: permissions,
                                    permissionChanged: permissionChanged,
                                    param: param,
                                    otherInitValue: otherInitValue,
                                    additionalStatements: additionalStatements));
            var response = Repository.ExecuteScalar_response(
                context: context,
                transactional: true,
                statements: statements.ToArray());

            if (response.Event == "Conflicted")
            {
                return(new ErrorData(
                           type: Error.Types.UpdateConflicts,
                           id: DeptId));
            }
            if (get)
            {
                Get(context: context, ss: ss);
            }
            SiteInfo.Reflesh(
                context: context,
                force: true);
            return(new ErrorData(type: Error.Types.None));
        }
Example #15
0
        protected void Application_Start()
        {
            Initialize();
            Context context = new Context(tenantId: 0)
            {
                Controller = "Global.asax",
                Action     = "Application_Start",
            };
            var log = new SysLogModel(context: context);

            ExtensionInitializer.Initialize(context: context);
            UsersInitializer.Initialize(context: context);
            StatusesMigrator.Migrate(context: context);
            StatusesInitializer.Initialize(context: context);
            NotificationInitializer.Initialize();
            SetConfigrations();
            SiteInfo.Reflesh(context: context);
            log.Finish(context: context);
        }
Example #16
0
        public Error.Types Update(
            Context context,
            SiteSettings ss,
            IEnumerable <string> permissions = null,
            bool permissionChanged           = false,
            RdsUser rdsUser          = null,
            SqlParamCollection param = null,
            List <SqlStatement> additionalStatements = null,
            bool otherInitValue = false,
            bool setBySession   = true,
            bool get            = true)
        {
            if (setBySession)
            {
                SetBySession(context: context);
            }
            var timestamp  = Timestamp.ToDateTime();
            var statements = new List <SqlStatement>();

            UpdateStatements(
                context: context,
                ss: ss,
                statements: statements,
                timestamp: timestamp,
                param: param,
                otherInitValue: otherInitValue,
                additionalStatements: additionalStatements);
            var response = Rds.ExecuteScalar_response(
                context: context,
                transactional: true,
                statements: statements.ToArray());

            if (response.Count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            if (get)
            {
                Get(context: context, ss: ss);
            }
            SiteInfo.Reflesh(context: context);
            return(Error.Types.None);
        }
Example #17
0
        /// <summary>
        /// Fixed:
        /// </summary>
        public static bool Login(Context context)
        {
            var demoModel = new DemoModel().Get(
                context: context,
                where : Rds.DemosWhere()
                .Passphrase(QueryStrings.Data("passphrase"))
                .CreatedTime(
                    DateTime.Now.AddDays(Parameters.Service.DemoUsagePeriod * -1),
                    _operator: ">="));

            if (demoModel.AccessStatus == Databases.AccessStatuses.Selected)
            {
                var loginId  = LoginId(demoModel, "User1");
                var password = Strings.NewGuid().Sha512Cng();
                if (!demoModel.Initialized)
                {
                    var idHash = new Dictionary <string, long>();
                    demoModel.Initialize(context: context, idHash: idHash, password: password);
                }
                else
                {
                    Rds.ExecuteNonQuery(
                        context: context,
                        statements: Rds.UpdateUsers(
                            param: Rds.UsersParam().Password(password),
                            where : Rds.UsersWhere().LoginId(loginId)));
                }
                new UserModel()
                {
                    LoginId  = loginId,
                    Password = password
                }.Authenticate(
                    context: context,
                    returnUrl: string.Empty);
                SiteInfo.Reflesh(context: context, force: true);
                return(Sessions.LoggedIn());
            }
            else
            {
                return(false);
            }
        }
 /// <summary>
 /// Fixed:
 /// </summary>
 private static void Initialize(
     this DemoModel demoModel, Dictionary <string, long> idHash, string password)
 {
     demoModel.InitializeTimeLag();
     InitializeDepts(demoModel, idHash);
     InitializeUsers(demoModel, idHash, password);
     SiteInfo.Reflesh(force: true);
     InitializeSites(demoModel, idHash);
     Def.DemoDefinitionCollection
     .Where(o => o.Type == "Sites")
     .OrderBy(o => o.Id)
     .ForEach(o =>
     {
         InitializeIssues(demoModel, o.Id, idHash);
         InitializeResults(demoModel, o.Id, idHash);
     });
     InitializeLinks(demoModel, idHash);
     InitializePermissions(idHash);
     Rds.ExecuteNonQuery(statements: Rds.UpdateDemos(
                             param: Rds.DemosParam().Initialized(true),
                             where : Rds.DemosWhere().Passphrase(demoModel.Passphrase)));
     Libraries.Migrators.SiteSettingsMigrator.Migrate();
 }
Example #19
0
        public Error.Types Update(
            SiteSettings ss,
            IEnumerable <string> permissions = null,
            bool permissionChanged           = false,
            RdsUser rdsUser          = null,
            SqlParamCollection param = null,
            bool paramAll            = false)
        {
            SetBySession();
            var statements = UpdateStatements(param, paramAll);
            var count      = Rds.ExecuteScalar_int(
                rdsUser: rdsUser,
                transactional: true,
                statements: statements.ToArray());

            if (count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            Get(ss);
            SiteInfo.Reflesh();
            return(Error.Types.None);
        }
Example #20
0
 public void OnAuthorization(AuthorizationContext filterContext)
 {
     SiteInfo.Reflesh();
 }
Example #21
0
        public Error.Types Update(
            Context context,
            SiteSettings ss,
            IEnumerable <string> permissions = null,
            bool permissionChanged           = false,
            bool extendedSqls                  = true,
            bool synchronizeSummary            = true,
            bool forceSynchronizeSourceSummary = false,
            bool notice = false,
            SqlParamCollection param = null,
            List <SqlStatement> additionalStatements = null,
            bool otherInitValue = false,
            bool setBySession   = true,
            bool get            = true)
        {
            if (context.ContractSettings.Notice != false && notice)
            {
                CheckNotificationConditions(context: context, ss: ss, before: true);
            }
            if (setBySession)
            {
                SetBySession(context: context);
            }
            var timestamp  = Timestamp.ToDateTime();
            var statements = new List <SqlStatement>();

            if (extendedSqls)
            {
                statements.OnUpdatingExtendedSqls(SiteId, WikiId, timestamp);
            }
            UpdateStatements(
                context: context,
                ss: ss,
                statements: statements,
                timestamp: timestamp,
                param: param,
                otherInitValue: otherInitValue,
                additionalStatements: additionalStatements);
            if (permissionChanged)
            {
                statements.UpdatePermissions(context, ss, WikiId, permissions);
            }
            var response = Rds.ExecuteScalar_response(
                context: context,
                transactional: true,
                statements: statements.ToArray());

            if (response.Count == 0)
            {
                return(Error.Types.UpdateConflicts);
            }
            if (Title_Updated(context: context))
            {
                Rds.ExecuteNonQuery(
                    context: context,
                    statements: new SqlStatement[]
                {
                    Rds.UpdateSites(
                        where : Rds.SitesWhere()
                        .TenantId(context.TenantId)
                        .SiteId(SiteId),
                        param: Rds.SitesParam().Title(Title.Value),
                        addUpdatedTimeParam: false,
                        addUpdatorParam: false),
                    StatusUtilities.UpdateStatus(
                        tenantId: context.TenantId,
                        type: StatusUtilities.Types.SitesUpdated)
                });
            }
            if (context.ContractSettings.Notice != false && notice)
            {
                CheckNotificationConditions(context: context, ss: ss);
                Notice(context: context, ss: ss, type: "Updated");
            }
            if (get)
            {
                Get(context: context, ss: ss);
            }
            UpdateRelatedRecords(context: context, ss: ss, extendedSqls: extendedSqls);
            if (get && Rds.ExtendedSqls(SiteId, WikiId)?.Any(o => o.OnUpdated) == true)
            {
                Get(context: context, ss: ss);
            }
            SiteInfo.Reflesh(context: context);
            return(Error.Types.None);
        }
        public static string ImportSitePackage(
            Context context,
            SiteSettings ss,
            SitePackageApiModel apiData = null)
        {
            var includeData = Parameters.SitePackage.IncludeDataOnImport != OptionTypes.Disabled &&
                              (apiData?.SelectedSites.Any(site => site.IncludeData == true)
                               ?? context.Forms.Bool("IncludeData"));
            var includeSitePermission = Parameters.SitePackage.IncludeSitePermissionOnImport != OptionTypes.Disabled &&
                                        (apiData?.IncludeSitePermission
                                         ?? context.Forms.Bool("IncludeSitePermission"));
            var includeRecordPermission = Parameters.SitePackage.IncludeRecordPermissionOnImport != OptionTypes.Disabled &&
                                          (apiData?.IncludeRecordPermission
                                           ?? context.Forms.Bool("IncludeRecordPermission"));
            var includeColumnPermission = Parameters.SitePackage.IncludeColumnPermissionOnImport != OptionTypes.Disabled &&
                                          (apiData?.IncludeColumnPermission
                                           ?? context.Forms.Bool("IncludeColumnPermission"));
            var includeNotifications = Parameters.SitePackage.IncludeNotificationsOnImport != OptionTypes.Disabled &&
                                       (apiData?.IncludeNotifications
                                        ?? context.Forms.Bool("IncludeNotifications"));
            var includeReminders = Parameters.SitePackage.IncludeRemindersOnImport != OptionTypes.Disabled &&
                                   (apiData?.IncludeReminders
                                    ?? context.Forms.Bool("IncludeReminders"));

            if (ss.SiteId == 0)
            {
                ss.PermissionType = context.SiteTopPermission();
            }
            if (!Parameters.SitePackage.Import ||
                !context.CanManageSite(ss: ss))
            {
                return(Messages.ResponseInvalidRequest(context: context).ToJson());
            }
            if (includeData && context.ContractSettings.Import == false)
            {
                return(Messages.ResponseInvalidRequest(context: context).ToJson());
            }
            var sitePackage = apiData == null
                ? GetSitePackageFromPostedFile(context : context)
                : GetSitePackage(
                context: context,
                ss: ss,
                apiData: apiData);

            if (sitePackage == null)
            {
                return(Messages.ResponseInvalidRequest(context: context).ToJson());
            }
            if (context.ContractSettings.SitesLimit(
                    context: context,
                    number: sitePackage.Sites.Count()))
            {
                return(Messages.ResponseSitesLimit(context: context).ToJson());
            }
            if (includeData)
            {
                if (Parameters.General.ImportMax > 0 &&
                    Parameters.General.ImportMax < sitePackage.Data
                    .SelectMany(o => o.Body)
                    .Count())
                {
                    return(Messages.ResponseImportMax(
                               context: context,
                               data: Parameters.General.ImportMax.ToString())
                           .ToJson());
                }
                if (sitePackage.Data.Any(o => o.Header.Any(p =>
                                                           context.ContractSettings.ItemsLimit(
                                                               context: context,
                                                               siteId: p.SiteId,
                                                               number: o.Body.Count()))))
                {
                    return(Messages.ResponseItemsLimit(
                               context: context,
                               data: Parameters.General.ImportMax.ToString())
                           .ToJson());
                }
            }
            sitePackage.ConvertInheritPermissionInNotIncluded();
            sitePackage.HeaderInfo.SavedBaseSiteId = apiData?.TargetSiteId
                                                     ?? context.SiteId;
            sitePackage.HeaderInfo.SavedInheritPermission = ss.InheritPermission;
            foreach (var conv in sitePackage.HeaderInfo.Convertors)
            {
                conv.SiteTitle = conv.SiteId == sitePackage.HeaderInfo.BaseSiteId &&
                                 !String.IsNullOrEmpty(apiData?.SiteTitle)
                        ? apiData.SiteTitle
                        : conv.SiteTitle;
                var response = Repository.ExecuteScalar_response(
                    context: context,
                    transactional: true,
                    selectIdentity: true,
                    statements: new SqlStatement[]
                {
                    Rds.InsertItems(
                        selectIdentity: true,
                        param: Rds.ItemsParam()
                        .ReferenceType("Sites")
                        .Title(conv.SiteTitle)),
                    Rds.UpdateItems(
                        where : Rds.ItemsWhere().ReferenceId(raw: Def.Sql.Identity),
                        param: Rds.ItemsParam().SiteId(raw: Def.Sql.Identity)),
                });
                conv.SavedSiteId = response.Id;
            }
            foreach (var conv in sitePackage.HeaderInfo.Convertors)
            {
                var packageSiteModel = sitePackage.Sites
                                       .Where(e => e.SiteId == conv.SiteId)
                                       .FirstOrDefault();
                packageSiteModel.SetSavedIds(
                    context: context,
                    ss: ss,
                    sitePackage: sitePackage,
                    savedSiteId: conv.SavedSiteId.ToLong(),
                    includeSitePermission: includeSitePermission &&
                    sitePackage.HeaderInfo.IncludeSitePermission);
                packageSiteModel.SiteSettings = packageSiteModel.GetSavedSiteSettings(
                    context: context,
                    header: sitePackage.HeaderInfo,
                    includeColumnPermission: includeColumnPermission,
                    permissionIdList: sitePackage.PermissionIdList,
                    includeNotifications: includeNotifications,
                    includeReminders: includeReminders);
                Repository.ExecuteScalar_response(
                    context: context,
                    transactional: true,
                    statements: new SqlStatement[]
                {
                    Rds.InsertSites(param: Rds.SitesParam()
                                    .SiteId(packageSiteModel.SavedSiteId)
                                    .TenantId(packageSiteModel.SavedTenantId)
                                    .Title(conv.SiteTitle)
                                    .Body(packageSiteModel.Body)
                                    .GridGuide(packageSiteModel.GridGuide)
                                    .EditorGuide(packageSiteModel.EditorGuide)
                                    .ReferenceType(packageSiteModel.ReferenceType.MaxLength(32))
                                    .ParentId(packageSiteModel.SavedParentId)
                                    .InheritPermission(packageSiteModel.SavedInheritPermission)
                                    .SiteSettings(packageSiteModel.SiteSettings.ToJson())
                                    .Publish(packageSiteModel.Publish)
                                    .DisableCrossSearch(packageSiteModel.DisableCrossSearch)
                                    .Comments(packageSiteModel.Comments.ToJson())),
                    Rds.PhysicalDeleteLinks(
                        where : Rds.LinksWhere().SourceId(packageSiteModel.SavedSiteId)),
                    LinkUtilities.Insert(link: packageSiteModel.SiteSettings.Links
                                         ?.Where(o => o.SiteId > 0)
                                         .Select(o => o.SiteId)
                                         .Distinct()
                                         .ToDictionary(o => o, o => packageSiteModel.SavedSiteId)
                                         ?? new Dictionary <long, long>()),
                    Rds.InsertPermissions(
                        param: Rds.PermissionsParam()
                        .ReferenceId(packageSiteModel.SavedSiteId)
                        .DeptId(0)
                        .UserId(context.UserId)
                        .PermissionType(Permissions.Manager()),
                        _using: packageSiteModel.SavedInheritPermission == packageSiteModel.SavedSiteId),
                });
                var siteModel = new SiteModel(
                    context: context,
                    siteId: packageSiteModel.SavedSiteId);
                var fullText = siteModel.FullText(
                    context: context,
                    ss: siteModel.SiteSettings);
                Repository.ExecuteNonQuery(
                    context: context,
                    transactional: true,
                    statements: Rds.UpdateItems(
                        where : Rds.ItemsWhere()
                        .ReferenceId(packageSiteModel.SavedSiteId),
                        param: Rds.ItemsParam()
                        .FullText(fullText, _using: fullText != null)
                        .SearchIndexCreatedTime(DateTime.Now, _using: fullText != null)));
            }
            var idHash = sitePackage.GetIdHashFromConverters();

            foreach (long savedSiteId in sitePackage.HeaderInfo.Convertors.Select(e => e.SavedSiteId))
            {
                var siteModel = new SiteModel(
                    context: context,
                    siteId: savedSiteId);
                switch (siteModel.ReferenceType)
                {
                case "Wikis":
                    var wikiModel = new WikiModel(
                        context: context,
                        ss: siteModel.SiteSettings)
                    {
                        SiteId   = siteModel.SiteId,
                        Title    = siteModel.Title,
                        Body     = siteModel.Body,
                        Comments = siteModel.Comments
                    };
                    wikiModel.Create(
                        context: context,
                        ss: siteModel.SiteSettings);
                    var wikiId = Repository.ExecuteScalar_long(
                        context: context,
                        statements: Rds.SelectWikis(
                            top: 1,
                            column: Rds.WikisColumn().WikiId(),
                            where : Rds.WikisWhere().SiteId(siteModel.SiteId)));
                    idHash.Add(savedSiteId, wikiId);
                    break;

                default:
                    Search.Indexes.Create(
                        context: context,
                        ss: siteModel.SiteSettings,
                        id: siteModel.SiteId);
                    break;
                }
            }
            SiteInfo.Reflesh(context: context);
            int dataCount = 0;

            if (includeData)
            {
                if (sitePackage.Data.Any())
                {
                    ImportItems(
                        context: context,
                        sitePackage: sitePackage,
                        idHash: idHash);
                    sitePackage.ConvertDataId(
                        context: context,
                        idHash: idHash);
                    dataCount = ImportData(
                        context: context,
                        sitePackage: sitePackage,
                        idHash: idHash);
                }
            }
            if (sitePackage.HeaderInfo.Convertors.Any())
            {
                foreach (var conv in sitePackage.HeaderInfo.Convertors)
                {
                    if (conv.ReferenceType == "Sites")
                    {
                        if ((!conv.Order.IsNullOrEmpty() && conv.Order.Equals("[]") == false))
                        {
                            var newOrders = new List <long>();
                            var orders    = conv.Order.Deserialize <List <long> >()?.ToList()
                                            ?? new List <long>();
                            orders.ForEach(e => newOrders.Add(idHash.Get(e)));
                            if (newOrders.Any())
                            {
                                new OrderModel()
                                {
                                    ReferenceId   = conv.SavedSiteId.ToLong(),
                                    ReferenceType = "Sites",
                                    OwnerId       = 0,
                                    Data          = newOrders
                                }.UpdateOrCreate(
                                    context: context,
                                    ss: ss);
                            }
                        }
                    }
                }
                var response = Repository.ExecuteScalar_response(
                    context: context,
                    transactional: true);
            }
            if (sitePackage.Permissions.Any())
            {
                foreach (var conv in sitePackage.HeaderInfo.Convertors)
                {
                    var packageSiteModel = sitePackage.Sites
                                           .Where(e => e.SiteId == conv.SiteId)
                                           .FirstOrDefault();
                    var packagePermissionModel = sitePackage.Permissions
                                                 .Where(e => e.SiteId == conv.SiteId)
                                                 .FirstOrDefault();
                    foreach (var permissionShortModel in packagePermissionModel.Permissions)
                    {
                        if (includeSitePermission == false)
                        {
                            if (permissionShortModel.ReferenceId == packagePermissionModel.SiteId)
                            {
                                continue;
                            }
                        }
                        if ((includeRecordPermission == false) || (dataCount == 0))
                        {
                            if (permissionShortModel.ReferenceId != packagePermissionModel.SiteId)
                            {
                                continue;
                            }
                        }
                        var idConverter = new IdConverter(
                            context: context,
                            siteId: packageSiteModel.SavedSiteId,
                            permissionShortModel: permissionShortModel,
                            permissionIdList: sitePackage.PermissionIdList,
                            convertSiteId: idHash[permissionShortModel.ReferenceId]);
                        var exists = Rds.ExecuteScalar_int(
                            context: context,
                            statements: Rds.SelectPermissions(
                                column: Rds.PermissionsColumn().ReferenceId(),
                                where : Rds.PermissionsWhere()
                                .ReferenceId(idHash[permissionShortModel.ReferenceId])
                                .DeptId(idConverter.ConvertDeptId)
                                .GroupId(idConverter.ConvertGroupId)
                                .UserId(idConverter.ConvertUserId))) > 0;
                        if (idConverter.Convert == true && !exists)
                        {
                            Repository.ExecuteNonQuery(
                                context: context,
                                transactional: true,
                                statements: Rds.InsertPermissions(
                                    param: Rds.PermissionsParam()
                                    .ReferenceId(idHash[permissionShortModel.ReferenceId])
                                    .DeptId(idConverter.ConvertDeptId)
                                    .GroupId(idConverter.ConvertGroupId)
                                    .UserId(idConverter.ConvertUserId)
                                    .PermissionType(permissionShortModel.PermissionType)));
                        }
                    }
                }
            }
            Repository.ExecuteNonQuery(
                context: context,
                statements: StatusUtilities.UpdateStatus(
                    tenantId: context.TenantId,
                    type: StatusUtilities.Types.UsersUpdated));
            if (apiData == null)
            {
                SessionUtilities.Set(
                    context: context,
                    message: Messages.SitePackageImported(
                        context: context,
                        data: new string[]
                {
                    sitePackage.HeaderInfo.Convertors.Count().ToString(),
                    dataCount.ToString()
                }));
                return(new ResponseCollection()
                       .Href(url: Locations.ItemIndex(
                                 context: context,
                                 id: ss.SiteId))
                       .ToJson());
            }
            else
            {
                return(sitePackage.HeaderInfo.Convertors
                       .Select(o => new
                {
                    OldSiteId = o.SiteId,
                    NewSiteId = o.SavedSiteId,
                    ReferenceType = o.ReferenceType,
                    Title = o.SiteTitle
                })
                       .ToJson());
            }
        }
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            var context = new ContextImplement(
                sessionStatus: false,
                sessionData: false,
                item: false,
                setPermissions: false);

            if (context.Controller != "errors" && Parameters.SyntaxErrors?.Any() == true)
            {
                filterContext.Result = new RedirectResult(
                    Locations.ParameterSyntaxError(context: context));
            }
            if (context.Authenticated &&
                !context.ContractSettings.AllowedIpAddress(context.UserHostAddress))
            {
                Authentications.SignOut(context: context);
                filterContext.Result = new RedirectResult(
                    Locations.InvalidIpAddress(context: context));
                return;
            }
            if (context.Authenticated &&
                context.ContractSettings.OverDeadline(context: context))
            {
                Authentications.SignOut(context: context);
                filterContext.Result = new RedirectResult(
                    Locations.Login(context: context) + "?expired=1");
                return;
            }
            if (context.Authenticated &&
                Parameters.Security.TokenCheck &&
                filterContext.HttpContext.Request.HasFormContentType &&
                filterContext.HttpContext.Request.Form.Count > 0 &&
                filterContext.HttpContext.Request.Form["Token"] != context.Token())
            {
                filterContext.HttpContext.Response.StatusCode = 400;
                if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    filterContext.Result = new JsonResult(
                        new
                    {
                        Message = Displays.InvalidRequest(context: context)
                    });
                }
                else
                {
                    filterContext.Result = new ContentResult()
                    {
                        Content = Displays.InvalidRequest(context: context)
                    };
                }
                return;
            }
            if (!context.LoginId.IsNullOrEmpty())
            {
                if (!context.Authenticated)
                {
                    if (Authentications.Windows(context: context))
                    {
                        filterContext.Result = new EmptyResult();
                        return;
                    }
                    else
                    {
                        Authentications.SignOut(context: context);
                        filterContext.Result = new RedirectResult(
                            Locations.Login(context: context));
                        return;
                    }
                }
            }
            SiteInfo.Reflesh(context: context);
        }