예제 #1
0
 private string GetSmsCodeCacheKey(string mobile)
 {
     return(CacheUtils.GetClassKey(typeof(LoginController), nameof(Administrator), mobile));
 }
예제 #2
0
 public TableStyleIe(IDatabaseManager databaseManager, CacheUtils caching, string directoryPath)
 {
     _databaseManager = databaseManager;
     _caching         = caching;
     _directoryPath   = directoryPath;
 }
 public static void Clear()
 {
     CacheUtils.Remove(CacheKey);
 }
예제 #4
0
        public NameValueCollection GetCountArray(string userKeyPrefix)//进度及显示
        {
            var retval = new NameValueCollection();

            if (CacheUtils.Get(userKeyPrefix + CacheTotalCount) != null && CacheUtils.Get(userKeyPrefix + CacheCurrentCount) != null && CacheUtils.Get(userKeyPrefix + CacheMessage) != null)
            {
                var totalCount   = TranslateUtils.ToInt((string)CacheUtils.Get(userKeyPrefix + CacheTotalCount));
                var currentCount = TranslateUtils.ToInt((string)CacheUtils.Get(userKeyPrefix + CacheCurrentCount));
                var message      = (string)CacheUtils.Get(userKeyPrefix + CacheMessage);
                retval = AjaxManager.GetCountArrayNameValueCollection(totalCount, currentCount, message);
            }
            return(retval);
        }
예제 #5
0
 private string GetEntityKey(string tableName, int contentId)
 {
     return(CacheUtils.GetEntityKey(tableName, contentId));
 }
예제 #6
0
 private string GetCacheKey(int siteId) => CacheUtils.GetListKey(_repository.TableName, siteId);
예제 #7
0
 private static void FileWatcher_OnFileChange(object sender, EventArgs e)
 {
     CacheUtils.Remove(CacheKey);
 }
예제 #8
0
 private string GetSmsCodeCacheKey(string mobile)
 {
     return(CacheUtils.GetCacheKey(nameof(MobileController), nameof(Administrator), mobile));
 }
        public void Get()
        {
            var response = HttpContext.Current.Response;

            var code = CreateValidateCode();

            if (CacheUtils.Exists($"{CookieName}.{code}"))
            {
                code = CreateValidateCode();
            }

            CookieUtils.SetCookie(CookieName, code, DateTime.Now.AddMinutes(10));

            response.BufferOutput = true;                                //特别注意
            response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1)); //特别注意
            response.Cache.SetCacheability(HttpCacheability.NoCache);    //特别注意
            response.AppendHeader("Pragma", "No-Cache");                 //特别注意
            response.ContentType = "image/png";

            byte[] buffer;

            using (var image = new Bitmap(130, 53, PixelFormat.Format32bppRgb))
            {
                var r      = new Random();
                var colors = Colors[r.Next(0, 5)];

                using (var g = Graphics.FromImage(image))
                {
                    g.FillRectangle(new SolidBrush(Color.FromArgb(240, 243, 248)), 0, 0, 200, 200);                                                          //矩形框
                    g.DrawString(code, new Font(FontFamily.GenericSerif, 28, FontStyle.Bold | FontStyle.Italic), new SolidBrush(colors), new PointF(14, 3)); //字体/颜色

                    var random = new Random();

                    for (var i = 0; i < 25; i++)
                    {
                        var x1 = random.Next(image.Width);
                        var x2 = random.Next(image.Width);
                        var y1 = random.Next(image.Height);
                        var y2 = random.Next(image.Height);

                        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                    }

                    for (var i = 0; i < 100; i++)
                    {
                        var x = random.Next(image.Width);
                        var y = random.Next(image.Height);

                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    }

                    g.Save();
                }

                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Png);
                    buffer = ms.ToArray();
                }
            }

            response.ClearContent();
            response.BinaryWrite(buffer);
            response.End();
        }
예제 #10
0
 public MaterialFileRepository(ISettingsManager settingsManager)
 {
     _settingsManager = settingsManager;
     _repository      = new Repository <MaterialFile>(settingsManager.Database, settingsManager.Redis);
     CacheKey         = CacheUtils.GetListKey(_repository.TableName);
 }
