public HttpResponseMessage CreateEntry(Entry e) { try { /* we're taking in an entry, and want to update the basics */ e.CreatedOnDate = DateTime.UtcNow; e.CreatedByUserId = -1; e.LastModifiedOnDate = DateTime.UtcNow; e.LastModifiedByUserId = -1; /* if we don't have a moduleId coming in, let's look it up */ if (e.ModuleId < 1) { //look up module var mc = new ModuleController(); var mi = mc.GetModuleByDefinition(0, "VehiDataCollector"); //TODO: assuming PortalId=0 if moduleid =0 if (mi != null) { e.ModuleId = mi.ModuleID; } } var vc = new EntryController(); vc.CreateEntry(e); return(Request.CreateResponse(HttpStatusCode.OK, "valid")); } catch (Exception exc) { DnnLog.Error(exc); //todo: obsolete return(Request.CreateResponse(HttpStatusCode.BadRequest, "error in request")); //todo: probably should localize that? } }
private bool IsFileExpired(string file) { StreamReader oRead = null; try { var Lines = File.ReadAllLines(file); DateTime expires = DateTime.Parse(Lines[0], CultureInfo.InvariantCulture); if (expires < DateTime.UtcNow) { return(true); } else { return(false); } } catch (Exception ex) { //if check expire time failed, then force to expire the cache. DnnLog.Error(ex); return(true); } finally { if (oRead != null) { oRead.Close(); } } }
/// ----------------------------------------------------------------------------- /// <summary> /// cmdReset_Click runs when the Reset Button is clicked /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 03/03/2006 created /// </history> /// ----------------------------------------------------------------------------- private void cmdReset_Click(object sender, EventArgs e) { string answer = ""; if (MembershipProviderConfig.RequiresQuestionAndAnswer && !IsAdmin) { if (String.IsNullOrEmpty(txtAnswer.Text)) { OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); return; } answer = txtAnswer.Text; } try { UserController.ResetPassword(User, answer); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.Success)); } catch (ArgumentException exc) { DnnLog.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.InvalidPasswordAnswer)); } catch (Exception exc) { DnnLog.Error(exc); OnPasswordUpdated(new PasswordUpdatedEventArgs(PasswordUpdateStatus.PasswordResetFailed)); } }
/// ----------------------------------------------------------------------------- /// <summary> /// wizInstall_FinishButtonClick runs when the Finish Button on the Wizard is clicked. /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 08/13/2007 created /// </history> /// ----------------------------------------------------------------------------- protected void wizInstall_FinishButtonClick(object sender, WizardNavigationEventArgs e) { try { if (!String.IsNullOrEmpty(TempInstallFolder) && Directory.Exists(TempInstallFolder)) { Directory.Delete(TempInstallFolder, true); } if (DeleteFile) { // delete file try { File.SetAttributes(FileName, FileAttributes.Normal); File.Delete(FileName); } catch (Exception exc) { DnnLog.Error(exc); } } //Redirect to Definitions page Response.Redirect(ReturnURL, true); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } }
public ActionResult AcceptFriend(int notificationId) { var success = false; try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(notificationId, UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(notificationId); int userRelationshipId; if (int.TryParse(notification.Context, out userRelationshipId)) { var userRelationship = RelationshipController.Instance.GetUserRelationship(userRelationshipId); if (userRelationship != null) { var friend = UserController.GetUserById(PortalSettings.PortalId, userRelationship.UserId); FriendsController.Instance.AcceptFriend(friend); success = true; } } } } catch (Exception exc) { DnnLog.Error(exc); } return(Json(new { Result = success ? "success" : "error" })); }
//[DnnAuthorize(AllowAnonymous = true)] public HttpResponseMessage GetArticle(int articleId) { try { var a = ArticleController.GetArticle(articleId); var newArt = new ArticleViewModel { ArticleId = a.ArticleId, Body = WebUtility.HtmlDecode(a.Body), CreatedByUser = a.CreatedByUser, CreatedByUserId = a.CreatedByUserId, CreatedOnDate = a.CreatedOnDate, Description = WebUtility.HtmlDecode(a.Description), LastModifiedByUser = a.LastUpdatedByUser, LastModifiedByUserId = a.LastModifiedByUserId, LastModifiedOnDate = a.LastModifiedOnDate, ModuleId = a.ModuleId, Title = a.Title, url = DotNetNuke.Common.Globals.NavigateURL(a.TabID, "", "&aid=" + a.ArticleId) }; return(Request.CreateResponse(HttpStatusCode.OK, newArt)); } catch (Exception exc) { DnnLog.Error(exc); //todo: obsolete return(Request.CreateResponse(HttpStatusCode.BadRequest, "error in request")); //todo: probably should localize that? } }
public string CommentSave(int journalId, string comment) { try { var ci = new CommentInfo { JournalId = journalId, Comment = HttpUtility.UrlDecode(comment) }; if (ci.Comment.Length > 2000) { ci.Comment = ci.Comment.Substring(0, 1999); ci.Comment = Utilities.RemoveHTML(ci.Comment); } ci.UserId = UserInfo.UserID; InternalJournalController.Instance.SaveComment(ci); var ji = JournalController.Instance.GetJournalItem(PortalSettings.PortalId, UserInfo.UserID, journalId); var jp = new JournalParser(PortalSettings, ActiveModule.ModuleID, ji.ProfileId, -1, UserInfo); return(jp.GetCommentRow(ci)); } catch (Exception exc) { DnnLog.Error(exc); return(string.Empty); } }
private void OnPageInit(object sender, EventArgs e) { try { var page = (System.Web.UI.Page)sender; if ((page == null)) { return; } //ManageRequest(page, PortalSettings.Current.PortalId, PortalSettings.Current.ActiveTab.TabID); } catch (Exception ex) { /* * var objEventLog = new EventLogController(); * var objEventLogInfo = new LogInfo(); * objEventLogInfo.AddProperty("Analytics.AnalyticsModule", "OnPageLoad"); * objEventLogInfo.AddProperty("ExceptionMessage", ex.Message); * objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(); * objEventLog.AddLog(objEventLogInfo); */ DnnLog.Error(ex); } }
public ActionResult JoinGroup(int roleId) { try { if (UserInfo.UserID >= 0 && roleId > 0) { var roleController = new RoleController(); roleInfo = roleController.GetRole(roleId, PortalSettings.PortalId); if (roleInfo != null) { var requireApproval = Convert.ToBoolean(roleInfo.Settings["ReviewMembers"].ToString()); if (roleInfo.IsPublic && !requireApproval) { roleController.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, roleInfo.RoleID, Null.NullDate); roleController.UpdateRole(roleInfo); return(Json(new { Result = "success", URL = roleInfo.Settings["URL"] })); } if (roleInfo.IsPublic && requireApproval) { roleController.AddUserRole(PortalSettings.PortalId, UserInfo.UserID, roleInfo.RoleID, RoleStatus.Pending, false, Null.NullDate, Null.NullDate); Components.Notifications notifications = new Components.Notifications(); notifications.AddGroupOwnerNotification(Constants.MemberPendingNotification, TabId, ModuleId, roleInfo, UserInfo); return(Json(new { Result = "success", URL = string.Empty })); } } } } catch (Exception exc) { DnnLog.Error(exc); } return(Json(new { Result = "error" })); }
//[AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveGame(Game jsonGame) { //todo: jsonGame will never be null, check for something else if (jsonGame != null) { var currentGame = jsonGame; try { var gc = new GameController(); //TODO: Save Game if (currentGame != null) { //we need to lookup the game based on the GameId if passed in the json, if so, then combine all the new stats if (currentGame.GameId > 0) { var existingGame = gc.GetGame(currentGame.GameId); currentGame.FieldIdentifier = existingGame.FieldIdentifier; currentGame.CreatedDate = existingGame.CreatedDate; currentGame.CreatedByUserId = existingGame.CreatedByUserId; } else { currentGame.CreatedDate = DateTime.Now; currentGame.CreatedByUserId = 1; //check if a Field exists, if not add it var f = FieldController.GetField(currentGame.FieldIdentifier); if (f == null) { f = new Field { FieldIdentifier = currentGame.FieldIdentifier, FieldName = currentGame.FieldIdentifier, CreatedByUserId = 1, CreatedDate = DateTime.Now, LastUpdatedByUserId = 1, LastUpdatedDate = DateTime.Now }; f = f.Save(); } currentGame.FieldIdentifier = f.FieldIdentifier; } currentGame.LastUpdatedByUserId = 1; currentGame.PlayedDate = DateTime.Now; currentGame.PortalId = PortalSettings.PortalId; //save the game information currentGame = gc.SaveGame(currentGame); //TODO: how to flag games in progress? //return the GameID so Netduino knows to use this return(Json(currentGame.GameId, JsonRequestBehavior.AllowGet)); } return(null); } catch (Exception exc) { DnnLog.Error(exc); return(Json(null, JsonRequestBehavior.AllowGet)); } } return(null); }
/// ----------------------------------------------------------------------------- /// <summary> /// lstTemplate_SelectedIndexChanged runs when the selected template is changed /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 11/04/2004 created /// </history> /// ----------------------------------------------------------------------------- protected void OnTemplateSelectedIndexChanged(object sender, EventArgs e) { if (lstTemplate.SelectedIndex > -1) { try { var template = LoadPortalTemplateInfoForSelectedItem(); if (!string.IsNullOrEmpty(template.Description)) { lblTemplateDescription.Text = template.Description; } var xmlDoc = new XmlDocument(); xmlDoc.Load(template.TemplateFilePath); XmlNode node = xmlDoc.SelectSingleNode("//portal/portalDesktopModules"); if (node != null) { var message = PortalController.CheckDesktopModulesInstalled(node.CreateNavigator()); if (!string.IsNullOrEmpty(message)) { message = string.Format(LocalizeString("ModulesNotInstalled"), message); UI.Skins.Skin.AddModuleMessage(this, message, ModuleMessage.ModuleMessageType.YellowWarning); } } } catch (Exception exc) { DnnLog.Error(exc); } } else { lblTemplateDescription.Text = ""; } }
public IList <Route> MapRoute(string moduleFolderName, string url, object defaults, object constraints, string[] namespaces) { if (namespaces == null || namespaces.Length == 0 || String.IsNullOrEmpty(namespaces[0])) { throw new ArgumentException("At least one namespace must be specified."); } if (String.IsNullOrEmpty(moduleFolderName)) { throw new ArgumentNullException("moduleFolderName"); } url = url.Trim(new[] { '/', '\\' }); var prefixes = GetRoutePrefixes(); var routes = new List <Route>(); string formattedRouteName = GetFormattedRouteName(moduleFolderName); int i = 0; foreach (var prefix in prefixes) { var routeName = string.Format(formattedRouteName, i); var routeUrl = string.Format("{0}DesktopModules/{1}/API/{2}", prefix, moduleFolderName, url); var route = _routes.MapRoute(routeName, routeUrl, defaults, constraints, namespaces); route.DataTokens["Name"] = routeName; routes.Add(route); DnnLog.Trace("Mapping route: " + routeName + " @ " + routeUrl); i++; } return(routes); }
public static string UpdateValidationKey() { string backupFolder = Globals.glbConfigFolder + "Backup_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + "\\"; var xmlConfig = new XmlDocument(); string strError = ""; //save the current config files BackupConfig(); try { //open the web.config xmlConfig = Load(); //create random keys for the Membership machine keys xmlConfig = UpdateValidationKey(xmlConfig); } catch (Exception ex) { DnnLog.Error(ex); strError += ex.Message; } //save a copy of the web.config strError += Save(xmlConfig, backupFolder + "web_.config"); //save the web.config strError += Save(xmlConfig); return(strError); }
public static string Save(XmlDocument xmlDoc, string filename) { try { string strFilePath = Globals.ApplicationMapPath + "\\" + filename; FileAttributes objFileAttributes = FileAttributes.Normal; if (File.Exists(strFilePath)) { //save current file attributes objFileAttributes = File.GetAttributes(strFilePath); //change to normal ( in case it is flagged as read-only ) File.SetAttributes(strFilePath, FileAttributes.Normal); } //save the config file var writer = new XmlTextWriter(strFilePath, null) { Formatting = Formatting.Indented }; xmlDoc.WriteTo(writer); writer.Flush(); writer.Close(); //reset file attributes File.SetAttributes(strFilePath, objFileAttributes); return(""); } catch (Exception exc) { //the file permissions may not be set properly DnnLog.Error(exc); return(exc.Message); } }
private static LogInfo FillLogInfo(IDataReader dr) { var obj = new LogInfo(); try { obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"]); obj.LogGUID = Convert.ToString(dr["LogGUID"]); if (dr["LogPortalID"] != DBNull.Value) { obj.LogPortalID = Convert.ToInt32(dr["LogPortalID"]); } if (dr["LogPortalName"] != DBNull.Value) { obj.LogPortalName = Convert.ToString(dr["LogPortalName"]); } if (dr["LogServerName"] != DBNull.Value) { obj.LogServerName = Convert.ToString(dr["LogServerName"]); } if (dr["LogUserID"] != DBNull.Value) { obj.LogUserID = Convert.ToInt32(dr["LogUserID"]); } obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"]); obj.LogUserName = Convert.ToString(dr["LogUserName"]); obj.LogConfigID = Convert.ToString(dr["LogConfigID"]); obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"])); } catch (Exception exc) { DnnLog.Error(exc); } return(obj); }
public ActionResult LeaveGroup(int roleId) { var success = false; try { if (UserInfo.UserID >= 0 && roleId > 0) { var roleController = new RoleController(); roleInfo = roleController.GetRole(roleId, PortalSettings.PortalId); if (roleInfo != null) { if (UserInfo.IsInRole(roleInfo.RoleName)) { RoleController.DeleteUserRole(UserInfo, roleInfo, PortalSettings, false); } success = true; } } } catch (Exception exc) { DnnLog.Error(exc); } return(Json(new { Result = success ? "success" : "error" })); }
protected override void OnError(EventArgs e) { base.OnError(e); Exception exc = Server.GetLastError(); DnnLog.Fatal("An error has occurred while loading page.", exc); string strURL = Globals.ApplicationURL(); if (exc != null && exc is HttpException && !IsViewStateFailure(exc)) { HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); } if (Request.QueryString["error"] != null) { strURL += (strURL.IndexOf("?") == -1 ? "?" : "&") + "error=terminate"; } else { strURL += (strURL.IndexOf("?") == -1 ? "?" : "&") + "error=" + (exc == null || UserController.GetCurrentUserInfo() == null || !UserController.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : Server.UrlEncode(exc.Message)); if (!Globals.IsAdminControl()) { strURL += "&content=0"; } } Exceptions.ProcessPageLoadException(exc, strURL); }
/// ----------------------------------------------------------------------------- /// <summary> /// DeleteRule runs when the Delete button for a specified rule is clicked /// </summary> /// <remarks> /// </remarks> /// <history> /// [jbrinkman] 5/28/2007 Created /// </history> /// ----------------------------------------------------------------------------- protected void DeleteRule(object source, DataListCommandEventArgs e) { //Get the index of the row to delete int index = e.Item.ItemIndex; //Remove the rule from the rules collection Rules.RemoveAt(index); try { //Save the new collection RequestFilterSettings.Save(Rules); } catch (UnauthorizedAccessException exc) { DnnLog.Debug(exc); lblErr.InnerText = Localization.GetString("unauthorized", LocalResourceFile); lblErr.Visible = true; //This forces the system to reload the settings from DotNetNuke.Config //since we have already deleted the entry from the Rules list. Rules = null; } //Rebind the collection BindRules(); }
public ActionResult Delete(int journalId) { try { var jc = JournalController.Instance; var ji = jc.GetJournalItem(PortalSettings.PortalId, UserInfo.UserID, journalId); if (ji == null) { return(Json(new { Result = "invalid request" }, JsonRequestBehavior.AllowGet)); } if (ji.UserId == UserInfo.UserID || UserInfo.IsInRole(PortalSettings.AdministratorRoleName)) { jc.DeleteJournalItem(PortalSettings.PortalId, UserInfo.UserID, journalId); return(Json(new { Result = "success" }, JsonRequestBehavior.AllowGet)); } return(Json(new { Result = "access denied" }, JsonRequestBehavior.AllowGet)); } catch (Exception exc) { DnnLog.Error(exc); return(Json(new { Result = "error" })); } }
public string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings, bool disableShowMissingKeys) { //make the default translation property ".Text" if (key.IndexOf(".", StringComparison.Ordinal) < 1) { key += ".Text"; } string resourceValue = Null.NullString; bool keyFound = TryGetStringInternal(key, language, resourceFileRoot, portalSettings, ref resourceValue); //If the key can't be found then it doesn't exist in the Localization Resources if (Localization.ShowMissingKeys && !disableShowMissingKeys) { if (keyFound) { resourceValue = "[L]" + resourceValue; } else { resourceValue = "RESX:" + key; } } if (!keyFound) { DnnLog.Warn("Missing localization key. key:{0} resFileRoot:{1} threadCulture:{2} userlan:{3}", key, resourceFileRoot, Thread.CurrentThread.CurrentUICulture, language); } return(resourceValue); }
private void OnUpdateRequestCache(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; try { var HttpContextFilter = context.Items["OpenOutputCache:Filter"]; //OpenOutputCacheFilter filter = context.Response.Filter as OpenOutputCacheFilter; if (HttpContextFilter != null) { //PortalSettings ps = PortalController.GetCurrentPortalSettings(); //int TabId = ps.ActiveTab.TabID; OpenOutputCacheFilter filter = (OpenOutputCacheFilter)HttpContext.Current.Items["OpenOutputCache:Filter"]; filter.StopFiltering(); var Response = context.Response; Response.Cache.SetLastModified(DateTime.UtcNow); string CacheMode = (string)app.Context.Items["OpenOutputCache:CacheMode"]; int ExpireDelay = (int)app.Context.Items["OpenOutputCache:ExpireDelay"]; SetResponseCache(Response, filter.CacheKey, ExpireDelay, CacheMode); Logger.InfoFormat("OnUpdateRequestCache {0} / {1}", filter.TabId, filter.CacheKey); } } catch (Exception ex) { DnnLog.Error(ex); } }
private static Version GetNETFrameworkVersion() { string version = Environment.Version.ToString(2); if (version == "2.0") { //Try and load a 3.0 Assembly try { AppDomain.CurrentDomain.Load("System.Runtime.Serialization, Version=3.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"); version = "3.0"; } catch (Exception exc) { DnnLog.Error(exc); } //Try and load a 3.5 Assembly try { AppDomain.CurrentDomain.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"); version = "3.5"; } catch (Exception exc) { DnnLog.Error(exc); } } return(new Version(version)); }
public HttpResponseMessage GetAllAnnouncements(string output) { try { var mc = new ModuleController(); var results = new List <AnnouncementInfo>(); // get list of all announcements modules in the site var annModules = mc.GetModulesByDefinition(PortalSettings.PortalId, "Announcements"); // loop through all the modules foreach (ModuleInfo m in annModules) { // make sure to only include modules the user actually has access to if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.View, "VIEW", m)) { // get the current announcements of the module IEnumerable <Components.Business.AnnouncementInfo> baseResults = new Components.Business.AnnouncementsController().GetCurrentAnnouncements(m.ModuleID); // add to the total results list results.AddRange(baseResults.Select(announcementInfo => new AnnouncementInfo(announcementInfo)).ToList()); } } return(GenerateOutput(results.OrderByDescending(a => a.PublishDate).ToList(), output)); } catch (Exception ex) { DnnLog.Error(ex); return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public static void RunSchedule(HttpRequest request) { DnnLog.MethodEntry(); //First check if we are upgrading/installing if (request.Url.LocalPath.ToLower().EndsWith("install.aspx") || request.Url.LocalPath.ToLower().EndsWith("upgradewizard.aspx") || request.Url.LocalPath.ToLower().EndsWith("installwizard.aspx")) { return; } try { if (SchedulingProvider.SchedulerMode == SchedulerMode.REQUEST_METHOD && SchedulingProvider.ReadyForPoll) { DnnLog.Trace("Running Schedule " + (SchedulingProvider.SchedulerMode)); SchedulingProvider scheduler = SchedulingProvider.Instance(); var requestScheduleThread = new Thread(scheduler.ExecuteTasks); requestScheduleThread.IsBackground = true; requestScheduleThread.Start(); SchedulingProvider.ScheduleLastPolled = DateTime.Now; } } catch (Exception exc) { Exceptions.LogException(exc); } }
public ActionResult FollowBack(int notificationId) { var success = false; try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(notificationId, UserInfo.UserID); if (recipient != null) { var notification = NotificationsController.Instance.GetNotification(notificationId); int targetUserId; if (int.TryParse(notification.Context, out targetUserId)) { var targetUser = UserController.GetUserById(PortalSettings.PortalId, targetUserId); FollowersController.Instance.FollowUser(targetUser); NotificationsController.Instance.DeleteNotificationRecipient(notificationId, UserInfo.UserID); success = true; } } } catch (Exception exc) { DnnLog.Error(exc); } return(Json(new { Result = success ? "success" : "error" })); }
public ActionResult SaveSlide(int tabId, int moduleId, string slideContent, int slideOrder, int slideId) { //not currently using slide order try { //TODO: create a new slide //if slideid is passed in we should get the original slide var saveSlide = new Slide(); if (slideId > 0) { saveSlide = Slide.SlideLoad(slideId); } else { saveSlide.CreatedByUserId = UserInfo.UserID; saveSlide.CreatedOnDate = DateTime.UtcNow; saveSlide.ModuleId = moduleId; } saveSlide.LastModifiedByUserId = UserInfo.UserID; saveSlide.LastModifiedOnDate = DateTime.UtcNow; saveSlide.Body = slideContent; saveSlide.Save(tabId); //TODO: return something if the slide is created return(null); } catch (Exception exc) { DnnLog.Error(exc); return(Json(null, JsonRequestBehavior.AllowGet)); } }
public override bool StreamOutput(int tabId, string cacheKey, HttpContext context) { bool Succes = false; try { string attribFileName = OpenFileProvider.GetAttribFileName(tabId, cacheKey); string cachedOutputFileName = OpenFileProvider.GetCachedOutputFileName(tabId, cacheKey); if (File.Exists(attribFileName) && File.Exists(cachedOutputFileName) && !IsFileExpired(attribFileName)) { var Response = context.Response; DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(cachedOutputFileName); Response.Cache.SetLastModified(lastWriteTimeUtc); bool send304 = false; HttpRequest request = context.Request; string ifModifiedSinceHeader = request.Headers["If-Modified-Since"]; string etag = request.Headers["If-None-Match"]; if (ifModifiedSinceHeader != null && etag != null) { etag = etag.Trim('"'); try { DateTime utcIfModifiedSince = DateTime.Parse(ifModifiedSinceHeader); if (lastWriteTimeUtc <= utcIfModifiedSince && etag == cacheKey) { Response.StatusCode = 304; Response.StatusDescription = "Not Modified"; Response.SuppressContent = true; //Response.ClearContent(); Response.AddHeader("Content-Length", "0"); send304 = true; } } catch { DnnLog.Error("Ignore If-Modified-Since header, invalid format: " + ifModifiedSinceHeader); } } if (!send304) { context.Response.TransmitFile(cachedOutputFileName); } Succes = true; } else { FileSystemUtils.DeleteFileWithWait(attribFileName, 100, 200); FileSystemUtils.DeleteFileWithWait(cachedOutputFileName, 100, 200); Succes = false; } } catch (Exception ex) { Succes = false; DnnLog.Error(ex); } return(Succes); }
public void TryIt() { var currentDelay = (int)Delay.TotalMilliseconds; int retrysRemaining = MaxRetries; do { try { Action(); DnnLog.Trace("Action succeeded - {0}", Description); return; } catch (Exception) { if (retrysRemaining <= 0) { DnnLog.Warn("All retries of action failed - {0}", Description); throw; } DnnLog.Trace("Retrying action {0} - {1}", retrysRemaining, Description); SleepAction.Invoke(currentDelay); const double epsilon = 0.0001; if (Math.Abs(DelayMultiplier - 1) > epsilon) { currentDelay = (int)(currentDelay * DelayMultiplier); } } retrysRemaining--; } while (true); }
internal static IEnumerable <IFileInfo> DeserializeFileInfo(string content) { if (string.IsNullOrEmpty(content)) { yield break; } foreach (var file in content.FromJson <int[]>().ToArray()) { IFileInfo fileInfo = null; try { fileInfo = FileManager.Instance.GetFile(file); } catch { // throw new ApplicationException(string.Format("Error loading file properties for FileID '{0}'", file), ex); // On second thought, I don't know how much sense it makes to be throwing an exception here. If the file // has been deleted or is otherwise unavailable, there's really no reason we can't continue on handling the // ContentItem without its attachment. Better than the yellow screen of death? --cbond DnnLog.Warn("Unable to load file properties for File ID {0}", file); } if (fileInfo != null) { yield return(fileInfo); } } }
public ActionResult GetItems(string fileExtensions) { try { var userFolder = _folderManager.GetUserFolder(UserInfo); var extensions = new List <string>(); if (!string.IsNullOrEmpty(fileExtensions)) { fileExtensions = fileExtensions.ToLowerInvariant(); extensions.AddRange(fileExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); } var folderStructure = new Item { children = GetChildren(userFolder, extensions), folder = true, id = userFolder.FolderID, name = Localization.GetString("UserFolderTitle.Text", Localization.SharedResourceFile) }; return(Json(new List <Item> { folderStructure }, JsonRequestBehavior.AllowGet)); } catch (Exception exc) { DnnLog.Error(exc); return(Json(null, JsonRequestBehavior.AllowGet)); } }