コード例 #1
0
 protected internal void OnAppContentResponderInitialized(AppConf appConf)
 {
     if (AppContentResponderInitialized != null)
     {
         AppContentResponderInitialized(this, appConf);
     }
 }
コード例 #2
0
ファイル: BamServer.cs プロジェクト: dekkerb115/Bam.Net
 protected void OnAppInitialized(AppConf conf)
 {
     if (AppInitialized != null)
     {
         AppInitialized(this, conf);
     }
 }
コード例 #3
0
ファイル: BamServer.cs プロジェクト: ThreeHeadz/Bam.Net
 protected void OnCreatedApp(AppConf conf)
 {
     if (CreatedApp != null)
     {
         CreatedApp(this, conf);
     }
 }
コード例 #4
0
 private void ForEachProxiedClass(AppConf appConf, DirectoryInfo serviceDir, Action <Type> doForEachProxiedType)
 {
     foreach (string searchPattern in appConf.ServiceSearchPattern)
     {
         ForEachProxiedClass(searchPattern, serviceDir, doForEachProxiedType);
     }
 }
コード例 #5
0
        protected internal void GenerateAppDaos(string dbJsRoot, AppConf appConf, DirectoryInfo appDaoDir, string fileSearchPattern)
        {
            DirectoryInfo daoTemp = appConf.AppRoot.GetDirectory(Path.Combine(dbJsRoot, "appdaotmp_".RandomLetters(4)));

            // get the saved hashes to determine if changes were made
            string hashPath = GetHashFilePath(appDaoDir);
            List <FileContentHash> hashes = GetHashes(hashPath);

            //      generate app dao from *.db.js ~a:/dao/
            FileInfo[] dbJsFiles = appConf.AppRoot.GetFiles(dbJsRoot, fileSearchPattern);
            //      compile into ~a:/dao/bin
            dbJsFiles.Each(dbJs =>
            {
                string path = dbJs.FullName.ToLowerInvariant();
                FileContentHash currentHash = new FileContentHash(path);

                if (!hashes.Contains(currentHash) && appConf.CheckDaoHashes)
                {
                    FileContentHash remove = hashes.Where(h => h.FilePath.ToLowerInvariant().Equals(path)).FirstOrDefault();
                    if (remove != null)
                    {
                        hashes.Remove(remove);
                    }
                    hashes.Add(currentHash);
                    hashes.ToArray().ToJsonFile(hashPath);
                    GenerateAppDao(appConf.Name, appDaoDir, daoTemp, dbJs);
                }
                else if (!appConf.CheckDaoHashes)
                {
                    GenerateAppDao(appConf.Name, appDaoDir, daoTemp, dbJs);
                }
            });
        }
コード例 #6
0
        private void AddJsonConfig(List <AppConf> configs, DirectoryInfo appDir, FileInfo appsConf)
        {
            AppConf conf = SetAppNameInJson(appDir, appsConf);

            conf.BamConf = this;
            configs.Add(conf);
        }
コード例 #7
0
ファイル: BamServer.cs プロジェクト: dekkerb115/Bam.Net
 protected void OnAppInitializing(AppConf conf)
 {
     if (AppInitializing != null)
     {
         AppInitializing(this, conf);
     }
 }
コード例 #8
0
        protected void SendCsProxyCode(IRequest request, IResponse response)
        {
            string    appName            = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);
            string    defaultBaseAddress = ServiceProxySystem.GetBaseAddress(request.Url);
            string    nameSpace          = request.QueryString["namespace"] ?? "ServiceProxyClients";
            string    contractNameSpace  = "{0}.Contracts"._Format(nameSpace);
            Incubator combined           = new Incubator();

            combined.CopyFrom(CommonServiceProvider);

            if (AppServiceProviders.ContainsKey(appName))
            {
                Incubator appProviders = AppServiceProviders[appName];
                combined.CopyFrom(appProviders, true);
            }

            string[] classNames = request.QueryString["classes"] == null ? combined.ClassNames : request.QueryString["classes"].DelimitSplit(",", ";");

            StringBuilder csharpCode = ServiceProxySystem.GenerateCSharpProxyCode(defaultBaseAddress, classNames, nameSpace, contractNameSpace, combined, Logger, request.UserHostAddress.StartsWith("127.0.0.1"));

            response.Headers.Add("Content-Disposition", "attachment;filename=" + nameSpace + ".cs");
            response.Headers.Add("Content-Type", "text/plain");
            byte[] data = Encoding.UTF8.GetBytes(csharpCode.ToString());
            response.OutputStream.Write(data, 0, data.Length);
        }