예제 #11
0
파일: HttpManager.cs 프로젝트: rinavin/RCJS
        /// <summary> interact with the cache manager; execute HTTP request if needed; if 'decryptResponse' is true, fresh
        /// responses from the server will be decrypted (if needed) using the 'encryptionKey' passed to 'setProperties'; </summary>
        /// <param name="requestedURL">URL to be accessed. If the URL contains a time stamp on the server-side (|timestamp), the time stamp is seperated from the URL and checked against the local/client-side cache.</param>
        /// <param name="requestContent">content to be sent to server (relevant only for POST method - is null for other methods). may be byte[] or string.</param>
        /// <param name="requestContentType">type of the content to be sent to server, e.g application/octet-stream (for POST method only).</param>
        /// <param name="decryptResponse">if true, fresh responses from the server will be decrypted using the 'encryptionKey' passed to 'HttpManager.SetProperties'.</param>
        /// <param name="allowRetry">whether or not retry after connection failure.</param>
        /// <param name="cachingStrategy">Enabels or disables cache read/write operations.</param>
        /// <param name="isError">set to true if server returns error processing the request.</param>
        /// <returns>response (from the server).</returns>
        internal byte[] GetContent(String requestedURL, object requestContent, String requestContentType, bool decryptResponse, bool allowRetry,
                                   CachingStrategy cachingStrategy, out bool isError)
        {
            String urlCachedByRequest = null; // a cached file retrieval request without the timestamp, e.g. http://[server]/[requester]?CTX=&CACHE=MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml

            byte[]   response         = null;
            long     startTime        = Misc.getSystemMilliseconds();
            TimeSpan requestStartTime = DateTime.Now.TimeOfDay; // for RecentNetworkActivities only
            bool     isCacheRequest   = false;

            try
            {
                Logger.Instance.WriteServerToLog(
                    "*************************************************************************************************");

                cachingStrategy.FoundInCache = false;
                isError = false;

                String remoteTime = null;

                // GET request
                if (requestContent == null)
                {
                    //--------------------------------------------------------------------------------------------
                    // topic #16 (MAGIC version 1.8 for WIN) RC - Cache security enhancements:
                    //   the server reports the time stamp as part as the URL, for example:
                    //      http://../mgrqispi.dll?CTX=155842418385&CACHE=KeyboardMapping.xml%7C19/03/2009%2009:45:33
                    //   cache files are accessed via a request, in this example:
                    //      http://myserver/MagicScripts/mgrqispi.dll?CTX=155842418385&CACHE=KeyboardMapping.xml
                    //                                                               ^ indexOfCacheToken
                    //--------------------------------------------------------------------------------------------
                    // extract the remote time from the request
                    int indexOfCacheToken = requestedURL.IndexOf(ConstInterface.RC_TOKEN_CACHED_FILE);
                    if (indexOfCacheToken != -1)
                    {
                        isCacheRequest = true;
                        string decodedUrl = HttpUtility.UrlDecode(requestedURL, Encoding.UTF8);
                        requestedURL = CacheUtils.URLToFileName(decodedUrl);

                        string cacheFilePath = String.Empty;
                        CacheUtils.GetCacheFileDetailsFromUrl(decodedUrl, ref cacheFilePath, ref remoteTime, ref decryptResponse);

                        byte[]     bufferToSend = Encoding.UTF8.GetBytes(cacheFilePath);
                        IEncryptor encryptor    = PersistentOnlyCacheManager.GetInstance();
                        if (!encryptor.EncryptionDisabled)
                        {
                            byte[] encryptedURL = encryptor.Encrypt(Encoding.UTF8.GetBytes(cacheFilePath));
                            byte[] base64EncodedEncryptedURL = Base64.encode(encryptedURL);
                            bufferToSend = base64EncodedEncryptedURL;
                        }
                        // prepare URL again by encoding only CACHE value
                        urlCachedByRequest = decodedUrl.Substring(0, indexOfCacheToken) +
                                             ConstInterface.RC_INDICATION +
                                             ConstInterface.RC_TOKEN_CACHED_FILE +
                                             HttpUtility.UrlEncode(bufferToSend);
                    }
                    else if (requestedURL.IndexOf('?') == -1)
                    {
                        // i.e. the url refers to a file on the web server, rather than a requester + query string
                        remoteTime = _httpClient.GetRemoteTime(requestedURL);
                    }
                }

                Logger.Instance.WriteServerToLog(requestedURL);

                byte[] errorResponse = null;
                // Story#138618: remoteTime will not exist in the cache url.
                // (for backward compatibility remoteTime exist in url if  SpecialTimeStampRIACache is ON)
                if (remoteTime == null && !isCacheRequest)
                {
                    // resources for which no remote time could be retrieved (either by the web server or by the runtime-engine, in a cache request url) can't be and aren't cached,
                    // since without a time stamp the client can't decide if the client-side copy is out-dated.
                    //-----------------------------

                    LogAccessToServer("", requestContent);
                    response = GetContentByHTTPRequest(requestedURL, requestContent, requestContentType, allowRetry);
                    Debug.Assert(response != null);
                    errorResponse = CheckAndGetErrorResponse(response);
                }
                else
                {
                    // cachable resources ..
                    //----------------------

                    ICacheManager cacheManager = PersistentOnlyCacheManager.GetInstance();
                    if (cachingStrategy.CachedContentShouldBeReturned)
                    {
                        response = (remoteTime == null
                                ? cacheManager.GetFile(requestedURL)
                                : cacheManager.GetFile(requestedURL, remoteTime));
                        cachingStrategy.FoundInCache = (response != null);
                    }
                    else
                    {
                        // here 'requestedURL' is excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.
                        Debug.Assert(requestedURL.IndexOf('|') == -1);
                        cachingStrategy.FoundInCache = (cachingStrategy.AllowOutdatedContent || remoteTime == null
                                                      ? cacheManager.IsExists(requestedURL)
                                                      : cacheManager.CheckFile(requestedURL, remoteTime));
                    }

                    if (cachingStrategy.FoundInCache)
                    {
                        Logger.Instance.WriteServerToLog("Found in cache.");
                    }
                    else
                    {
                        LogAccessToServer(String.Format("Not in cache{0}!", cachingStrategy.AllowOutdatedContent ? "" : " or outdated"), null);

                        // get fresh content & put in the cache
                        response = GetContentByHTTPRequest((urlCachedByRequest ?? requestedURL), null, requestContentType, allowRetry);
                        if (response != null)
                        {
                            errorResponse = CheckAndGetErrorResponse(response);

                            // do not save the file, if there is an error.
                            if (errorResponse == null && cachingStrategy.CanWriteToCache)
                            {
                                cacheManager.PutFile(requestedURL, response, remoteTime);
                            }
                        }
                    }
                }

                //Error messages are never encrypted. So, do not decrypt them.
                if (errorResponse != null)
                {
                    response = errorResponse;
                    isError  = true;
                }
                else if (decryptResponse && response != null)
                {
                    IEncryptor encryptor = PersistentOnlyCacheManager.GetInstance();
                    response = encryptor.Decrypt(response);
                }

#if PocketPC
                GUIMain.getInstance().MainForm.updateProgressBar();
#endif

                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + OSEnvironment.EolSeq +
                                    (new Uri((urlCachedByRequest ?? requestedURL))).GetLeftPart(UriPartial.Path), ex);
            }
            finally
            {
                //collect statistics
                var elapsedTime = (uint)(Misc.getSystemMilliseconds() - startTime);

                // !foundInCache ==> the request was executed by the HTTP client ==> should be recorded
                if (!cachingStrategy.FoundInCache)
                {
                    Statistics.RecordRequest(elapsedTime,
                                             (ulong)(requestContent != null
                                                    ? HttpClient.GetRequestContentLength(requestContent)
                                                    : 0),
                                             (ulong)(response != null
                                                    ? response.Length
                                                    : 0));
                }
                Logger.Instance.WriteServerToLog(
                    string.Format(
                        "Completed {0}: {1:N0} ms, accumulated: {2:N0} ms (server: {3:N0}), {4}{5}{6}**************************************************************************************************",
                        (cachingStrategy.FoundInCache
                      ? ""
                      : string.Format("#{0:N0}", Statistics.GetRequestsCnt())
                        ),
                        elapsedTime,
                        Statistics.GetAccumulatedExternalTime(), Statistics.GetAccumulatedServerTime(),
                        (cachingStrategy.FoundInCache
                      ? ""
                      : (response != null
                            ? string.Format("{0:N0} bytes downloaded", response.Length)
                            : "Null response!")
                        ),
                        OSEnvironment.EolSeq, OSEnvironment.TabSeq)
                    );
                if (!cachingStrategy.FoundInCache && ClientManager.Instance.getDisplayStatisticInfo())
                {
                    // Add the networking activity.
                    var downloadSizeKB = (ulong)(response != null
                                                ? response.Length
                                                : 0);
                    RecentNetworkActivities.Append(Statistics.GetRequestsCnt(), requestStartTime, elapsedTime, downloadSizeKB, requestedURL);
                }
            }
        }
