Skip to content

Commit

Permalink
moved one-minute scheduler out of Server class into its own class
Browse files Browse the repository at this point in the history
  • Loading branch information
markentingh committed Apr 29, 2017
1 parent 43b945b commit a3eae09
Show file tree
Hide file tree
Showing 16 changed files with 275 additions and 177 deletions.
9 changes: 7 additions & 2 deletions App/Components/Login/new-pass.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

if (err == false) {
//show success message
S.message.show(msg, '', 'Your password has been updated. Go ahead and <a href="javascript:window.location.reload()">Log In</a> with your new password');
window.location.reload();
} else {
//show error message
S.message.show(msg, 'error', 'An error occurred while trying to update your password');
Expand All @@ -53,4 +53,9 @@
//add event listeners
$('#password, #password2').on('input', S.login.watchPass);
$('#btnsavepass').on('click', S.login.savePass);
$('.login form').on('submit', function (e) { S.login.savePass(); e.preventDefault(); return false; });
$('.login form').on('submit', function (e) {
e.preventDefault();
e.cancelBubble = true;
S.login.savePass();
return false;
});
2 changes: 1 addition & 1 deletion App/Core/Component.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public struct structPosition
public Page Page;

public string id = ""; //unique ID
public int blockId = 0;
public string blockId = "";
public string panelId = ""; //unique ID of panel this component belongs to
public string panelCellId = ""; //unique ID of panel cell this component belongs to

Expand Down
68 changes: 42 additions & 26 deletions App/Core/Page.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public struct structArea
public struct structBlock
{
public string name;
public int id;
public string id;
public bool isPage;
public List<Component> components;
public bool changed;
Expand Down Expand Up @@ -160,6 +160,10 @@ public void getPageInfoFromUrl(structUrl url)
{
loadPageInfo(reader);
}
else
{
break;
}
}
else
{
Expand Down Expand Up @@ -325,6 +329,19 @@ public structPage loadPage(bool fromCache = true)
}
else
{
//check if website has been initialized yet
if(Url.path == "login")
{
if (!S.Server.Cache.ContainsKey("init_website"))
{
//initialize new website
S.Server.Cache.Add("init_website", 1);
var test = new Services.Init(S);
test.Website();
S.Server.Cache.Remove("init_website");
return loadPage();
}
}
//initialize a new page
page = new structPage();
page.areas = new List<structArea>();
Expand All @@ -337,7 +354,7 @@ public structPage loadPage(bool fromCache = true)
//load blocks associated with this page
for (var x = 0; x < area.blocks.Count; x++)
{
if(area.blocks[x].isPage == false && area.blocks[x].id > 0)
if(area.blocks[x].isPage == false && area.blocks[x].id.IndexOf("page_") < 0)
{
//external block
area.blocks[x] = loadBlock(area.blocks[x].id, fromCache);
Expand Down Expand Up @@ -399,7 +416,7 @@ public Tuple<Scaffold, List<structArea>, structPage, List<Panel>> loadPageAndLay
//add page-level block to empty area
area.blocks.Add(new structBlock()
{
id = 0,
id = "page_" + area.name.ToLower(),
name = "Page " + S.Util.Str.Capitalize(area.name),
isPage = true,
components = new List<Component>()
Expand Down Expand Up @@ -569,17 +586,17 @@ public string Render()
#endregion

#region "Blocks"
public string GetBlockFilePath(int blockid = 0, string specialFolder = "", string blockType = "")
public string GetBlockFilePath(string blockid = "", string specialFolder = "", string blockType = "")
{

var path = "/Content/websites/" +
websiteId + "/blocks/" + blockid.ToString() + "/" +
websiteId + "/blocks/" + blockid + "/" +
(specialFolder != "" ? specialFolder + "/" : "") +
(blockType != "" ? blockType + "_" : "") + "block.json";
return path;
}

public structBlock loadBlock(int blockid, bool fromCache = true)
public structBlock loadBlock(string blockid, bool fromCache = true)
{
var block = new structBlock();
var filename = GetBlockFilePath(blockid, editFolder, editType);
Expand All @@ -592,7 +609,7 @@ public structBlock loadBlock(int blockid, bool fromCache = true)
{
//initialize new block & save to file
var sqlEditor = new SqlQueries.Editor(S);
var reader = sqlEditor.GetBlock(blockid);
var reader = sqlEditor.GetBlock(int.Parse(blockid));
if (reader.Read())
{
block.components = new List<Component>();
Expand Down Expand Up @@ -660,7 +677,7 @@ public void UpdateBlock(ref structPage page, structBlock block)

#region "Panels"

public Panel CreatePanel(string id, string name, string area, int blockId, string blockName = "", bool isPageLevelBlock = false)
public Panel CreatePanel(string id, string name, string area, string blockId, string blockName = "", bool isPageLevelBlock = false)
{
var panel = new Panel(S, this, id, name, S.Util.Str.Capitalize(area.Replace("-", " ")), blockId, blockName, isPageLevelBlock);
panel.cells = new List<Panel.structCell>();
Expand Down Expand Up @@ -815,7 +832,7 @@ public void loadComponents(structBlock block, Panel blockPanel, ref List<Panel>
/// <param name="panel">instance of the panel which contains the cell instance</param>
/// <param name="cell">panel cell instance to load the component into</param>
/// <returns></returns>
public Component createNewComponent(string name, string panelId, string cellId, int blockId)
public Component createNewComponent(string name, string panelId, string cellId, string blockId)
{
//first, find component class by name
string className = "Websilk.Components." + name;
Expand Down Expand Up @@ -855,50 +872,49 @@ public List<Component> GetAllComponents(List<Panel> panels)
#endregion

#region "Save"
public void SavePage(structPage page, bool saveToDisk = false)
public Utility.IgnorableContractResolver IgnorablePagePropertiesResolver(bool ignore = true)
{
StripCustomBlocks(page);
var path = GetPageFilePath(page.pageId, editFolder, editType);
//create contract resolver that removes ignored properties from an object before serializing the object
var contractResolver = new Utility.IgnorableContractResolver();
if (saveToDisk == true)
if(ignore == true)
{
//ignore any properties that are used only for cached pages
contractResolver.Ignore(typeof(structBlock), "changed");
}
var serialize = S.Util.Serializer.WriteObjectAsString(page, Formatting.None, TypeNameHandling.Auto, contractResolver);
return contractResolver;
}

public void SavePage(structPage page, bool saveToDisk = false)
{
StripCustomBlocks(page);
var path = GetPageFilePath(page.pageId, editFolder, editType);
var serialize = S.Util.Serializer.WriteObjectAsString(page, Formatting.None, TypeNameHandling.Auto, IgnorablePagePropertiesResolver(saveToDisk));
S.Server.SaveToCache(path, serialize);
if (saveToDisk == true)
{
//schedule save to file system
S.Server.ScheduleSaveFile(S.Server.MapPath(path), serialize);
S.Server.ScheduleEveryMinute.ScheduleSaveFile(S.Server.MapPath(path), serialize);

//schedule save page to history on file system
var now = DateTime.Now;
var historyPath = GetPageFilePath(page.pageId, "history/" + now.ToString("yyyy"), now.ToString("MM_dd_H_mm"));
S.Server.ScheduleSaveFile(S.Server.MapPath(historyPath), serialize);
S.Server.ScheduleEveryMinute.ScheduleSaveFile(S.Server.MapPath(historyPath), serialize);
}
}

public void SaveBlock(structBlock block, bool saveToDisk = false)
{
var path = GetBlockFilePath(block.id, editFolder, editType);
var contractResolver = new Utility.IgnorableContractResolver();
if(saveToDisk == true)
{
//ignore any properties that are used only for cached blocks
contractResolver.Ignore(typeof(structBlock), "changed");
}
var serialize = S.Util.Serializer.WriteObjectAsString(block, Formatting.None, TypeNameHandling.Auto, contractResolver);
var serialize = S.Util.Serializer.WriteObjectAsString(block, Formatting.None, TypeNameHandling.Auto, IgnorablePagePropertiesResolver(saveToDisk));
S.Server.SaveToCache(path, serialize);
if (saveToDisk == true)
{
//schedule save block to file system
S.Server.ScheduleSaveFile(S.Server.MapPath(path), serialize);
S.Server.ScheduleEveryMinute.ScheduleSaveFile(S.Server.MapPath(path), serialize);

//schedule save block to history on file system
var now = DateTime.Now;
var historyPath = GetBlockFilePath(block.id, "history/" + now.ToString("yyyy"), now.ToString("MM_dd_H_mm"));
S.Server.ScheduleSaveFile(S.Server.MapPath(historyPath), serialize);
S.Server.ScheduleEveryMinute.ScheduleSaveFile(S.Server.MapPath(historyPath), serialize);
}
}
#endregion
Expand Down
6 changes: 3 additions & 3 deletions App/Core/Panel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public struct structCell

public string name = ""; //a human-readable name for reference only
public string id = ""; //a unique ID
public int blockId = 0;
public string blockId = "";
public bool isPageBlock = false;
public string areaName = ""; //name of layout area this panel belongs to
public string blockName = ""; //name of block section to load into
Expand All @@ -104,7 +104,7 @@ public struct structCell
[JsonIgnore]
public string foot = "";

public Panel(Core WebsilkCore, Page page, string Id = "", string Name = "", string AreaName = "", int BlockId = 0, string BlockName = "", bool IsPageBlock = false)
public Panel(Core WebsilkCore, Page page, string Id = "", string Name = "", string AreaName = "", string BlockId = "", string BlockName = "", bool IsPageBlock = false)
{
S = WebsilkCore;
id = Id;
Expand Down Expand Up @@ -161,7 +161,7 @@ public string Render()
{
div.Attributes.Add("data-area", areaName);
div.Attributes.Add("data-block", blockName);
div.Attributes.Add("data-block-id", blockId.ToString());
div.Attributes.Add("data-block-id", blockId);
if(isPageBlock == true)
{
div.Attributes.Add("data-page-level", "true");
Expand Down
87 changes: 18 additions & 69 deletions App/Core/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Chroniton;

namespace Websilk
{
Expand All @@ -19,13 +18,6 @@ public enum enumEnvironment
production = 2
}

private struct saveFile
{
public string file;
public string data;
public DateTime created;
}

public string Version = "";
// #.#.#.#.#.# = years since github repo was created (10/22/2016) [#]
// current year, month, day of release [#.#.#]
Expand All @@ -41,7 +33,6 @@ private struct saveFile
public Random Random = new Random();
public bool resetPass = false;
public int bcrypt_workfactor = 10;
public int saveFileInterval = 20;
private string _path = "";


Expand All @@ -55,23 +46,16 @@ private struct saveFile
// where data is injected in between each array item.
public Dictionary<string, structScaffold> Scaffold = new Dictionary<string, structScaffold>();

//Scheduler that runs once every 1 minute
public Scheduler scheduleEveryMinute = new Scheduler();

//scheduler objects to check every 1 minute
private List<saveFile> scheduleSaveFiles = new List<saveFile>();

public Server()
{
//start 1 minute interval schedule
scheduleEveryMinute.Start(60, CheckScheduleEveryMinute);
}
//schedule that runs once every minute
public Schedule.EveryMinute ScheduleEveryMinute = new Schedule.EveryMinute();

#region "System.UI.Web.Page.Server methods"
public string path(string strPath = "")
{
if(_path == "") { _path = Path.GetFullPath(".") + "\\"; }
return _path + strPath.Replace("/", "\\");
if (_path == "") { _path = Path.GetFullPath(".") + "\\"; }
var str = strPath.Replace("/", "\\");
if (str.Substring(0, 1) == "\\") { str = str.Substring(1); }
return _path + str;
}

public string MapPath(string strPath = "") { return path(strPath); }
Expand Down Expand Up @@ -109,17 +93,25 @@ public void CheckAdminPassword()
/// <returns></returns>
public string LoadFileFromCache(string filename, bool noDevEnvCache = false, bool noCache = false)
{
if((environment != enumEnvironment.development || noDevEnvCache == false) && noCache == false)
//first, check scheduled save file list
if (ScheduleEveryMinute.HasScheduledSaveFile(MapPath(filename)))
{
return ScheduleEveryMinute.GetScheduledSaveFileData(MapPath(filename));
}

if ((environment != enumEnvironment.development || noDevEnvCache == false) && noCache == false)
{
//next, check cache
if (Cache.ContainsKey(filename))
{
return (string)Cache[filename];
}
}
if (File.Exists(MapPath(filename)))
{
//finally, check file system
var file = File.ReadAllText(MapPath(filename));
if(environment != enumEnvironment.development && noCache == false)
if (environment != enumEnvironment.development && noCache == false)
{
Cache.Add(filename, file);
}
Expand All @@ -133,55 +125,12 @@ public void SaveToCache(string key, string value)
if (Cache.ContainsKey(key))
{
Cache[key] = value;
}else
{
Cache.Add(key, value);
}
}
#endregion

#region "Scheduler"
private void CheckScheduleEveryMinute()
{
//check queue for files to save
if(scheduleSaveFiles.Count > 0)
{
foreach (var f in scheduleSaveFiles)
{
if((f.created - DateTime.Now).TotalMinutes >= saveFileInterval)
{
if (!Directory.Exists(Path.GetFullPath(f.file)))
{
Directory.CreateDirectory(Path.GetFullPath(f.file));
}
File.WriteAllText(f.file, f.data);
scheduleSaveFiles.Remove(f);
}
}
}
}

public void ScheduleSaveFile(string filePath, string data)
{
RemoveScheduledSaveFile(filePath);
scheduleSaveFiles.Add(new saveFile()
else
{
file = filePath,
data = data,
created = DateTime.Now
});
}

public void RemoveScheduledSaveFile(string filePath)
{
var i = scheduleSaveFiles.FindIndex(a => a.file == filePath);
if (i >= 0)
{
scheduleSaveFiles.RemoveAt(i);
Cache.Add(key, value);
}
}
#endregion
}


}
Loading

0 comments on commit a3eae09

Please sign in to comment.