/// <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);
                    }
                });
            });
        }
Exemple #2
0
        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 Heuristics Data
        /// </summary>
        /// <param name="db"></param>
        public static void LoadHeuristics()
        {
            if (_Heuristics != null && _Heuristics.Count != 0)
            {
                return;
            }

            var db   = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath);
            var list = db.Query <ImageSizeHeuristics>();

            _Heuristics = new Dictionary <string, ImageSizeHeuristics>();

            foreach (var row in list)
            {
                _Heuristics[row.Key] = row;
            }
        }
Exemple #4
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            BootStrapper.RootPath = this.RootPathProvider.GetRootPath();

            // create App_Data
            Directory.CreateDirectory(Path.Combine(BootStrapper.RootPath, "App_Data"));

            ModuleResource.ReadSystemsAndResources(BootStrapper.RootPath);

            this.Conventions.ViewLocationConventions.Clear();

            #region Localized View Conventions

            // Site's View Folder has most priority
            // Mobile View Overrides
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                string u = context.Context.Request.Headers.UserAgent.ToLowerInvariant();
                if (u.Contains("mobile/"))
                {
                    return("Site/Views/Mobile/" + viewName + "_" + context.Context.Items["Language"]);
                }

                return(string.Empty); // not mobile browser
            });

            // Desktop View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Site/Views/Desktop/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // Generic View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Site/Views/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // Theme view location (views/_theme) can override _theme of the Theme folder
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                var theme = context.Context.GetSiteSettings().Theme;
                if (theme == null)
                {
                    return(string.Empty);
                }

                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Themes/" + theme + "/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // NancyBlack's View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("NancyBlack/Content/Views/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // then try Views in Systems (AdminSystem, ContentSystem etc...)
            foreach (var system in ModuleResource.Systems)
            {
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    if (context.Context.Items.ContainsKey("Language") == false)
                    {
                        return(string.Empty);
                    }

                    return(string.Concat("NancyBlack/Modules/",
                                         viewName,
                                         "_",
                                         context.Context.Items["Language"]));
                });

                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    if (context.Context.Items.ContainsKey("Language") == false)
                    {
                        return(string.Empty);
                    }

                    return(string.Concat("NancyBlack/Modules/",
                                         system,
                                         "/Views/",
                                         viewName,
                                         "_",
                                         context.Context.Items["Language"]));
                });
            }

            #endregion

            #region Sub Website View Conventions

            // Generic View for SubWebsite Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                string subSiteName = (string)context.Context.Items[ContextItems.SubSite];
                if (!string.IsNullOrEmpty(subSiteName))
                {
                    return("Site/SubSites/" + subSiteName + "/Views/" + viewName);
                }

                return(string.Empty);
            });

            #endregion

            #region View Conventions

            // Site's View Folder has most priority
            // Mobile View Overrides
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                string u = context.Context.Request.Headers.UserAgent.ToLowerInvariant();
                if (u.Contains("mobile/"))
                {
                    return("Site/Views/Mobile/" + viewName);
                }

                return(string.Empty); // not mobile browser
            });

            // Desktop View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("Site/Views/Desktop/" + viewName);
            });

            // Generic View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("Site/Views/" + viewName);
            });

            // Theme view location (views/_theme) can override _theme of the Theme folder
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                var theme = context.Context.GetSiteSettings().Theme;
                if (theme == null)
                {
                    return(string.Empty);
                }

                return("Themes/" + theme + "/" + viewName);
            });

            // NancyBlack's View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("NancyBlack/Content/Views/" + viewName);
            });

            // then try Views in Systems (AdminSystem, ContentSystem etc...)
            foreach (var system in ModuleResource.Systems)
            {
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    return(string.Concat("NancyBlack/Modules/",
                                         viewName));
                });
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    return(string.Concat("NancyBlack/Modules/",
                                         system,
                                         "/Views/",
                                         viewName));
                });
            }

            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return(viewName); // fully qualify names
            });

            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return(viewName.Substring(1)); // fully qualify names, remove forward slash at first
            });



            #endregion

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/__membership/login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };
            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>
            {
                // Get Subsite Name if in main site will get null
                string folder = Path.Combine(BootStrapper.RootPath, "Site", "SubSites");
                if (Directory.Exists(folder))
                {
                    var subSiteNames     = from subDirectories in Directory.GetDirectories(folder) select Path.GetFileName(subDirectories);
                    var matchSubSiteName = (from subSite in subSiteNames where ctx.Request.Url.HostName.Contains(subSite) select subSite).FirstOrDefault();

                    ctx.Items[ContextItems.SubSite] = matchSubSiteName;
                }
                else
                {
                    ctx.Items[ContextItems.SubSite] = null;
                }

                var db = NancyBlackDatabase.GetSiteDatabase(this.RootPathProvider.GetRootPath());
                GlobalVar.Default.Load(db);

                ctx.Items["SiteDatabase"] = db;
                ctx.Items["CurrentSite"]  = AdminModule.ReadSiteSettings();
                ctx.Items["SiteSettings"] = AdminModule.ReadSiteSettings();
                ctx.Items["RootPath"]     = BootStrapper.RootPath;

                if (ctx.Request.Cookies.ContainsKey("userid") == false)
                {
                    ctx.Request.Cookies.Add("userid", Guid.NewGuid().ToString());
                }

                return(null);
            });

            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {
                if (ctx.Request.Cookies.ContainsKey("userid"))
                {
                    ctx.Response.Cookies.Add(
                        new NancyCookie("userid", ctx.Request.Cookies["userid"], DateTime.Now.AddYears(10)));
                }

                GlobalVar.Default.Persist(ctx.Items["SiteDatabase"] as NancyBlackDatabase);
            });

            foreach (var item in container.ResolveAll <IPipelineHook>())
            {
                item.Hook(pipelines);
            }
        }
        /// <summary>
        /// Immediately Send out email
        /// </summary>
        public static void ProcessQueue(Nancy.NancyContext ctx)
        {
            if (_Outbox == null)
            {
                return;
            }

            if (ctx.Items.ContainsKey("SiteSettings") == false)
            {
                return;
            }

            lock (BaseModule.GetLockObject("MailSenderModule.ProcessQueue"))
            {
                if (_Outbox == null)
                {
                    return;
                }

                var toSend = _Outbox.ToList();
                _Outbox = null;

                var site = ctx.Items["SiteSettings"] as JObject;

                Task.Run(() =>
                {
                    Func <SmtpSettings, SmtpClient> getClient = (s) =>
                    {
                        SmtpClient client  = new SmtpClient(s.server);
                        client.Port        = s.port;
                        client.Credentials = new System.Net.NetworkCredential(s.username, s.password);
                        client.EnableSsl   = s.useSSL;
                        client.Timeout     = 30000;

                        return(client);
                    };

                    var db            = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath);
                    var settings      = site.Property("smtp").Value.ToObject <SmtpSettings>();
                    var count         = 0;
                    SmtpClient sender = getClient(settings);

                    foreach (var mail in toSend)
                    {
                        if (count % 100 == 0)
                        {
                            sender.Dispose();
                            count = 0;

                            sender = getClient(settings);
                        }

                        var log         = new NcbMailSenderLog();
                        log.Body        = mail.Body;
                        log.To          = string.Join(",", from m in mail.To select m.Address);
                        log.Subject     = mail.Subject;
                        log.MessageHash = (log.Body + log.To + log.Subject).GetHashCode();
                        log.Settings    = settings;
                        log.__createdAt = DateTime.Now;
                        log.__updatedAt = DateTime.Now;

                        var today   = DateTime.Now.Date;
                        var lastLog = db.Query <NcbMailSenderLog>().Where(l => l.MessageHash == log.MessageHash).FirstOrDefault();
                        if (lastLog != null)
                        {
                            if (DateTime.Now.Subtract(lastLog.__createdAt).TotalHours < 12)
                            {
                                log.IsSkipped = true;
                            }
                        }

                        if (log.IsSkipped == false)
                        {
                            try
                            {
                                log.IsAttempted = true;

                                mail.From = new MailAddress(settings.fromEmail);
                                sender.Send(mail);

                                log.IsSent = true;
                            }
                            catch (Exception e)
                            {
                                log.Exception = e;
                            }
                        }

                        db.UpsertRecord(log);
                        count++;
                    }

                    db.Dispose();
                });
            }
        }
        /// <summary>
        /// Query Azure Table Storage and update page view
        /// </summary>
        private void UpdatePageView(AffiliateRegistration reg)
        {
            // Fire and Forget - if multiple threads have spaned
            var database = NancyBlackDatabase.GetSiteDatabase(this.RootPath);
            var key      = reg.AffiliateCode + "-updatepageview";

            reg = database.GetById <AffiliateRegistration>(reg.Id);
            if (reg.LastPageViewUpdate.Date == DateTime.Now.Date)
            {
                return;
            }

            Task.Run(() =>
            {
                lock (BaseModule.GetLockObject(key))
                {
                    var cached = MemoryCache.Default[key] as AffiliateRegistration;
                    if (cached != null)
                    {
                        // someone has recently do the update
                        if (cached.LastPageViewUpdate.Date == DateTime.Now.Date)
                        {
                            return;
                        }
                    }

                    if (reg.LastPageViewUpdate == default(DateTime))
                    {
                        reg.LastPageViewUpdate = reg.__createdAt;
                    }

                    var table = GetPageViewTable();


                    var pageViews = (from pv in table.CreateQuery <PageView>()
                                     where
                                     pv.Timestamp > reg.LastPageViewUpdate &&
                                     pv.AffiliateCode == reg.AffiliateCode
                                     select pv);

                    var userSet = new HashSet <string>();

                    foreach (var item in pageViews)
                    {
                        reg.TotalPageView++;
                        userSet.Add(item.UserUniqueId);

                        if (item.QueryString.Contains("source="))
                        {
                            reg.TotalAffiliateLinkClicks++;
                        }

                        if (item.QueryString.Contains("subscribe=1"))
                        {
                            reg.TotalSubscribeLinkClicks++;
                        }
                    }

                    reg.LastPageViewUpdate = DateTime.Now;
                    reg.TotalUniqueUser   += userSet.Count;
                    reg.TotalSales         = NancyBlackDatabase.GetSiteDatabase(this.RootPath).Query <SaleOrder>()
                                             .Where(so => so.AffiliateCode == reg.AffiliateCode &&
                                                    so.PaymentStatus == PaymentStatus.PaymentReceived).Count();

                    reg.UpdateCommissionRate();

                    database.UpsertRecord(reg);

                    // Make the instance for checking available for 1 hour
                    MemoryCache.Default.Add(key, reg, DateTimeOffset.Now.AddHours(1));
                }
            });
        }
        private dynamic AffiliateDashboard(AffiliateRegistration registration, dynamic arg)
        {
            var siteDatabase = NancyBlackDatabase.GetSiteDatabase(this.RootPath);

            dynamic affiliateFacts = MemoryCache.Default["affiliatefacts"];

            if (affiliateFacts == null)
            {
                affiliateFacts = new
                {
                    Total       = siteDatabase.Query <AffiliateRegistration>().Count(),
                    TotalActive = siteDatabase.Query("SELECT Distinct AffiliateCode FROM AffiliateTransaction", new { Count = 0 }).Count(),
                    PayoutStats = siteDatabase.Query("SELECT Count(Id) as Count, Avg(CommissionAmount) as Avg, Sum(CommissionAmount) as Sum FROM AffiliateTransaction", new { Count = 0, Avg = 0.0M, Sum = 0.0M }).FirstOrDefault(),
                };
                MemoryCache.Default.Add("affiliatefacts", affiliateFacts, DateTimeOffset.Now.AddHours(1));
            }

            var content = ContentModule.GetPage(siteDatabase, "/__affiliate", true);

            var standardModel = new StandardModel(200);

            standardModel.Content = content;

            if (registration != null)
            {
                var     key           = "dashboard-" + registration.NcbUserId;
                dynamic dashboardData = MemoryCache.Default[key];

                if (Request.Query.code != null)
                {
                    dashboardData = null; // this is impersonation by user 1 - refresh all data

                    MemoryCache.Default.Remove(key);
                    MemoryCache.Default.Remove("AffiliateReg-" + registration.AffiliateCode);
                }

                if (dashboardData == null)
                {
                    var user       = siteDatabase.GetById <NcbUser>(registration.NcbUserId);
                    var saleOrders = siteDatabase.Query <SaleOrder>()
                                     .Where(so => so.NcbUserId == registration.NcbUserId)
                                     .ToList();

                    var activeSaleOrder = (from so in saleOrders
                                           where so.PaymentStatus == PaymentStatus.Credit ||
                                           so.PaymentStatus == PaymentStatus.Deposit ||
                                           so.PaymentStatus == PaymentStatus.PaymentReceived
                                           select so).FirstOrDefault();

                    if (activeSaleOrder != null)
                    {
                        // figure out delivery date
                        activeSaleOrder.FindShipoutAndDeliveryDate(siteDatabase);
                    }

                    Func <SaleOrder, SaleOrder> reduce = (so) =>
                    {
                        var thinCustomer = new
                        {
                            FirstName = (string)so.Customer.FirstName,
                            LastName  = (string)so.Customer.LastName
                        };

                        return(new SaleOrder()
                        {
                            __createdAt = so.__createdAt,
                            SaleOrderIdentifier = so.SaleOrderIdentifier,
                            Status = so.Status,
                            PaymentStatus = so.PaymentStatus,
                            Customer = thinCustomer
                        });
                    };

                    var stat = AffiliateReward.GetRewardStats(siteDatabase, registration);
                    Func <AffiliateReward, JObject> addCanClaim = (rew) =>
                    {
                        var canClaim = AffiliateReward.CanClaim(siteDatabase, rew, registration, stat);
                        var toReturn = JObject.FromObject(rew);

                        toReturn.Add("canClaim", canClaim);

                        return(toReturn);
                    };

                    Func <AffiliateReward, bool> postProcess = (rew) =>
                    {
                        if (rew.IsRewardsClaimable)
                        {
                            return(true);
                        }

                        if (rew.ActiveUntil.HasValue)
                        {
                            if (DateTime.Now.Subtract(rew.ActiveUntil.Value).TotalDays > 7)
                            {
                                return(false); // skip rewards older than 1 week
                            }

                            return(true); // show that they have missed this rewards
                        }

                        if (rew.TotalQuota > 0) // with quota, see created date
                        {
                            if (DateTime.Now.Subtract(rew.__createdAt).TotalDays > 7)
                            {
                                return(false); // dont show old rewards
                            }

                            return(true);
                        }

                        return(true);
                    };

                    AffiliateRegistration refererReg;
                    refererReg = siteDatabase.Query <AffiliateRegistration>()
                                 .Where(reg => reg.AffiliateCode == registration.RefererAffiliateCode)
                                 .FirstOrDefault();

                    if (refererReg != null)
                    {
                        var refererUser = siteDatabase.GetById <NcbUser>(refererReg.NcbUserId);
                        refererReg.AdditionalData = new
                        {
                            Id = refererUser.Profile.id
                        };
                    }

                    dashboardData = new
                    {
                        Referer = refererReg,

                        Registration = registration,

                        Code = registration.AffiliateCode,

                        RelatedOrders = siteDatabase.Query <SaleOrder>()
                                        .Where(so => so.AffiliateCode == registration.AffiliateCode)
                                        .AsEnumerable()
                                        .Select(s => reduce(s)).ToList(),

                        AffiliateTransaction = siteDatabase.Query("SELECT * FROM AffiliateTransaction WHERE AffiliateCode=?",
                                                                  new AffiliateTransaction(),
                                                                  new object[] { registration.AffiliateCode }).ToList(),

                        Profile = user.Profile,

                        SaleOrders = siteDatabase.Query <SaleOrder>()
                                     .Where(so => so.NcbUserId == registration.NcbUserId)
                                     .AsEnumerable()
                                     .Select(s => reduce(s)).ToList(),

                        ActiveSaleOrder = activeSaleOrder,

                        /* Stats */

                        SubscribeAll = siteDatabase.QueryAsDynamic("SELECT COUNT(Id) As Count FROM AffiliateRegistration WHERE RefererAffiliateCode=?",
                                                                   new { Count = 0 },
                                                                   new object[] { registration.AffiliateCode }).First().Count,

                        ShareClicks = siteDatabase.QueryAsDynamic("SELECT COUNT(Id) As Count, Url FROM AffiliateShareClick WHERE AffiliateRegistrationId=? GROUP By Url",
                                                                  new { Count = 0, Url = "" },
                                                                  new object[] { registration.Id }).ToList(),

                        Downline = AffiliateModule.DiscoverDownLine(siteDatabase, registration.AffiliateCode).ToList(),

                        Rewards = siteDatabase.Query <AffiliateReward>().ToList()
                                  .Where(rew => rew.IsActive == true)
                                  .AsEnumerable()
                                  .Where(rew => postProcess(rew))
                                  .Select(rew => addCanClaim(rew)),

                        RewardsStat = stat,

                        ClaimedRewards = siteDatabase.Query <AffiliateRewardsClaim>()
                                         .Where(c => c.NcbUserId == registration.NcbUserId)
                                         .ToList(),

                        AffiliateFacts = affiliateFacts
                    };

#if !DEBUG
                    MemoryCache.Default.Add(key, dashboardData, DateTimeOffset.Now.AddMinutes(10));
#endif
                    UpdatePageView(registration);
                }

                standardModel.Data = JObject.FromObject(dashboardData);
            }


            return(View["affiliate-dashboard", standardModel]);
        }