コード例 #9
0
        public AppContentResponder(ContentResponder commonResponder, AppConf conf, DataSettings dataSettings = null, ILogger logger = null)
            : base(commonResponder.BamConf, logger)
        {
            if (conf.BamConf == null)
            {
                conf.BamConf = commonResponder.BamConf;
            }
            DataSettings       = dataSettings ?? DataSettings.Current;
            ContentResponder   = commonResponder;
            ServerRoot         = commonResponder.ServerRoot;
            AppConf            = conf;
            AppRoot            = AppConf.AppRoot;
            AppTemplateManager = new AppDustRenderer(this);
            AppContentLocator  = ContentLocator.Load(this);
            Fs commonRoot = new Fs(new DirectoryInfo(Path.Combine(ServerRoot.Root, CommonFolder)));

            ContentHandlers   = new Dictionary <string, ContentHandler>();
            AllRequestHandler = new ContentHandler($"{conf.Name}.AllRequestHandler", AppRoot)
            {
                CheckPaths = false
            };
            CustomHandlerMethods = new List <MethodInfo>();
            CommonContentLocator = ContentLocator.Load(commonRoot);
            SetUploadHandler();
            SetBaseIgnorePrefixes();
            ContentHandlerScanTask = ScanForContentHandlers();
            SetAllRequestHandler();
        }
コード例 #10
0
        protected internal void SetIncludes(AppConf conf, LayoutModel layoutModel)
        {
            Args.ThrowIfNull(conf, "AppConf");
            Args.ThrowIfNull(conf.BamConf, "BamConf");
            Args.ThrowIfNull(conf.BamConf.ContentRoot, "ContentRoot");
            ApplicationServiceRegistry reg = ApplicationServiceRegistry.ForApplication(conf.Name);
            IIncludesResolver          includesResolver = reg.Get <IIncludesResolver>();
            Includes commonIncludes = new Includes();

            if (IncludeCommon)
            {
                commonIncludes = includesResolver.ResolveCommonIncludes(conf.BamConf.ContentRoot);
            }
            Includes      appIncludes        = includesResolver.ResolveApplicationIncludes(conf.Name, conf.BamConf.ContentRoot);
            Includes      combined           = commonIncludes.Combine(appIncludes);
            StringBuilder styleSheetLinkTags = new StringBuilder();

            foreach (string css in combined.Css)
            {
                styleSheetLinkTags.AppendLine(StyleSheetLinkTag.For(css).Render());
            }

            layoutModel.StyleSheetLinkTags = styleSheetLinkTags.ToString();

            StringBuilder scriptLinkTags = new StringBuilder();

            foreach (string script in combined.Scripts)
            {
                scriptLinkTags.Append(ScriptTag.For(script).Render());
            }

            layoutModel.ScriptTags = scriptLinkTags.ToString();
        }
コード例 #11
0
        private LayoutModel GetLayoutModel(string appName)
        {
            AppConf     conf = BamConf.AppConfigs.FirstOrDefault(c => c.Name.Equals(appName));
            LayoutConf  defaultLayoutConf = new LayoutConf(conf);
            LayoutModel layoutModel       = defaultLayoutConf.CreateLayoutModel();

            return(layoutModel);
        }
コード例 #12
0
        private static AppConf SetAppNameInYaml(DirectoryInfo appDir, FileInfo appsConf)
        {
            AppConf conf = appsConf.FromYamlFile <AppConf>();

            conf.Name = appDir.Name;
            conf.ToYamlFile(appsConf);
            return(conf);
        }
コード例 #13
0
        protected internal virtual void GenerateAppDao(string dbJsRoot, AppConf appConf, DirectoryInfo appDaoDir)
        {
            GenerateAppDaoSucceeded += RegisterNewAppDaoDll;

            GenerateAppDaos(dbJsRoot, appConf, appDaoDir, "*.db.js");
            GenerateAppDaos(dbJsRoot, appConf, appDaoDir, "*.db.json");

            GenerateAppDaoSucceeded -= RegisterNewAppDaoDll;
        }
コード例 #14
0
        /// <summary>
        /// Initializes the file system from the embedded zip resource
        /// that represents a bare bones app.
        /// </summary>
        public override void Initialize()
        {
            OnAppInitializing();
            WriteCompiledTemplates();

            AppRoot.WriteFile("appConf.json", AppConf.ToJson(true));

            OnAppInitialized();
        }