예제 #12
0
        public async Task <ActionResult <SubmitResult> > Submit([FromBody] SubmitRequest request)
        {
            if (!await _authManager.HasContentPermissionsAsync(request.SiteId, request.ChannelId, Types.ContentPermissions.View))
            {
                return(Unauthorized());
            }

            var downloadUrl = string.Empty;

            var site = await _siteRepository.GetAsync(request.SiteId);

            if (site == null)
            {
                return(NotFound());
            }

            var channel = await _channelRepository.GetAsync(request.ChannelId);

            if (channel == null)
            {
                return(NotFound());
            }

            var columnsManager = new ColumnsManager(_databaseManager, _pathManager);
            var columns        = await columnsManager.GetContentListColumnsAsync(site, channel, ColumnsManager.PageType.Contents);

            var contentInfoList = new List <Content>();
            var ccIds           = await _contentRepository.GetSummariesAsync(site, channel, true);

            var count = ccIds.Count;

            var pages = Convert.ToInt32(Math.Ceiling((double)count / site.PageSize));

            if (pages == 0)
            {
                pages = 1;
            }

            if (count > 0)
            {
                for (var page = 1; page <= pages; page++)
                {
                    var offset    = site.PageSize * (page - 1);
                    var limit     = site.PageSize;
                    var pageCcIds = ccIds.Skip(offset).Take(limit).ToList();

                    var sequence = offset + 1;

                    foreach (var channelContentId in pageCcIds)
                    {
                        var contentInfo = await _contentRepository.GetAsync(site, channelContentId.ChannelId, channelContentId.Id);

                        if (contentInfo == null)
                        {
                            continue;
                        }

                        if (!request.IsAllCheckedLevel)
                        {
                            var checkedLevel = contentInfo.CheckedLevel;
                            if (contentInfo.Checked)
                            {
                                checkedLevel = site.CheckContentLevel;
                            }
                            if (!request.CheckedLevelKeys.Contains(checkedLevel))
                            {
                                continue;
                            }
                        }

                        if (!request.IsAllDate)
                        {
                            if (contentInfo.AddDate < request.StartDate || contentInfo.AddDate > request.EndDate)
                            {
                                continue;
                            }
                        }

                        contentInfoList.Add(await columnsManager.CalculateContentListAsync(sequence++, site, request.ChannelId, contentInfo, columns));
                    }
                }

                if (contentInfoList.Count > 0)
                {
                    if (request.ExportType == "zip")
                    {
                        var fileName = $"{channel.ChannelName}.zip";
                        var filePath = _pathManager.GetTemporaryFilesPath(fileName);

                        var caching      = new CacheUtils(_cacheManager);
                        var exportObject = new ExportObject(_pathManager, _databaseManager, caching, site);
                        contentInfoList.Reverse();
                        if (await exportObject.ExportContentsAsync(filePath, contentInfoList))
                        {
                            downloadUrl = _pathManager.GetTemporaryFilesUrl(fileName);
                        }
                    }
                    else if (request.ExportType == "excel")
                    {
                        var fileName = $"{channel.ChannelName}.csv";
                        var filePath = _pathManager.GetTemporaryFilesPath(fileName);

                        var excelObject = new ExcelObject(_databaseManager, _pathManager);

                        await excelObject.CreateExcelFileForContentsAsync(filePath, site, channel, contentInfoList, request.ColumnNames);

                        downloadUrl = _pathManager.GetTemporaryFilesUrl(fileName);
                    }
                }
            }

            return(new SubmitResult
            {
                Value = downloadUrl,
                IsSuccess = !string.IsNullOrEmpty(downloadUrl)
            });
        }