Exemple #8
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            BootStrapper.RootPath = this.RootPathProvider.GetRootPath();

            // create App_Data
            Directory.CreateDirectory(Path.Combine(BootStrapper.RootPath, "App_Data"));

            ModuleResource.ReadSystemsAndResources(BootStrapper.RootPath);

            this.Conventions.ViewLocationConventions.Clear();

            #region Localized View Conventions

            // Site's View Folder has most priority
            // Mobile View Overrides
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                string u = context.Context.Request.Headers.UserAgent.ToLowerInvariant();
                if (u.Contains("mobile/"))
                {
                    return("Site/Views/Mobile/" + viewName + "_" + context.Context.Items["Language"]);
                }

                return(string.Empty); // not mobile browser
            });

            // Desktop View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Site/Views/Desktop/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // Generic View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Site/Views/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // Theme view location (views/_theme) can override _theme of the Theme folder
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                var theme = context.Context.GetSiteSettings().Theme;
                if (theme == null)
                {
                    return(string.Empty);
                }

                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("Themes/" + theme + "/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // NancyBlack's View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                if (context.Context.Items.ContainsKey("Language") == false)
                {
                    return(string.Empty);
                }

                return("NancyBlack/Content/Views/" + viewName + "_" + context.Context.Items["Language"]);
            });

            // then try Views in Systems (AdminSystem, ContentSystem etc...)
            foreach (var system in ModuleResource.Systems)
            {
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    if (context.Context.Items.ContainsKey("Language") == false)
                    {
                        return(string.Empty);
                    }

                    return(string.Concat("NancyBlack/Modules/",
                                         viewName,
                                         "_",
                                         context.Context.Items["Language"]));
                });

                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    if (context.Context.Items.ContainsKey("Language") == false)
                    {
                        return(string.Empty);
                    }

                    return(string.Concat("NancyBlack/Modules/",
                                         system,
                                         "/Views/",
                                         viewName,
                                         "_",
                                         context.Context.Items["Language"]));
                });
            }

            #endregion

            #region View Conventions

            // Site's View Folder has most priority
            // Mobile View Overrides
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                string u = context.Context.Request.Headers.UserAgent.ToLowerInvariant();
                if (u.Contains("mobile/"))
                {
                    return("Site/Views/Mobile/" + viewName);
                }

                return(string.Empty); // not mobile browser
            });

            // Desktop View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("Site/Views/Desktop/" + viewName);
            });

            // Generic View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("Site/Views/" + viewName);
            });

            // Theme view location (views/_theme) can override _theme of the Theme folder
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                var theme = context.Context.GetSiteSettings().Theme;
                if (theme == null)
                {
                    return(string.Empty);
                }

                return("Themes/" + theme + "/" + viewName);
            });

            // NancyBlack's View Location
            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return("NancyBlack/Content/Views/" + viewName);
            });

            // then try Views in Systems (AdminSystem, ContentSystem etc...)
            foreach (var system in ModuleResource.Systems)
            {
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    return(string.Concat("NancyBlack/Modules/",
                                         viewName));
                });
                this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
                {
                    return(string.Concat("NancyBlack/Modules/",
                                         system,
                                         "/Views/",
                                         viewName));
                });
            }

            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return(viewName); // fully qualify names
            });

            this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return(viewName.Substring(1)); // fully qualify names, remove forward slash at first
            });



            #endregion

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/__membership/login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };
            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>
            {
                ctx.Items["SiteDatabase"] = NancyBlackDatabase.GetSiteDatabase(this.RootPathProvider.GetRootPath());
                ctx.Items["CurrentSite"]  = AdminModule.ReadSiteSettings();
                ctx.Items["SiteSettings"] = AdminModule.ReadSiteSettings();
                ctx.Items["RootPath"]     = BootStrapper.RootPath;
                if (ctx.CurrentUser == null)
                {
                    ctx.CurrentUser = NcbUser.Anonymous;
                    if (ctx.Request.Url.HostName == "localhost")
                    {
                        ctx.CurrentUser = NcbUser.LocalHostAdmin;
                    }
                }

                return(null);
            });

            foreach (var item in container.ResolveAll <IPipelineHook>())
            {
                item.Hook(pipelines);
            }
        }
