/// <summary> /// Get Receivable Account /// </summary> /// <param name="db"></param> /// <returns></returns> public static List <string> GetCashAccounts(NancyBlackDatabase db) { var siteSettings = AdminModule.ReadSiteSettings(); if (siteSettings.accounting == null) { return(db.QueryAsDynamic("SELECT DISTINCT IncreaseAccount AS Name FROM AccountingEntry", new { Name = "" }) .AsEnumerable() .Select(item => (string)item.Name) .ToList()); } var accountSettings = (from dynamic item in siteSettings.accounting.accounts as JArray select new { Name = (string)item.Name, Type = (string)item.Type }).ToLookup(i => i.Name, i => i.Type); return(db.QueryAsDynamic("SELECT DISTINCT IncreaseAccount AS Name FROM AccountingEntry", new { Name = "" }) .AsEnumerable() .Select(item => (string)item.Name) .Where(s => string.IsNullOrEmpty(s) == false && accountSettings[s].FirstOrDefault() == "Cash") .ToList()); }
/// <summary> /// Pull serial numbers into ItemsDetail Serial Number Attribute /// </summary> public void EnsuresSerialNumberVisible(NancyBlackDatabase db) { if (this.Status == SaleOrderStatus.Delivered || this.Status == SaleOrderStatus.Shipped || this.Status == SaleOrderStatus.ReadyToShip || this.Status == SaleOrderStatus.Testing) { if (this.ItemsDetail.Any(p => p.Attributes == null || p.Attributes.Serial == null)) { var ivt = db.Query <InventoryItem>().Where(row => row.SaleOrderId == this.Id).ToLookup(row => row.ProductId); foreach (var item in this.ItemsDetail) { if (item.Attributes == null) { item.Attributes = new JObject(); } item.Attributes.Serial = string.Join(",", ivt[item.Id].Select(row => row.SerialNumber)); } db.UpsertRecord(this); } } }
private static void NancyBlackDatabase_ObjectUpdated(NancyBlackDatabase db, string table, dynamic obj) { if (table == "SaleOrder") { AccountingSystemModule.HandleCreditRequest(db, obj); } }
private static void NancyBlackDatabase_ObjectCreated(NancyBlackDatabase db, string table, dynamic obj) { if (table == "Receipt") { AccountingSystemModule.ProcessReceiptCreation(db, obj); } }
/// <summary> /// Find Ancestor of given affiliate code /// </summary> /// <param name="code"></param> /// <param name="db"></param> /// <returns></returns> private static List <string> DiscoverUpline(string code, NancyBlackDatabase db) { var ancestorList = new List <string>(); var currentCode = code; while (true) { var parent = db.Query <AffiliateRegistration>() .Where(r => r.AffiliateCode == currentCode) .FirstOrDefault(); if (parent == null || string.IsNullOrEmpty(parent.AffiliateCode) || parent.AffiliateCode == ancestorList.LastOrDefault() || // BUG in previous version of website ancestorList.Contains(parent.AffiliateCode)) // BUG in previous version of website { break; } ancestorList.Add(parent.AffiliateCode); currentCode = parent.RefererAffiliateCode; } return(ancestorList); }
/// <summary> /// Automatically create recurrance /// </summary> /// <param name="db"></param> /// <param name="entry"></param> internal static void ProcesAutoRecurranceCreation(NancyBlackDatabase db, AccountingEntry entry) { if (entry.Addendum == null) { return; } if (entry.Addendum.Recurring == true) { var lastPayment = (DateTime)entry.Addendum.LastPayment; var entries = new List <AccountingEntry>(); var start = entry.DueDate; var index = 2; while (start.AddMonths(1) <= lastPayment) { start = start.AddMonths(1); var copy = JObject.FromObject(entry).ToObject <AccountingEntry>(); copy.TransactionDate = start; copy.DueDate = start; copy.Id = 0; copy.Notes = "Recurring " + index + " of Entry:" + entry.Id + "\r\n" + entry.Notes; copy.Addendum.RecurringMaster = entry.Id; entries.Add(copy); index++; } db.Connection.InsertAll(entries); } }
private void UpdateTag_ObjectUpdate(NancyBlackDatabase db, string table, dynamic obj) { if (!(obj is IContent)) { return; } IContent content = obj; var type = content.GetType().Name; var existTags = db.Query <Tag>().Where(tag => tag.ContentId == content.Id && tag.Type == type); if (content.Tags != null) { var source = string.Join(",", content.Tags.Split(',').Distinct().OrderBy(s => s)).ToLowerInvariant(); var inDb = string.Join(",", existTags.ToList().Select(tag => tag.Name).OrderBy(s => s)).ToLowerInvariant(); // return when there is nothing change in tags if (source == inDb) { return; } } db.Transaction(() => { // delete exist tags for re-add new tags foreach (var tag in existTags) { db.DeleteRecord(tag); } // re-insert tag this.InsertTag(db, content); }); }
/// <summary> /// When inventory inbound is created, find the inventory item that needs to be fullfilled /// and fullfil with item from inventory inbound /// </summary> /// <param name="db"></param> /// <param name="obj"></param> internal static void ProcessInventoryInboundCreation(NancyBlackDatabase db, InventoryInbound obj) { // ensures that only one thread will be doing this lock (InventoryAdminModule.LockObject) { db.Transaction(() => { var inboundItems = new List <InventoryItem>(); foreach (var item in obj.Items) { InventoryItem ivitm = new InventoryItem(); ivitm.InboundDate = obj.InboundDate; ivitm.InventoryInboundId = obj.Id; ivitm.ProductId = item.ProductId; ivitm.BuyingCost = item.Price; ivitm.BuyingTax = item.Tax; db.UpsertRecord(ivitm); inboundItems.Add(ivitm); } InventoryAdminModule.InboundCompleted(db, obj, inboundItems); }); } }
/// <summary> /// Get child content of given url /// </summary> /// <param name="db">Reference to the database</param> /// <param name="url">Base Url</param> /// <param name="levels">Level of items to get, 0 means unlimited.</param> /// <returns></returns> public static IEnumerable <Page> GetChildPages(NancyBlackDatabase db, string url, int levels = 0) { if (url.StartsWith("/") == false) { url = "/" + url; } url = url.ToLowerInvariant() + "/"; var query = db.Query <Page>() .Where(p => p.Url.StartsWith(url)) .Where(p => p.DisplayOrder >= 0) .OrderBy(p => p.DisplayOrder) .OrderByDescending(p => p.__createdAt); if (levels == 0) { return(query); } else { var finishQuery = query.AsEnumerable(); // hit the database return(finishQuery.Where(p => { var urlParts = p.Url.Split('/'); return (urlParts.Length - 2) == levels; })); } }
/// <summary> /// Find User's Claim /// </summary> /// <param name="siteDb"></param> /// <param name="user"></param> private void AssignClaims(NancyBlackDatabase siteDb, NcbUser user) { var enroll = siteDb.Query <NcbEnroll>() .Where(e => e.IsActive && e.NcbUserId == user.Id) .ToList(); if (enroll.Count > 0) { var claims = new List <string>(); foreach (var item in enroll) { var _claims = GetRoleById(siteDb, item.NcbRoleId).Claims; if (_claims == null) { continue; } claims.AddRange(from c in GetRoleById(siteDb, item.NcbRoleId).Claims select c); } user.Claims = claims; } else { user.Claims = new string[0]; } }
/// <summary> /// Handles the case when sale order is using credit /// </summary> /// <param name="db"></param> /// <param name="so"></param> internal static void HandleCreditRequest(NancyBlackDatabase db, SaleOrder saleorder) { if (saleorder.PaymentStatus != PaymentStatus.Credit) { return; } // only create one receivable per sale order var existingReceivable = db.Query <AccountingEntry>().Where(e => e.SaleOrderId == saleorder.Id && e.IncreaseAccount == "Receivable").FirstOrDefault(); if (existingReceivable != null) { // update amount if changed if (existingReceivable.IncreaseAmount != saleorder.TotalAmount) { existingReceivable.IncreaseAmount = saleorder.TotalAmount; db.UpsertRecord(existingReceivable); } return; } AccountingEntry receivableEntry = new AccountingEntry(); receivableEntry.TransactionDate = DateTime.Now; receivableEntry.DueDate = DateTime.Now.Date.AddDays(30); receivableEntry.TransactionType = "newaccount"; receivableEntry.DebtorLoanerName = "Receivable From Sales"; receivableEntry.IncreaseAccount = "Receivable"; receivableEntry.IncreaseAmount = saleorder.TotalAmount; receivableEntry.SaleOrderId = saleorder.Id; db.UpsertRecord(receivableEntry); }
/// <summary> /// Save Heuristics Data /// </summary> /// <param name="db"></param> public static void SaveHeuristics() { if (DateTime.Now.Subtract(_LastSaved).TotalSeconds < 5) { return; } _LastSaved = DateTime.Now; var myId = Interlocked.Increment(ref _SaveCounter); Task.Run(() => { Task.Delay(3000).Wait(); if (myId < _SaveCounter) { return; } var db = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath); db.Transaction(() => { foreach (var item in _Heuristics.Values) { db.UpsertRecord <ImageSizeHeuristics>(item); } }); }); }
public static void GenerateUserCode(NancyBlackDatabase db, NcbUser user) { user.Code = Guid.NewGuid().ToString().Substring(0, 5).ToUpper(); user.CodeRequestDate = DateTime.Now; db.UpsertRecord <NcbUser>(user); }
/// <summary> /// See status of user opt-in /// </summary> /// <param name="db"></param> /// <param name="type"></param> /// <returns></returns> public static bool IsOptInActive(NancyBlackDatabase db, int userId, string type) { var optin = db.Query <FacebookMessengerOptIn>() .Where(o => o.NcbUserId == userId && o.OptInType == type) .FirstOrDefault(); return(optin != null); }
/// <summary> /// Handles Count Request /// </summary> /// <param name="db"></param> /// <param name="arg"></param> /// <returns></returns> protected dynamic HandleInlineCountRequest(NancyBlackDatabase db, dynamic arg) { return(new { Count = this.HandleCountWithoutSkipAndTakeRequest(db, arg), Results = this.HandleQueryRequest_WithoutCountSupport(db, arg) }); }
void NancyBlackDatabase_ObjectDeleted(NancyBlackDatabase db, string entity, dynamic item) { // remove cached user if (entity == "__Enrollment") { MemoryCache.Default.Remove("User-" + item.UserGuid); } }
public IEnumerable <object> GetRowVersions(NancyBlackDatabase db) { var rows = db.Query <RowVersion>() .Where(row => row.DataType == "SaleOrder" && row.RowId == this.Id) .ToList(); return(rows.Select(row => JsonConvert.DeserializeObject(row.js_Row))); }
/// <summary> /// Whether user can claim the reward /// </summary> /// <param name="db"></param> /// <param name="rewardsId"></param> /// <param name="registrationId"></param> /// <returns></returns> public static bool CanClaim(NancyBlackDatabase db, int rewardsId, int registrationId) { var reg = db.GetById <AffiliateRegistration>(registrationId); var rewards = db.GetById <AffiliateReward>(rewardsId); var stat = AffiliateReward.GetRewardStats(db, reg); return(AffiliateReward.CanClaim(db, rewards, reg, stat)); }
public CommerceModule() { if (_Triggered == false) { // ensure that we have thank you page ContentModule.GetPage(NancyBlackDatabase.GetSiteDatabase(this.RootPath), "/__/commerce/thankyou", true); _Triggered = true; } // testing thankyou page by nancy white Get["/__/commerce/thankyou"] = this.HandleViewRequest("commerce-thankyoupage", (arg) => { if (this.CurrentUser.HasClaim("admin") == false) { return(new StandardModel(404)); } var page = ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true); return(new StandardModel(this, page, JObject.FromObject(new SaleOrder() { SaleOrderIdentifier = "SO20990909-999999", }))); }); Get["/__commerce/cart"] = this.HandleViewRequest("commerce-shoppingcart", (arg) => { return(new StandardModel(this, "Checkout")); }); // get the product Get["/__commerce/api/productstructure"] = this.HandleRequest(this.BuildProductStructure); // List User's address Get["/__commerce/api/addresses"] = this.HandleRequest(this.FindUserAddress); // Save User's address Post["/__commerce/api/address"] = this.HandleRequest(this.UpdateUserAddress); // Save User's cart Post["/__commerce/api/checkout"] = this.HandleRequest(this.Checkout); Get["/__commerce/saleorder/{so_id}/{form}"] = this.HandleViewRequest("commerce-print", this.HandleCommercePrint); Patch["/tables/SaleOrder/{id:int}"] = this.HandleRequest(this.HandleSalorderSaveRequest); Post["/__commerce/api/resolvevariation"] = this.HandleRequest(this.HandleVariationRequest); Get["/__commerce/banner"] = this.HandleRequest(this.HandleBannerRequest); Get["/__commerce/settings"] = this.HandleRequest((arg) => { return(this.CurrentSite.commerce); }); Post["/__commerce/api/checkpromotion"] = this.HandleRequest(this.HandlePromotionCheckRequest); }
/// <summary> /// Load variable from database, this will only load once per application start up /// </summary> /// <param name="db"></param> public void Load(NancyBlackDatabase db) { if (_Variables != null) { return; } _Variables = db.Query <GlobalVarEntry>().ToDictionary(gv => gv.Key, gv => gv); }
/// <summary> /// Handles the delete request /// </summary> /// <param name="db"></param> /// <param name="arg"></param> /// <returns></returns> protected dynamic HandleDeleteRecordRequest(NancyBlackDatabase db, dynamic arg) { var entityName = (string)arg.table_name; var id = arg.item_id == null ? 0 : (int?)arg.item_id; db.DeleteRecord(entityName, new { Id = id }); return(204); }
/// <summary> /// Handles getting item by it's id /// </summary> /// <param name="db"></param> /// <param name="args"></param> /// <returns></returns> protected dynamic HandleSingleItemRequest(NancyBlackDatabase db, dynamic args) { var tableName = (string)args.table_name; var id = (int)args.item_id; TableSecModule.ThrowIfNoPermission(this.Context, tableName, TableSecModule.PERMISSON_QUERY); return(this.SiteDatabase.GetByIdAsJObject(tableName, id)); }
public void AddRMAItem(NancyBlackDatabase db, RMAItem item, bool saveRMA = true) { item = db.UpsertRecord <RMAItem>(item); this.RMAItemsId.Add(item.Id); if (saveRMA) { db.UpsertRecord <RMA>(this); } }
private AngularChart GetLaptopSoldChart(List <SaleOrder> paidSaleOrders, NancyBlackDatabase db) { var chart = new AngularChart() { Title = "Sold Laptop", Labels = new List <string>(), EnumType = AngularChartType.Pie, IsLegend = true, Data = new List <dynamic>() }; var lookupLaptopId = new ConcurrentDictionary <int, int>(); // count sold laptop paidSaleOrders.AsParallel().ForAll((so => { // find laptop from item's url var laptop = so.ItemsDetail.Where(item => item.Url.StartsWith("/products/laptops")).FirstOrDefault(); // find laptop in another type (archive-laptops) if (laptop == null) { laptop = so.ItemsDetail.Where(item => item.Url.StartsWith("/products/archive-laptops")).FirstOrDefault(); } // count sold laptop when found one if (laptop != null) { var newQty = (int)laptop.Attributes.Qty; lookupLaptopId.AddOrUpdate(laptop.Id, newQty, (laptopId, existQty) => existQty + newQty); } })); var soldLaptopsData = new ConcurrentBag <dynamic>(); // group.Key = laptop's id and group.Value = laptop sold's count lookupLaptopId.AsParallel().ForAll((group => { var laptop = db.GetById <Product>(group.Key); soldLaptopsData.Add(new { Id = group.Key, Title = laptop.Title, Quantity = group.Value, Price = laptop.Price }); })); foreach (var laptop in soldLaptopsData.OrderBy(product => product.Price)) { chart.Labels.Add(laptop.Title); chart.Data.Add(laptop.Quantity); } return(chart); }
/// <summary> /// Handles Insert/Update Request /// </summary> /// <param name="action">The action.</param> /// <returns></returns> protected dynamic HandleInsertUpdateRequest(NancyBlackDatabase db, dynamic arg) { var entityName = (string)arg.table_name; if (arg.body == null) { return(400); } if (this.SiteDatabase.DataType.FromName(entityName) == null) { if (this.Request.Url.HostName != "localhost") { return(403); } // enable all access for automatically created table TableSecModule.SetTableSec(this.Context, entityName, true, true, true, true); } dynamic fromClient = arg.body.Value as JObject; int? id = fromClient.id; if (id == null) { id = fromClient.Id; } if (id == null || id == 0) { TableSecModule.ThrowIfNoPermission(this.Context, entityName, TableSecModule.PERMISSON_CREATE); } else { TableSecModule.ThrowIfNoPermission(this.Context, entityName, TableSecModule.PERMISSON_UPDATE); } // special treatment for IContent if (typeof(IContent).IsAssignableFrom(db.DataType.FromName(entityName).GetCompiledType())) { if (id == null || id == 0) { fromClient.CreatedBy = this.CurrentUser.Id; } else { fromClient.UpdatedBy = this.CurrentUser.Id; } } dynamic record = db.UpsertRecord(entityName, fromClient); return(this.Negotiate .WithContentType("application/json") .WithModel((object)record)); }
/// <summary> /// Get Content which match the same Tag /// </summary> /// <param name="db"></param> /// <param name="url"></param> /// <returns></returns> public static IEnumerable <object> GetContentByTag(NancyBlackDatabase db, Tag tag, int skip, int take) { var tags = db.Query <Tag>() .Where(rec => rec.Url == tag.Url && rec.Type == tag.Type && rec.Name == tag.Name); foreach (var rec in tags) { yield return(db.GetById(rec.Type, rec.ContentId)); } }
internal static void ProcessInventoryItemUpdate(NancyBlackDatabase db, InventoryItem req) { if (req.IsFullfilled == false) { // Serial Number is missing - we will not auto process it if (string.IsNullOrEmpty(req.SerialNumber)) { return; } lock (BaseModule.GetLockObject("InventoryPurchase")) { var available = db.Query <InventoryPurchase>() .Where(i => i.InventoryItemId == 0 && i.ProductId == req.ProductId) .OrderBy(i => i.Id) .FirstOrDefault(); if (available == null) { // we actually dont have inventory, but serial number was keyed in // so we try the average cost instead dynamic price = db.Query("SELECT ProductId, AVG(BuyingPrice) as AvgCost FROM InventoryPurchase WHERE ProductId=? GROUP BY ProductId", new { ProductId = 1, AvgCost = 0M }, new object[] { req.ProductId }).FirstOrDefault(); if (price != null) { req.BuyingCost = (Decimal)price.AvgCost; } req.IsFullfilled = true; req.FulfilledDate = DateTime.Now; db.Connection.Update(req); } else { req.BuyingCost = available.BuyingPrice; req.BuyingTax = available.BuyingTax; req.InventoryPurchaseId = available.Id; req.IsFullfilled = true; req.FulfilledDate = DateTime.Now; available.InventoryItemId = req.Id; db.Connection.RunInTransaction(() => { db.Connection.Update(req); db.Connection.Update(available); }); } } } }
/// <summary> /// Refresh access token for given user id /// </summary> public static void RefreshTokenIfRequired(NancyBlackDatabase db, dynamic siteSettings, int userId) { var user = db.GetById <NcbUser>(userId); if (user == null) { throw new ArgumentException("User is not valid"); } GoogleAccountModule.RefreshTokenIfRequired(db, siteSettings, user); }
private void InsertTag_ObjectCreate(NancyBlackDatabase db, string table, dynamic obj) { if (!(obj is IContent)) { return; } IContent content = obj; this.InsertTag(db, content); }
/// <summary> /// Handles Count Request /// </summary> /// <param name="db"></param> /// <param name="arg"></param> /// <returns></returns> protected dynamic HandleCountRequest(NancyBlackDatabase db, dynamic arg) { var entityName = (string)arg.table_name; var rows = db.Count(entityName, this.Request.Query["$filter"], this.Request.Query["$orderby"], this.Request.Query["$skip"], this.Request.Query["$top"]); return(JToken.Parse(rows.ToString())); }
public void Static_InsertSpeed() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); for (int i = 0; i < 1000; i++) { db.UpsertRecord(new TestClass()); } conn.Dispose(); File.Delete(temp); }
public void Static_Delete() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); var instance = db.UpsertRecord(new TestClass()); db.DeleteRecord(instance); var output = db.GetById<TestClass>(instance.Id); Assert.IsTrue(output == null, "DELETE was not success"); conn.Dispose(); File.Delete(temp); }
public void Static_Query() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); var instance = new TestClass(); instance.Name = "Test Query"; db.UpsertRecord(instance); var check = db.Query<TestClass>().Where(i => i.Name == "Test Query").FirstOrDefault(); Assert.IsTrue(check.Name == "Test Query", "Query got wrong item"); conn.Dispose(); File.Delete(temp); }
public void Static_Insert() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); var instance = db.UpsertRecord(new TestClass()); Assert.IsTrue(instance.Id > 0, "ID was not set"); Assert.IsTrue(instance.__createdAt != DateTime.MinValue, "__createdAt was not set"); Assert.IsTrue(instance.__updatedAt != DateTime.MinValue, "__updatedAt was not set"); Assert.IsTrue(instance.__version != null, "Version was not set"); var instance2 = db.UpsertRecord(new TestClass()); Assert.IsTrue(instance2.Id > instance.Id, "ID was not running"); conn.Dispose(); File.Delete(temp); }
/// <summary> /// Generates the view. /// </summary> /// <param name="db">The database.</param> /// <param name="templatePath">The target template path.</param> /// <param name="table_name">The table_name.</param> /// <param name="replace">if set to <c>true</c>, view will be replaced.</param> /// <exception cref="System.InvalidOperationException">Entity: + table_name + does not exists, Insert some sample data before running this page.</exception> protected void GenerateView(NancyBlackDatabase db, string templatePath, string table_name, string layout, bool replace = false, string fileName = null) { if (fileName == null) { fileName = table_name; } var templateFile = Path.Combine( templatePath, fileName + ".cshtml"); if (File.Exists(templateFile) && replace == false) { return; } var type = db.DataType.FromName(table_name); if (type == null) { throw new InvalidOperationException("Entity:" + table_name + " does not exists, Insert some sample data before running this page."); } var template = File.ReadAllText(Path.Combine(this.RootPath, "Modules", "DatabaseSystem", "Views", "_backendtemplate.cshtml")); var code = Razor.Parse<ViewModel>(template, new ViewModel() { DataType = type, Layout = layout }, null); Directory.CreateDirectory(templatePath); File.WriteAllText(templateFile, code); }
/// <summary> /// Creates a content /// </summary> /// <param name="url"></param> /// <param name="layout"></param> /// <returns></returns> public static dynamic CreateContent(NancyBlackDatabase db, string url, string layout = "", string requiredClaims = "", int displayOrder = 0) { // try to find matching view that has same name as url var layoutFile = Path.Combine(_RootPath, "Site", "Views", url.Replace('/', '\\') + ".cshtml"); if (File.Exists(layoutFile)) { layout = url; } if (layout == "") { layout = "content"; } // if URL is "/" generate home instead if (url == "/") { layout = "home"; } if (url.StartsWith("/") == false) { url = "/" + url; } var createdContent = db.UpsertRecord("Content", new DefaultContent() { Id = 0, Url = url, Layout = layout, RequiredClaims = requiredClaims, DisplayOrder = displayOrder }); return createdContent; }
/// <summary> /// Get child content of given url /// </summary> /// <param name="url"></param> /// <returns></returns> public static IEnumerable<dynamic> GetChildContent(NancyBlackDatabase db, string url) { if (url.StartsWith("/") == false) { url = "/" + url; } return db.QueryAsDynamic("Content", string.Format("startswith(Url, '{0}/')", url.ToLowerInvariant()), "DisplayOrder"); }
/// <summary> /// Get User from login information /// </summary> /// <param name="db"></param> /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns></returns> public NcbUser GetUserFromLogin( NancyBlackDatabase db, string email, string passwordHash ) { var user = db.Query<NcbUser>() .Where(u => u.Email == email && u.PasswordHash == passwordHash) .FirstOrDefault(); if (user == null) { return null; } user.PasswordHash = null; this.AssignClaims(db, user); return user; }
/// <summary> /// Registers /// </summary> /// <param name="db"></param> /// <param name="registerParameters"></param> /// <returns></returns> public NcbUser Register( NancyBlackDatabase db, string email, string passwordHash ) { var existing = db.Query<NcbUser>() .Where(u => u.Email == email) .FirstOrDefault(); if (existing != null) { throw new InvalidOperationException("Email already in use"); } var user = new NcbUser(); user.Email = email; user.PasswordHash = passwordHash; user.Guid = Guid.NewGuid(); db.UpsertRecord(user); user.PasswordHash = null; return user; }
/// <summary> /// Find User's Claim /// </summary> /// <param name="siteDb"></param> /// <param name="user"></param> private void AssignClaims(NancyBlackDatabase siteDb, NcbUser user ) { var enroll = siteDb.Query<NcbEnroll>() .Where(e => e.IsActive && e.NcbUserId == user.Id) .ToList(); if (enroll.Count > 0) { var claims = new List<string>(); foreach (var item in enroll) { claims.AddRange(from c in this.GetRoleById(siteDb, item.NcbRoleId).Claims select c); } user.Claims = claims; } else { user.Claims = new string[0]; } }
/// <summary> /// Find the role by ID, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleById(NancyBlackDatabase siteDb, int id ) { var roles = MemoryCache.Default["Membership-Roles"] as Dictionary<int, NcbRole>; if (roles == null) { roles = siteDb.Query<NcbRole>().ToDictionary(r => r.Id); MemoryCache.Default.Add("Membership-Roles", roles, DateTimeOffset.Now.AddMinutes(5)); } NcbRole role; if (roles.TryGetValue( id, out role)) { return role; } throw new InvalidOperationException("Invalid Role Id:" + id); }
/// <summary> /// Find the role by Name, roles are cached for 5 minutes /// </summary> /// <param name="siteDb"></param> /// <param name="id"></param> /// <returns></returns> private NcbRole GetRoleByName(NancyBlackDatabase siteDb, string name) { var roles = MemoryCache.Default["Membership-RolesByName"] as Dictionary<string, NcbRole>; if (roles == null) { roles = siteDb.Query<NcbRole>().ToDictionary(r => r.Name.ToLowerInvariant()); MemoryCache.Default.Add("Membership-RolesByName", roles, DateTimeOffset.Now.AddMinutes(5)); } name = name.ToLowerInvariant(); NcbRole role; if (roles.TryGetValue(name, out role)) { return role; } // Make sure admin is available if (name == "admin") { role = new NcbRole() { Claims = new string[] { "admin" }, Name = "admin" }; siteDb.UpsertRecord( role ); MemoryCache.Default.Remove("Membership-RolesByName"); MemoryCache.Default.Remove("Membership-Roles"); return role; } throw new InvalidOperationException("Invalid Role Name: " + name ); }
void NancyBlackDatabase_ObjectDeleted(NancyBlackDatabase db, string entity, dynamic item) { // remove cached user if (entity == "__Enrollment") { MemoryCache.Default.Remove("User-" + item.UserGuid); } }
/// <summary> /// Get child content of given url /// </summary> /// <param name="url"></param> /// <returns></returns> public static dynamic GetContent(NancyBlackDatabase db, string url) { if (url.StartsWith("/") == false) { url = "/" + url; } return db.Query("Content", string.Format("Url eq '{0}'", url.ToLowerInvariant())).FirstOrDefault(); }
public void Static_Update() { var temp = Path.GetTempFileName(); SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(temp, true); NancyBlackDatabase db = new NancyBlackDatabase(conn); var instance = db.UpsertRecord(new TestClass()); instance.Name = "Test Update"; db.UpsertRecord(instance); var check = db.GetById<TestClass>(instance.Id); Assert.IsTrue(check.Name == "Test Update", "UPDATE was not success"); conn.Dispose(); File.Delete(temp); }