예제 #13
0
 public ExportObject(IPathManager pathManager, IDatabaseManager databaseManager, CacheUtils caching, Site site)
 {
     _pathManager     = pathManager;
     _databaseManager = databaseManager;
     _caching         = caching;
     _site            = site;
 }
예제 #14
0
 public static bool Update(UserGroupInfo model)
 {
     CacheUtils.Del("JsonLeeCMS_CacheForGetUserGroup");
     return(BizBase.dbo.UpdateModel <UserGroupInfo>(model));
 }
예제 #15
0
        public async Task <IHttpActionResult> Create()
        {
            try
            {
                var request = new AuthenticatedRequest();
                if (!request.IsAdminLoggin || request.AdminInfo == null)
                {
                    return(Unauthorized());
                }

#if !DEBUG
                var sessionId = request.GetPostString("sessionId");
                var cacheKey  = Constants.GetSessionIdCacheKey(request.AdminId);
                if (string.IsNullOrEmpty(sessionId) || CacheUtils.GetString(cacheKey) != sessionId)
                {
                    return(Unauthorized());
                }
#endif

                if (request.AdminInfo.LastActivityDate != null && ConfigManager.SystemConfigInfo.IsAdminEnforceLogout)
                {
                    var ts = new TimeSpan(DateTime.Now.Ticks - request.AdminInfo.LastActivityDate.Value.Ticks);
                    if (ts.TotalMinutes > ConfigManager.SystemConfigInfo.AdminEnforceLogoutMinutes)
                    {
                        return(Unauthorized());
                    }
                }

                var count = CreateTaskManager.PendingTaskCount;

                var pendingTask = CreateTaskManager.GetFirstPendingTask();
                if (pendingTask != null)
                {
                    try
                    {
                        var start = DateTime.Now;
                        await FileSystemObjectAsync.ExecuteAsync(pendingTask.SiteId, pendingTask.CreateType,
                                                                 pendingTask.ChannelId,
                                                                 pendingTask.ContentId, pendingTask.FileTemplateId, pendingTask.SpecialId);

                        var timeSpan = DateUtils.GetRelatedDateTimeString(start);
                        CreateTaskManager.AddSuccessLog(pendingTask, timeSpan);
                    }
                    catch (Exception ex)
                    {
                        CreateTaskManager.AddFailureLog(pendingTask, ex);
                    }
                    finally
                    {
                        CreateTaskManager.RemovePendingTask(pendingTask);
                    }
                }

                return(Ok(new
                {
                    Value = count
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
예제 #16
0
        public async Task <ActionResult <IntResult> > Submit([FromBody] SubmitRequest request)
        {
            if (!await _authManager.HasAppPermissionsAsync(MenuUtils.AppPermissions.SettingsSitesAdd))
            {
                return(Unauthorized());
            }

            if (!request.Root)
            {
                if (_pathManager.IsSystemDirectory(request.SiteDir))
                {
                    return(this.Error("文件夹名称不能为系统文件夹名称,请更改文件夹名称!"));
                }
                if (!DirectoryUtils.IsDirectoryNameCompliant(request.SiteDir))
                {
                    return(this.Error("文件夹名称不符合系统要求,请更改文件夹名称!"));
                }
                var sitePath = await _pathManager.GetSitePathAsync(request.ParentId);

                var directories = DirectoryUtils.GetDirectoryNames(sitePath);
                if (ListUtils.ContainsIgnoreCase(directories, request.SiteDir))
                {
                    return(this.Error("已存在相同的文件夹,请更改文件夹名称!"));
                }
                var list = await _siteRepository.GetSiteDirsAsync(request.ParentId);

                if (ListUtils.ContainsIgnoreCase(list, request.SiteDir))
                {
                    return(this.Error("已存在相同的站点文件夹,请更改文件夹名称!"));
                }
            }

            var channelInfo = new Channel();

            channelInfo.ChannelName          = channelInfo.IndexName = "首页";
            channelInfo.ParentId             = 0;
            channelInfo.ContentModelPluginId = string.Empty;

            var tableName = string.Empty;

            if (StringUtils.EqualsIgnoreCase(request.SiteType, Types.SiteTypes.Web) || StringUtils.EqualsIgnoreCase(request.SiteType, Types.SiteTypes.Wx))
            {
                if (request.TableRule == TableRule.Choose)
                {
                    tableName = request.TableChoose;
                }
                else if (request.TableRule == TableRule.HandWrite)
                {
                    tableName = request.TableHandWrite;

                    if (!await _settingsManager.Database.IsTableExistsAsync(tableName))
                    {
                        await _contentRepository.CreateContentTableAsync(tableName, _contentRepository.GetTableColumns(tableName));
                    }
                    else
                    {
                        await _settingsManager.Database.AlterTableAsync(tableName, _contentRepository.GetTableColumns(tableName));
                    }
                }
            }

            var adminId = _authManager.AdminId;

            var siteId = await _siteRepository.InsertSiteAsync(channelInfo, new Site
            {
                SiteName  = request.SiteName,
                SiteType  = request.SiteType,
                SiteDir   = request.SiteDir,
                TableName = tableName,
                ParentId  = request.ParentId,
                Root      = request.Root
            }, adminId);

            if (string.IsNullOrEmpty(tableName))
            {
                tableName = await _contentRepository.CreateNewContentTableAsync();

                await _siteRepository.UpdateTableNameAsync(siteId, tableName);
            }

            if (await _authManager.IsSiteAdminAsync() && !await _authManager.IsSuperAdminAsync())
            {
                var siteIdList = await _authManager.GetSiteIdsAsync() ?? new List <int>();

                siteIdList.Add(siteId);
                var adminInfo = await _administratorRepository.GetByUserIdAsync(adminId);

                await _administratorRepository.UpdateSiteIdsAsync(adminInfo, siteIdList);
            }

            var caching = new CacheUtils(_cacheManager);
            var site    = await _siteRepository.GetAsync(siteId);

            caching.SetProcess(request.Guid, "任务初始化...");

            if (request.CreateType == "local")
            {
                var manager = new SiteTemplateManager(_pathManager, _databaseManager, caching);
                await manager.ImportSiteTemplateToEmptySiteAsync(site, request.LocalDirectoryName, request.IsImportContents, request.IsImportTableStyles, adminId, request.Guid);

                caching.SetProcess(request.Guid, "生成站点页面...");
                await _createManager.CreateByAllAsync(site.Id);

                caching.SetProcess(request.Guid, "清除系统缓存...");
                _cacheManager.Clear();
            }
            else if (request.CreateType == "cloud")
            {
                caching.SetProcess(request.Guid, "开始下载模板压缩包,可能需要几分钟,请耐心等待...");

                var filePath = _pathManager.GetSiteTemplatesPath($"T_{request.CloudThemeName}.zip");
                FileUtils.DeleteFileIfExists(filePath);
                var downloadUrl = CloudUtils.Dl.GetThemesDownloadUrl(request.CloudThemeUserName, request.CloudThemeName);
                WebClientUtils.Download(downloadUrl, filePath);

                caching.SetProcess(request.Guid, "模板压缩包下载成功,开始解压缩,可能需要几分钟,请耐心等待...");

                var siteTemplateDir = $"T_{request.CloudThemeName}";
                var directoryPath   = _pathManager.GetSiteTemplatesPath(siteTemplateDir);
                DirectoryUtils.DeleteDirectoryIfExists(directoryPath);
                _pathManager.ExtractZip(filePath, directoryPath);

                caching.SetProcess(request.Guid, "模板压缩包解压成功,正在导入数据...");

                var manager = new SiteTemplateManager(_pathManager, _databaseManager, caching);
                await manager.ImportSiteTemplateToEmptySiteAsync(site, siteTemplateDir, request.IsImportContents, request.IsImportTableStyles, adminId, request.Guid);

                caching.SetProcess(request.Guid, "生成站点页面...");
                await _createManager.CreateByAllAsync(site.Id);

                caching.SetProcess(request.Guid, "清除系统缓存...");
                _cacheManager.Clear();
            }
            else
            {
                var templates = await _templateRepository.GetSummariesAsync(site.Id);

                foreach (var summary in templates)
                {
                    var template = await _templateRepository.GetAsync(summary.Id);

                    await _pathManager.WriteContentToTemplateFileAsync(site, template, Constants.Html5Empty, _authManager.AdminId);
                }

                await _createManager.CreateByAllAsync(site.Id);
            }

            return(new IntResult
            {
                Value = siteId
            });
        }
        public IHttpActionResult Insert()
        {
            try
            {
                var request = Context.AuthenticatedRequest;
                var siteId  = request.GetPostInt("siteId");
                if (!request.IsAdminLoggin)
                {
                    return(Unauthorized());
                }

                var authCode = request.GetPostString("authCode");
                var code     = CookieUtils.GetCookie(CaptchaController.CookieName);
                if (string.IsNullOrEmpty(code) || CacheUtils.Exists($"{CaptchaController.CookieName}.{code}"))
                {
                    return(BadRequest("验证码已超时,请点击刷新验证码!"));
                }
                CookieUtils.Erase(CaptchaController.CookieName);
                CacheUtils.InsertMinutes($"{CaptchaController.CookieName}.{code}", true, 10);
                if (!StringUtils.EqualsIgnoreCase(code, authCode))
                {
                    return(BadRequest("验证码不正确,请重新输入!"));
                }

                var categoryId     = request.GetPostInt("categoryId");
                var departmentId   = request.GetPostInt("departmentId");
                var categoryInfo   = CategoryManager.GetCategoryInfo(siteId, categoryId);
                var departmentInfo = DepartmentManager.GetDepartmentInfo(siteId, departmentId);

                var dataInfo = new DataInfo
                {
                    Id             = 0,
                    SiteId         = siteId,
                    AddDate        = DateTime.Now,
                    QueryCode      = StringUtils.GetShortGuid(true),
                    CategoryId     = categoryInfo?.Id ?? 0,
                    DepartmentId   = departmentInfo?.Id ?? 0,
                    IsCompleted    = false,
                    State          = DataState.New.Value,
                    DenyReason     = string.Empty,
                    RedoComment    = string.Empty,
                    ReplyContent   = string.Empty,
                    IsReplyFiles   = false,
                    ReplyDate      = DateTime.Now,
                    Name           = request.GetPostString("name"),
                    Gender         = request.GetPostString("gender"),
                    Phone          = request.GetPostString("phone"),
                    Email          = request.GetPostString("email"),
                    Address        = request.GetPostString("address"),
                    Zip            = request.GetPostString("zip"),
                    Title          = request.GetPostString("title"),
                    Content        = request.GetPostString("content"),
                    CategoryName   = categoryInfo == null ? string.Empty : categoryInfo.CategoryName,
                    DepartmentName = departmentInfo == null ? string.Empty : departmentInfo.DepartmentName
                };

                Main.DataRepository.Insert(dataInfo);

                return(Ok(new
                {
                    Value = dataInfo
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
예제 #18
0
 protected void btnok_Click(object sender, System.EventArgs e)
 {
     if (base.Action.Equals(ActionType.Add.ToString()) && !base.IsAuthorizedOp(ActionType.Add.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else if (base.Action.Equals(ActionType.Modify.ToString()) && !base.IsAuthorizedOp(ActionType.Modify.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else
     {
         DictsInfo dataById   = Dicts.GetDataById(WebUtils.GetQueryInt("dictid"));
         string    strKeyName = WebUtils.GetString(this.TextBox1.Text);
         string    @string    = WebUtils.GetString(this.TextBox2.Text);
         int       @int       = WebUtils.GetInt(this.TextBox3.Text);
         if (string.IsNullOrEmpty(strKeyName))
         {
             base.ShowMsg("Nội dung Từ điển quan trọng không thể để trống");
         }
         else if (string.IsNullOrEmpty(@string))
         {
             base.ShowMsg("Giá trị từ điền không thể để trống");
         }
         else if (base.Action.Equals(ActionType.Add.ToString()) && dataById.Items.Exists((DictItemInfo p) => p.KeyName.Equals(strKeyName)))
         {
             base.ShowMsg("Nội dung từ điển đã tồn tại");
         }
         else
         {
             if (base.Action.Equals(ActionType.Add.ToString()))
             {
                 string text = string.Empty;
                 if (dataById.DictValue.IndexOf("[") == -1)
                 {
                     text = string.Concat(new object[]
                     {
                         "{\"KeyName\":\"",
                         strKeyName,
                         "\",\"KeyValue\":\"",
                         @string,
                         "\",\"Sort\":",
                         @int,
                         "}"
                     });
                 }
                 else
                 {
                     text = string.Concat(new object[]
                     {
                         dataById.DictValue.TrimStart(new char[]
                         {
                             '['
                         }).TrimEnd(new char[]
                         {
                             ']'
                         }),
                         ",{\"KeyName\":\"",
                         strKeyName,
                         "\",\"KeyValue\":\"",
                         @string,
                         "\",\"Sort\":",
                         @int,
                         "}"
                     });
                 }
                 dataById.DictValue = "[" + text.TrimStart(new char[]
                 {
                     ','
                 }) + "]";
                 if (Dicts.Update(dataById))
                 {
                     CacheUtils.Del("JsonLeeCMS_CacheForGetDicts");
                     PageBase.log.AddEvent(base.LoginAccount.AccountName, "Thêm nội dung từ điển [" + strKeyName + "] thành công");
                     MessageUtils.DialogCloseAndParentReload(this);
                 }
                 else
                 {
                     base.ShowMsg("Thao tác thất bại");
                 }
             }
             if (base.Action.Equals(ActionType.Modify.ToString()))
             {
                 DictItemInfo dictItemInfo = (from p in Dicts.GetDataById(WebUtils.GetQueryInt("dictid")).Items
                                              where p.KeyName.Equals(WebUtils.GetQueryString("key"))
                                              select p).FirstOrDefault <DictItemInfo>();
                 string oldValue = string.Concat(new object[]
                 {
                     "{\"KeyName\":\"",
                     dictItemInfo.KeyName,
                     "\",\"KeyValue\":\"",
                     dictItemInfo.KeyValue,
                     "\",\"Sort\":",
                     dictItemInfo.Sort,
                     "}"
                 });
                 string newValue = string.Concat(new object[]
                 {
                     "{\"KeyName\":\"",
                     strKeyName,
                     "\",\"KeyValue\":\"",
                     @string,
                     "\",\"Sort\":",
                     @int,
                     "}"
                 });
                 dataById.DictValue = dataById.DictValue.Replace(oldValue, newValue);
                 if (Dicts.Update(dataById))
                 {
                     CacheUtils.Del("JsonLeeCMS_CacheForGetDicts");
                     PageBase.log.AddEvent(base.LoginAccount.AccountName, "Sửa đổi nội dung từ điển [" + strKeyName + "] thành công");
                     MessageUtils.DialogCloseAndParentReload(this);
                 }
                 else
                 {
                     base.ShowMsg("Thao tác thất bại");
                 }
             }
         }
     }
 }
예제 #19
0
 public TemplateIe(IPathManager pathManager, IDatabaseManager databaseManager, CacheUtils caching, Site site, string filePath)
 {
     _pathManager     = pathManager;
     _databaseManager = databaseManager;
     _caching         = caching;
     _site            = site;
     _filePath        = filePath;
 }
예제 #20
0
        public static void RecoverySite(int publishmentSystemId, bool isDeleteChannels, bool isDeleteTemplates, bool isDeleteFiles, bool isZip, string path, bool isOverride, bool isUseTable, string administratorName)
        {
            var importObject = new ImportObject(publishmentSystemId);

            var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId);

            var siteTemplatePath = path;

            if (isZip)
            {
                //解压文件
                siteTemplatePath = PathUtils.GetTemporaryFilesPath(EBackupTypeUtils.GetValue(EBackupType.Site));
                DirectoryUtils.DeleteDirectoryIfExists(siteTemplatePath);
                DirectoryUtils.CreateDirectoryIfNotExists(siteTemplatePath);

                ZipUtils.UnpackFiles(path, siteTemplatePath);
            }
            var siteTemplateMetadataPath = PathUtils.Combine(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteTemplateMetadata);

            if (isDeleteChannels)
            {
                var nodeIdList = DataProvider.NodeDao.GetNodeIdListByParentId(publishmentSystemId, publishmentSystemId);
                foreach (int nodeId in nodeIdList)
                {
                    DataProvider.NodeDao.Delete(nodeId);
                }
            }
            if (isDeleteTemplates)
            {
                var templateInfoArrayList =
                    DataProvider.TemplateDao.GetTemplateInfoArrayListByPublishmentSystemId(publishmentSystemId);
                foreach (TemplateInfo templateInfo in templateInfoArrayList)
                {
                    if (templateInfo.IsDefault == false)
                    {
                        DataProvider.TemplateDao.Delete(publishmentSystemId, templateInfo.TemplateId);
                    }
                }
            }
            if (isDeleteFiles)
            {
                DirectoryUtility.DeletePublishmentSystemFiles(publishmentSystemInfo);
            }

            //导入文件
            importObject.ImportFiles(siteTemplatePath, isOverride);

            //导入模板
            var templateFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileTemplate);

            importObject.ImportTemplates(templateFilePath, isOverride, administratorName);

            //导入辅助表
            var tableDirectoryPath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.Table);

            importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTable);

            //导入菜单
            var menuDisplayFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileMenuDisplay);

            importObject.ImportMenuDisplay(menuDisplayFilePath, isOverride);

            //导入标签样式
            var tagStyleFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileTagStyle);

            importObject.ImportTagStyle(tagStyleFilePath, isOverride);

            //导入固定广告
            var adFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileAd);

            importObject.ImportAd(adFilePath, isOverride);

            //导入采集规则
            var gatherRuleFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileGatherRule);

            importObject.ImportGatherRule(gatherRuleFilePath, isOverride);

            //导入提交表单
            var inputDirectoryPath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.Input);

            importObject.ImportInput(inputDirectoryPath, isOverride);

            //导入站点设置
            var configurationFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileConfiguration);

            importObject.ImportConfiguration(configurationFilePath);

            //导入内容模型
            var contentModelFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileContentModel);

            importObject.ImportContentModel(contentModelFilePath, true);

            //导入栏目及内容
            var siteContentDirectoryPath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.SiteContent);

            importObject.ImportChannelsAndContents(0, siteContentDirectoryPath, isOverride);

            DataProvider.NodeDao.UpdateContentNum(publishmentSystemInfo);

            //导入表样式及清除缓存
            if (isUseTable)
            {
                importObject.ImportTableStyles(tableDirectoryPath);
            }
            importObject.RemoveDbCache();

            CacheUtils.Clear();
        }
예제 #21
0
 public static void Clear()
 {
     CacheUtils.Remove(CacheKey);
     FileWatcher.UpdateCacheFile();
 }
예제 #22
0
 public static void ClearAllCache()
 {
     CacheUtils.RemoveByStartString(CacheKeyPrefix);
 }
예제 #23
0
 public ContentTagIe(IDatabaseManager databaseManager, CacheUtils caching)
 {
     _databaseManager = databaseManager;
     _caching         = caching;
 }
예제 #24
0
 private string CacheKey(MaterialType type) => CacheUtils.GetListKey(TableName, type.GetValue());
예제 #25
0
 private string GetListKey(string tableName, int siteId, int channelId)
 {
     return(CacheUtils.GetListKey(tableName, siteId.ToString(), (Math.Abs(channelId)).ToString()));
 }
예제 #26
0
 public ApplicationAuthorizes(IRoleService service, CacheUtils cache)
 {
     this.roleService = service ?? throw new ArgumentNullException(nameof(roleService));
     this.appCache    = cache ?? throw new ArgumentNullException(nameof(appCache));
 }
예제 #27
0
 /// <summary>
 /// 缓存模块注入
 /// </summary>
 /// <param name="cache"></param>
 /// <returns></returns>
 public FluentConfig Inject(ICache cache)
 {
     CacheUtils.Inject(cache);
     return(this);
 }
예제 #28
0
 public static void ClearCache(bool isAddAjaxUrl)
 {
     CacheUtils.Remove(CacheKey);
     CacheManager.UpdateTemporaryCacheFile(CacheFileName);
 }
예제 #29
0
        public static void RecoverySite(int siteId, bool isDeleteChannels, bool isDeleteTemplates, bool isDeleteFiles, bool isZip, string path, bool isOverride, bool isUseTable, string administratorName)
        {
            var importObject = new ImportObject(siteId, administratorName);

            var siteInfo = SiteManager.GetSiteInfo(siteId);

            var siteTemplatePath = path;

            if (isZip)
            {
                //解压文件
                siteTemplatePath = PathUtils.GetTemporaryFilesPath(EBackupTypeUtils.GetValue(EBackupType.Site));
                DirectoryUtils.DeleteDirectoryIfExists(siteTemplatePath);
                DirectoryUtils.CreateDirectoryIfNotExists(siteTemplatePath);

                ZipUtils.ExtractZip(path, siteTemplatePath);
            }
            var siteTemplateMetadataPath = PathUtils.Combine(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteTemplateMetadata);

            if (isDeleteChannels)
            {
                var channelIdList = ChannelManager.GetChannelIdList(ChannelManager.GetChannelInfo(siteId, siteId), EScopeType.Children, string.Empty, string.Empty, string.Empty);
                foreach (var channelId in channelIdList)
                {
                    DataProvider.ChannelDao.Delete(siteId, channelId);
                }
            }
            if (isDeleteTemplates)
            {
                var templateInfoList =
                    DataProvider.TemplateDao.GetTemplateInfoListBySiteId(siteId);
                foreach (var templateInfo in templateInfoList)
                {
                    if (templateInfo.IsDefault == false)
                    {
                        DataProvider.TemplateDao.Delete(siteId, templateInfo.Id);
                    }
                }
            }
            if (isDeleteFiles)
            {
                DirectoryUtility.DeleteSiteFiles(siteInfo);
            }

            //导入文件
            importObject.ImportFiles(siteTemplatePath, isOverride);

            //导入模板
            var templateFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileTemplate);

            importObject.ImportTemplates(templateFilePath, isOverride, administratorName);

            //导入辅助表
            var tableDirectoryPath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.Table);

            importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTable);

            //导入站点设置
            var configurationFilePath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.FileConfiguration);

            importObject.ImportConfiguration(configurationFilePath);

            //导入栏目及内容
            var siteContentDirectoryPath = PathUtils.Combine(siteTemplateMetadataPath, DirectoryUtils.SiteTemplates.SiteContent);

            importObject.ImportChannelsAndContents(0, siteContentDirectoryPath, isOverride);

            DataProvider.ChannelDao.UpdateContentNum(siteInfo);

            //导入表样式及清除缓存
            if (isUseTable)
            {
                importObject.ImportTableStyles(tableDirectoryPath);
            }
            importObject.RemoveDbCache();

            CacheUtils.ClearAll();
        }