Exemple #9
0
        public void Initialize(IPipelines piepeLinse, NancyContext ctx)
        {
            if (ctx.Request.Headers.UserAgent.Contains("facebookexternalhit/1.1"))
            {
                ctx.Request.Headers.Accept = new List <Tuple <string, decimal> >()
                {
                    new Tuple <string, decimal>("text/html", 1)
                };

                ctx.Items["FBBot"] = true;
            }

            ctx.Items["Webp"] = ctx.Request.Headers.Accept.Any(a => a.Item1 == "image/webp");

            ctx.Items["CurrentSite"]  = AdminModule.ReadSiteSettings();
            ctx.Items["SiteSettings"] = AdminModule.ReadSiteSettings();
            ctx.Items["RootPath"]     = BootStrapper.RootPath;
            ctx.Items["IsAdmin"]      = null;

            NancyBlackDatabase db = null;

            if (_FirstRun == true)
            {
                lock (BaseModule.GetLockObject("Request-FirstRun"))
                {
                    // check again, other thread might done it
                    if (_FirstRun == false)
                    {
                        goto Skip;
                    }
                    _FirstRun = false;

                    // this will ensure DataType Factory only run once
                    db = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath, ctx);

                    GlobalVar.Default.Load(db);

                    ctx.Items["SiteDatabase"] = db; // other modules expected this

                    foreach (var item in _GlobalInitializes)
                    {
                        item.GlobalInitialize(ctx);
                    }

Skip:

                    ;
                }
            }


            if (db == null)
            {
                db = NancyBlackDatabase.GetSiteDatabase(BootStrapper.RootPath, ctx);
                ctx.Items["SiteDatabase"] = db;
            }

            // Get Subsite Name if in main site will get null
            string folder = Path.Combine(BootStrapper.RootPath, "Site", "SubSites");

            if (Directory.Exists(folder))
            {
                var subSiteNames = from subDirectories in Directory.GetDirectories(folder) select Path.GetFileName(subDirectories);

                var matchSubSiteName = (from subSite in subSiteNames where ctx.Request.Url.HostName.Contains(subSite) select subSite).FirstOrDefault();

                ctx.Items[ContextItems.SubSite] = matchSubSiteName;
            }
            else
            {
                ctx.Items[ContextItems.SubSite] = null;
            }

            if (ctx.Request.Cookies.ContainsKey("userid") == false)
            {
                ctx.Items["userid"] = Guid.NewGuid().ToString();
            }
            else
            {
                ctx.Items["userid"] = ctx.Request.Cookies["userid"];
            }
        }