コード例 #15
0
ファイル: AppConf.cs プロジェクト: ThreeHeadz/Bam.Net
        private static string AppNameFromBinding(Uri uri, AppConf[] configs)
        {
            AppConf conf = configs.Where(c => c.Bindings.Any(h => h.HostName.Equals(uri.Authority))).FirstOrDefault();

            if (conf != null)
            {
                return(conf.Name);
            }
            return(string.Empty);
        }
コード例 #16
0
        private string RemoveBamAppsPrefix(string path)
        {
            string mgmtPrefix = $"/bam/apps/{AppConf.DomApplicationIdFromAppName(ApplicationName)}"; // TODO: this is a legacy construct resulting from the way that client side js is written; investigate removal

            if (path.StartsWith(mgmtPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                path = path.TruncateFront(mgmtPrefix.Length);
            }

            return(path);
        }
コード例 #17
0
        internal Fs AppFs(string appName)
        {
            Fs      result = null;
            AppConf conf   = AppConfigs.Where(ac => ac.Name.Equals(appName) || ac.Name.Equals(appName.ToLowerInvariant())).FirstOrDefault();

            if (conf != null)
            {
                result = conf.AppRoot;
            }

            return(result);
        }
コード例 #18
0
        private static AppConf SetAppNameInJson(DirectoryInfo appDir, FileInfo appsConf)
        {
            AppConf conf = appsConf.FromJson <AppConf>();

            if (conf == null)
            {
                conf = new AppConf();
            }
            conf.Name = appDir.Name;
            conf.ToJsonFile(appsConf);
            return(conf);
        }
コード例 #19
0
ファイル: LayoutConf.cs プロジェクト: dekkerb115/Bam.Net
        protected internal void SetIncludes(AppConf conf, LayoutModel layoutModel)
        {
            Includes includes = AppContentResponder.GetAppIncludes(conf);

            if (IncludeCommon)
            {
                Includes commonIncludes = ContentResponder.GetCommonIncludes(ContentRoot);
                includes = commonIncludes.Combine(includes);
            }
            layoutModel.ScriptTags         = includes.GetScriptTags().ToHtmlString();
            layoutModel.StyleSheetLinkTags = includes.GetStyleSheetLinkTags().ToHtmlString();
        }
コード例 #20
0
        public override bool TryRespond(IHttpContext context)
        {
            try
            {
                RequestWrapper  request  = context.Request as RequestWrapper;
                ResponseWrapper response = context.Response as ResponseWrapper;
                string          appName  = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);

                bool responded = false;

                if (request != null && response != null)
                {
                    string path = request.Url.AbsolutePath.ToLowerInvariant();

                    if (path.StartsWith("/{0}"._Format(ResponderSignificantName.ToLowerInvariant())))
                    {
                        if (path.StartsWith(MethodFormPrefixFormat._Format(ResponderSignificantName).ToLowerInvariant()))
                        {
                            responded = SendMethodForm(context, appName);
                        }
                        else
                        {
                            responded = SendProxyCode(request, response, path);
                        }
                    }
                    else
                    {
                        ExecutionRequest execRequest = CreateExecutionRequest(context, appName);
                        responded = execRequest.Execute();
                        if (responded)
                        {
                            RenderResult(appName, path, execRequest);
                        }
                    }
                }
                if (responded)
                {
                    OnResponded(context);
                }
                else
                {
                    OnNotResponded(context);
                }
                return(responded);
            }
            catch (Exception ex)
            {
                Logger.AddEntry("An error occurred in {0}.{1}: {2}", ex, this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                OnNotResponded(context);
                return(false);
            }
        }
コード例 #21
0
 private void AddConfiguredServiceProxyTypes(AppConf appConf)
 {
     appConf.ServiceTypeNames.Each(typeName =>
     {
         Type type = Type.GetType(typeName);
         if (type != null)
         {
             if (type.TryConstruct(out object instance, ex => Logger.AddEntry("AddConfiguredServiceProxyTypes: Unable to construct instance of type {0}: {1}", ex, type.Name, ex.Message)))
             {
                 SubscribeIfLoggable(instance);
                 AddAppService(appConf.Name, instance);
             }
         }
     });
 }
コード例 #22
0
        /// <summary>
        /// Deserializes each appConf found in subdirectories of
        /// the ~s:/apps folder.  For example, if there is a subfolder named
        /// Monkey in ~s:/apps then this method will search for ~s:/apps/Monkey/appConf.json
        /// then ~s:/apps/Monkey/appConf.yaml if the json file isn't found.  If neither
        /// is found a new AppConf is created and serialized to the json file
        /// specified above.
        /// </summary>
        /// <returns></returns>
        public List <AppConf> InitializeAppConfigs()
        {
            lock (_initAppConfigsLock)
            {
                List <AppConf> configs = new List <AppConf>();
                DirectoryInfo  appRoot = new DirectoryInfo(Path.Combine(ContentRoot, "apps"));
                if (!appRoot.Exists)
                {
                    appRoot.Create();
                }
                DirectoryInfo[] appDirs = appRoot.GetDirectories();
                appDirs.Each(appDir =>
                {
                    if (!appDir.Name.StartsWith("."))
                    {
                        bool configFound    = false;
                        FileInfo jsonConfig = new FileInfo(Path.Combine(appDir.FullName, "appConf.json"));
                        FileInfo appsConf   = jsonConfig;
                        if (appsConf.Exists)
                        {
                            configFound = true;
                            AddJsonConfig(configs, appDir, appsConf);
                        }
                        else
                        {
                            appsConf = new FileInfo(Path.Combine(appDir.FullName, "appConf.yaml"));
                            if (appsConf.Exists)
                            {
                                configFound = true;
                                AddYamlConfig(configs, appDir, appsConf);
                            }
                        }

                        if (!configFound)
                        {
                            AppConf conf = new AppConf(this, appDir.Name)
                            {
                                GenerateDao = this.GenerateDao
                            };
                            conf.ToJsonFile(jsonConfig);
                            configs.Add(conf);
                        }
                    }
                });

                return(configs);
            }
        }
コード例 #23
0
        /// <summary>
        /// Gets the Includes for the specified AppConf by reading the
        /// include.js file in the application folder.
        /// </summary>
        /// <param name="appConf"></param>
        /// <returns></returns>
        protected static internal Includes GetAppIncludes(AppConf appConf)
        {
            string   includeJs = Path.Combine(appConf.AppRoot.Root, IncludeFileName);
            string   appRoot   = Path.DirectorySeparatorChar.ToString();
            Includes includes  = GetIncludesFromIncludeJs(includeJs);

            includes.Scripts.Each((scr, i) =>
            {
                includes.Scripts[i] = Path.Combine(appRoot, scr).Replace("\\", "/");
            });
            includes.Css.Each((css, i) =>
            {
                includes.Css[i] = Path.Combine(appRoot, css).Replace("\\", "/");
            });

            return(includes);
        }
コード例 #24
0
        public void WriteBooks(AppConf appConfig)
        {
            AppName = appConfig.Name;
            FireEvent(AppInitializing, new WebBookEventArgs(appConfig));
            // get all the pages
            BamApplicationManager manager   = new BamApplicationManager(appConfig.BamConf);
            List <string>         pageNames = new List <string>(manager.GetPageNames(appConfig.Name));

            // read all the pages
            pageNames.Each(pageName =>
            {
                FireEvent(WritingBook, new WebBookEventArgs(appConfig));
                CurrentPage = pageName;
                Fs appFs    = appConfig.AppRoot;
                // create a new book for every page
                WebBook book = new WebBook {
                    Name = pageName
                };
                string content = appFs.ReadAllText("pages", "{0}.html"._Format(pageName));
                // get all the [data-navigate-to] and a elements
                CQ cq          = CQ.Create(content);
                CQ navElements = cq["a, [data-navigate-to]"];
                navElements.Each(nav =>
                {
                    // create a WebBookPage for each target
                    string href  = nav.Attributes["href"];
                    string navTo = nav.Attributes["data-navigate-to"];
                    string url   = string.IsNullOrEmpty(navTo) ? href: navTo;
                    if (!string.IsNullOrEmpty(url))
                    {
                        url           = url.Contains('?') ? url.Split('?')[0] : url;
                        string layout = nav.Attributes["data-layout"];
                        layout        = string.IsNullOrEmpty(layout) ? "basic" : layout;
                        if (pageNames.Contains(url))
                        {
                            book.Pages.Add(new WebBookPage {
                                Name = url, Layout = layout
                            });
                        }
                    }
                });
                appFs.WriteFile("~/books/{0}.json"._Format(book.Name), book.ToJson(true), true);
                FireEvent(WroteBook, new WebBookEventArgs(appConfig));
            });
            FireEvent(AppInitialized, new WebBookEventArgs(appConfig));
        }
コード例 #25
0
ファイル: BamServer.cs プロジェクト: dekkerb115/Bam.Net
        public AppContentResponder CreateApp(string appName, string defaultLayout = null, int port = 8080, bool ssl = false)
        {
            AppConf conf = new AppConf(appName, port, ssl);

            if (!string.IsNullOrEmpty(defaultLayout))
            {
                conf.DefaultLayout = defaultLayout;
            }
            OnCreatingApp(conf);

            AppContentResponder responder = new AppContentResponder(ContentResponder, conf);

            responder.Initialize();

            OnCreatedApp(conf);
            return(responder);
        }
コード例 #26
0
        protected internal WebBook GetBookByAppAndPage(string appName = "localhost", string pageName = "home")
        {
            AppConf appConf = BamConf[appName];
            WebBook result  = new WebBook();

            if (appConf != null)
            {
                string booksDir = "books";
                string bookFile = "{0}.json"._Format(pageName);
                Fs     appRoot  = appConf.AppRoot;
                if (appRoot.FileExists(booksDir, bookFile))
                {
                    result = appRoot.ReadAllText(booksDir, bookFile).FromJson <WebBook>();
                }
            }
            return(result);
        }
コード例 #27
0
        protected void SendJsProxyScript(IRequest request, IResponse response)
        {
            string appName             = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);
            bool   includeLocalMethods = request.UserHostAddress.StartsWith("127.0.0.1");

            StringBuilder script = ServiceProxySystem.GenerateJsProxyScript(CommonServiceProvider, CommonServiceProvider.ClassNames, includeLocalMethods);

            if (AppServiceProviders.ContainsKey(appName))
            {
                Incubator appProviders = AppServiceProviders[appName];
                script.AppendLine(ServiceProxySystem.GenerateJsProxyScript(appProviders, appProviders.ClassNames, includeLocalMethods).ToString());
            }

            response.ContentType = "application/javascript";
            byte[] data = Encoding.UTF8.GetBytes(script.ToString());
            response.OutputStream.Write(data, 0, data.Length);
        }