예제 #30
0
        public static NodeUpdateStatus Update(CategoryInfo cate)
        {
            CategoryInfo     dataById = Category.GetDataById(cate.AutoID);
            NodeUpdateStatus result;

            if (Category.GetCount(string.Concat(new object[]
            {
                "UrlRewriteName='",
                cate.UrlRewriteName,
                "' AND AutoID<>",
                cate.AutoID
            })) > 0)
            {
                result = NodeUpdateStatus.ExistsNodeIdentifier;
            }
            else
            {
                if (dataById.ParentID != cate.ParentID)
                {
                    if (cate.ParentID.Equals(dataById.AutoID))
                    {
                        result = NodeUpdateStatus.UnNodeSelf;
                        return(result);
                    }
                    if (cate.ParentID == 0)
                    {
                        cate.ParentID   = 0;
                        cate.Depth      = 1;
                        cate.ParentPath = "0";
                        cate.RootID     = cate.AutoID;
                    }
                    else
                    {
                        CategoryInfo cacheCategoryByID = Category.GetCacheCategoryByID(cate.ParentID);
                        cate.ParentID   = cacheCategoryByID.AutoID;
                        cate.ParentPath = cacheCategoryByID.ParentPath + "," + cacheCategoryByID.AutoID.ToString();
                        cate.RootID     = cacheCategoryByID.RootID;
                        cate.Depth      = cacheCategoryByID.Depth + 1;
                    }
                    if (dataById.ParentID > 0)
                    {
                        CategoryInfo dataById2 = Category.GetDataById(dataById.ParentID);
                        dataById2.ChildCount--;
                        BizBase.dbo.UpdateModel <CategoryInfo>(dataById2);
                        Category.UpdateOrigleParents(dataById);
                    }
                    if (cate.ParentPath != "0")
                    {
                        CategoryInfo dataById3 = Category.GetDataById(cate.ParentID);
                        dataById3.ChildCount++;
                        BizBase.dbo.UpdateModel <CategoryInfo>(dataById3);
                        Category.UpdateNowParents(cate, "Modify");
                    }
                    int depth       = dataById.Depth;
                    int depth2      = cate.Depth;
                    int intDepthCha = depth2 - depth;
                    Category.UpdateChildList(cate, intDepthCha);
                }
                if (BizBase.dbo.UpdateModel <CategoryInfo>(cate))
                {
                    CacheUtils.Del("JsonLeeCMS_CacheForProCATEGORY");
                    result = NodeUpdateStatus.Success;
                }
                else
                {
                    CacheUtils.Del("JsonLeeCMS_CacheForProCATEGORY");
                    result = NodeUpdateStatus.Error;
                }
            }
            return(result);
        }