コード例 #28
0
        protected static internal string[] GetPageScripts(AppConf appConf)
        {
            BamApplicationManager manager = new BamApplicationManager(appConf.BamConf);

            string[]      pageNames = manager.GetPageNames(appConf.Name);
            List <string> results   = new List <string>();

            pageNames.Each(pageName =>
            {
                string script = "/" + Fs.CleanPath(Path.Combine("pages", pageName + ".js")).Replace("\\", "/"); // for use in html
                if (appConf.AppRoot.FileExists(script))
                {
                    results.Add(script);
                }
            });

            return(results.ToArray());
        }
コード例 #29
0
        private void RenderResult(string appName, string path, ExecutionRequest execRequest)
        {
            string ext = Path.GetExtension(path).ToLowerInvariant();

            if (string.IsNullOrEmpty(ext))
            {
                AppConf appConf = this.BamConf[appName];
                if (appConf != null)
                {
                    LayoutConf pageConf = new LayoutConf(appConf);
                    string     fileName = Path.GetFileName(path);
                    string     json     = pageConf.ToJson(true);
                    appConf.AppRoot.WriteFile("~/pages/{0}.layout"._Format(fileName), json);
                }
            }

            RendererFactory.Respond(execRequest, ContentResponder);
        }
コード例 #30
0
        public AppContentResponder(ContentResponder commonResponder, AppConf conf)
            : base(commonResponder.BamConf)
        {
            if (conf.BamConf == null)
            {
                conf.BamConf = commonResponder.BamConf;
            }

            ContentResponder    = commonResponder;
            ServerRoot          = commonResponder.ServerRoot;
            AppConf             = conf;
            AppRoot             = AppConf.AppRoot;
            AppTemplateRenderer = new AppDustRenderer(this);
            AppContentLocator   = ContentLocator.Load(this);
            Fs commonRoot = new Fs(new DirectoryInfo(Path.Combine(ServerRoot.Root, CommonFolder)));

            CommonContentLocator = ContentLocator.Load(commonRoot);

            SetBaseIgnorePrefixes();
        }