Ejemplo n.º 1
0
        private static void InitTemplates()
        {
            templates     = new List <Template>();
            templatesById = new Dictionary <string, Template>();
            try
            {
                var path = StringHelper.AddToString(DirectoryHelper.Instance.ConfigDirectory, @"\", TemplatesDefinitionFilename);
                if (!File.Exists(path))
                {
                    path = StringHelper.AddToString(DirectoryHelper.Instance.ClientConfigDirectory, @"\", TemplatesDefinitionFilename);
                }

                var templateDefinitionData = JsonHelper.GetJsonFromFile(path);
                var templateDefinitions    = templateDefinitionData.ToObject <FromtemplateDefinitions>();

                templates = templateDefinitions.FormTemplates ?? templates;
                foreach (var template in templates)
                {
                    template.FormId   = template.FormId.ToLowerCamelCase();
                    template.Sections = DecorateSections(template.Sections);
                    templatesById.Add(template.FormId, template);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "TemplateDefinitions.InitTemplates: failed to init templates");
            }
        }
Ejemplo n.º 2
0
        protected JObject BuildSettingsData(string configDirectory, string clientConfigDirectory, bool allowInternal = false)
        {
            var newSettings = new JObject();
            var path        = StringHelper.AddToString(clientConfigDirectory, @"\", "settings.json");

            if (File.Exists(path))
            {
                var clientSettings = JsonHelper.GetJsonFromFile(path);
                if (clientSettings != null)
                {
                    SettingsHelper.UpdateSettingsWith(newSettings, clientSettings, allowInternal);
                }
            }

            var configuration = JsonHelper.FindTokenValue <JObject>(newSettings, "configuration");

            if (configuration == null)
            {
                configuration = new JObject();
                newSettings.Add("configuration", configuration);
            }

            path = StringHelper.AddToString(configDirectory, @"\", "config.json");
            if (File.Exists(path))
            {
                var customConfiguration = JsonHelper.GetJsonFromFile(path);
                if (customConfiguration != null)
                {
                    SettingsHelper.UpdateSettingsWith(configuration, customConfiguration, allowInternal);
                }
            }

            return(newSettings);
        }
Ejemplo n.º 3
0
        public static void ProcessFiles(string basePath, JToken settings)
        {
            var container = settings as JContainer;

            if (container == null)
            {
                return;
            }

            var filePath = FindAttributeValue <string>(container, FileAttribute);

            if (!string.IsNullOrEmpty(filePath))
            {
                var replace = string.Empty;
                filePath = StringHelper.AddToString(basePath, @"\", filePath.Replace("/", @"\"));
                if (File.Exists(filePath))
                {
                    replace = File.ReadAllText(filePath).ToBase64String();
                }

                JsonHelper.Replace(container, new JValue(replace));
            }
            else
            {
                var subContainers = container.Children <JContainer>().ToList();
                foreach (var subContainer in subContainers)
                {
                    ProcessFiles(basePath, subContainer);
                }
            }
        }
        protected object AddByKey(JObject translations, string key, out JToken parent, out string parentKey, out string subKey)
        {
            var    ks = key.Split(keyPartDelimiterSplitter).ToList();
            object o  = null;

            parent    = translations;
            parentKey = string.Empty;
            subKey    = key;

            while (o == null && parent != null && ks.Count > 1)
            {
                var k = ks[0];
                parentKey = StringHelper.AddToString(parentKey, keyPartDelimiter, k);
                ks.RemoveAt(0);
                var node = JsonHelper.GetTokenValue <JObject>(parent, k, true);
                if (node == null)
                {
                    node = new JObject();
                    (parent as JObject).Add(k.ToLowerCamelCase(), node);
                }

                parent = node;
                subKey = string.Join(keyPartDelimiter, ks);
                o      = parent != null?JsonHelper.GetTokenValue <object>(parent, subKey, true) : null;
            }

            if (o == null)
            {
                parentKey = string.Empty;
            }

            return(o);
        }
        private static void CollectLanguageLocalizations(string language, JArray routes, string parentPath)
        {
            localizations.TryGetValue(language, out var locs);
            normalizations.TryGetValue(language, out var norms);
            components.TryGetValue(language, out var comps);

            foreach (JObject route in routes.Children())
            {
                var path = JsonHelper.GetTokenValue <string>(route, "path");
                if (!string.IsNullOrEmpty(path))
                {
                    var fullPath = StringHelper.AddToString(parentPath, "/", path);

                    var component = JsonHelper.GetTokenValue <string>(route, "component");
                    if (!string.IsNullOrEmpty(component))
                    {
                        comps[fullPath] = component;
                    }

                    var localize  = JsonHelper.GetTokenValue <JObject>(route, "_localize") ?? new JObject();
                    var localized = JsonHelper.GetTokenValue <string>(localize, language) ?? path;
                    AddLocalizations(locs, path, localized);
                    AddLocalizations(norms, localized, path);
                    var children = route["children"] as JArray;
                    if (children != null)
                    {
                        CollectLanguageLocalizations(language, children, fullPath);
                    }
                }
            }
        }
        private ErrorModel CreateErrorViewModel(string contentMarkup, string language, string url, bool is404 = false)
        {
            ViewBag.Language = language;
            ViewBag.Title    = FrontendSettingsViaduc.Instance.GetTranslation(language, "page.title",
                                                                              "Schweizerisches Bundesarchiv BAR");

            var viewModel = new ErrorModel();

            var subRequestPath = WebHelper.GetApplicationSubRequestPath(Request);
            var relativeUrl    = StaticContentHelper.GetRelativeUrl(Request.ApplicationPath, subRequestPath, true);

            var contentNode =
                StaticContentHelper.FindStaticContentNode(FrontendSettingsViaduc.Instance, contentMarkup);

            var contentHtml = StaticContentHelper.ProcessStaticMarkupForMvc(FrontendSettingsViaduc.Instance, Request,
                                                                            relativeUrl, language, contentNode.OuterHtml);

            ViewBag.Html      = contentHtml;
            viewModel.BaseUrl = Request.ApplicationPath;
            viewModel.Url     = url;

            viewModel.LanguageLinks = new Dictionary <string, string>();
            var errorUrl = is404 ? "error/notfound" : $"error?url={url}";

            WebHelper.SupportedLanguages.ForEach(lang =>
            {
                viewModel.LanguageLinks[lang] = StringHelper.AddToString(Request.ApplicationPath, $"/{lang}/", errorUrl);
            });
            return(viewModel);
        }
        protected virtual void Initialize()
        {
            var clientRoot = WebHelper.MapPathIfNeeded(StringHelper.AddToString("~", "/", DirectoryHelper.Instance.ClientDefaultPath));
            var clientPath = GetFinalPath(clientRoot);
            var i          = clientPath.ToLowerInvariant().IndexOf(@"\dist");

            if (i > 0)
            {
                clientPath = Path.Combine(clientPath.Substring(0, i), "src");
            }

            i = clientPath.ToLowerInvariant().IndexOf(@"\src");
            if (i > 0)
            {
                clientPath = Path.Combine(clientPath.Substring(0, i), "src");
            }

            ClientSrcRoot   = clientPath;
            CoreSourcePath  = clientPath.Replace("src", Path.Combine("node_modules", "@cmi", "viaduc-web-core", "app"));
            FrontendSrcRoot = WebHelper.MapPathIfNeeded("~");

            ConfigRoot        = Path.Combine(ClientSrcRoot, @"config");
            DefaultOutputRoot = Path.Combine(ConfigRoot, @"_generated");
            DefaultDataPath   = Path.Combine(ConfigRoot, @"");
        }
Ejemplo n.º 8
0
        public ElasticQueryResult <T> RunQueryWithoutSecurityFilters <T>(ElasticQuery query) where T : TreeRecord
        {
            var info = StringHelper.AddToString(BaseUrl, "/", elasticSettings.DefaultIndex);

            info = StringHelper.AddToString(info, "/", elasticSettings.DefaultTypeName);
            var result = new ElasticQueryResult <T>
            {
                RequestInfo        = info,
                Status             = 0,
                TimeInMilliseconds = 0
            };

            var client = clientProvider.GetElasticClient(elasticSettings, result);

            try
            {
                var started = DateTime.Now;

                var request = new SearchRequest <ElasticArchiveRecord> {
                    Query = query.Query
                };
                var p = query.SearchParameters;

                AddPaging(p?.Paging, request);
                AddSort(p?.Paging?.OrderBy, p?.Paging?.SortOrder, request);
                ExcludeUnwantedFields(request);

                result.Response           = client.Search <T>(request);
                result.TimeInMilliseconds = (int)Math.Round((DateTime.Now - started).TotalMilliseconds);
                result.Status             = (int)HttpStatusCode.OK;

                ProcessQueryResult(result, null, null, client.SourceSerializer);
            }
            catch (Exception ex)
            {
                var statusCode = (ex as ElasticsearchClientException)?.Response?.HttpStatusCode;

                if (statusCode.HasValue)
                {
                    Log.Warning(ex, "Exception on Elastic query: {0}", result.RequestInfo);
                    result.Status = statusCode.Value;
                }
                else
                {
                    Log.Error(ex, "Exception on Elastic query: {0}", result.RequestInfo);
                    result.Status = (int)HttpStatusCode.InternalServerError;
                }

                var debugInformation = (ex as ElasticsearchClientException)?.DebugInformation;

                if (!string.IsNullOrEmpty(debugInformation))
                {
                    Log.Information(ex, "Additional information about the prior exception. Debug information: {0}", debugInformation);
                }

                result.Exception = ex;
            }

            return(result);
        }
Ejemplo n.º 9
0
        public static void RegisterBundles(BundleCollection bundles)
        {
            var dirHelper = DirectoryHelper.Instance;

            // static bundles
            var staticRoot = StringHelper.AddToString("~", "/", dirHelper.StaticDefaultPath);

            if (Directory.Exists(WebHelper.MapPathIfNeeded(staticRoot)))
            {
                bundles.Add(new ScriptBundle("~/static/js").Include(staticRoot + "js/*.js"));
                bundles.Add(
                    new ScriptBundle("~/static/css").Include(
                        staticRoot + "css/*.css",
                        staticRoot + "css/*.png"
                        )
                    );
            }


            // client bundles
            var clientRoot = StringHelper.AddToString("~", "/", dirHelper.ClientDefaultPath);

            if (Directory.Exists(WebHelper.MapPathIfNeeded(clientRoot)))
            {
                WebHelper.SetupClientDefaultBundleConfig(bundles);
            }
        }
        public static void SetupClientDefaultBundleConfig(BundleCollection bundles)
        {
            var clientRoot = StringHelper.AddToString("~", "/", DirectoryHelper.Instance.ClientDefaultPath);

            if (!Directory.Exists(MapPathIfNeeded(clientRoot)))
            {
                return;
            }

            BundleTable.EnableOptimizations = false;
        }
Ejemplo n.º 11
0
        protected override void Initialize()
        {
            base.Initialize();

            var vdInfo = Viaduc = new AppInfo(this, "viaducclient", "vd", "app;app/modules/client");

            vdInfo.AppDatas = new List <AppData>
            {
                new JsonAppData
                {
                    Info     = "Public/Settings",
                    Root     = FrontendSettingsViaduc.Instance.GetServerSettings(),
                    Mappings = new List <JsonDataMapping>
                    {
                        new JsonDataMapping
                        {
                            Select = "$.search.advancedSearchFields[*]",
                            Map    = node => new Dictionary <string, string>
                            {
                                {
                                    "metadata.searchFields." + JsonHelper.GetTokenValue <string>(node, "key"),
                                    JsonHelper.GetTokenValue <string>(node, "displayName")
                                }
                            }
                        },
                        new JsonDataMapping
                        {
                            Select = "$.search.simpleSearchSortingFields[*]",
                            Map    = node => new Dictionary <string, string>
                            {
                                {
                                    "metadata.sortFields." + StringHelper.AddToString(JsonHelper.GetTokenValue <string>(node, "orderBy"), ".",
                                                                                      JsonHelper.GetTokenValue <string>(node, "sortOrder")),
                                    JsonHelper.GetTokenValue <string>(node, "displayName")
                                }
                            }
                        }
                    }
                },
                new MetaAppData(new ModelData())
                {
                    Info = "Model"
                }
            };
        }
        protected object FindByKey(JObject translations, string key, out JToken parent, out string parentKey, out string subKey)
        {
            var    ks = key.Split(keyPartDelimiterSplitter).ToList();
            object o  = null;

            parent    = translations;
            parentKey = string.Empty;
            subKey    = key;

            // search in common
            if (ks.Count == 1)
            {
                // search in common
                o      = JsonHelper.GetTokenValue <object>(translations[commonKey], ks[0], true);
                parent = translations[commonKey];
                subKey = ks[0];
            }

            // search by name space
            while (o == null && parent != null && ks.Count > 0)
            {
                var k = ks[0];
                parentKey = StringHelper.AddToString(parentKey, keyPartDelimiter, k);
                ks.RemoveAt(0);
                parent = JsonHelper.GetTokenValue <JToken>(parent, k, true);
                subKey = string.Join(keyPartDelimiter, ks);
                o      = parent != null?JsonHelper.GetTokenValue <object>(parent, subKey, true) : null;
            }

            if (o == null)
            {
                parentKey = string.Empty;
            }

            // search by full (multi-part) key
            if (o == null && key.Contains(keyPartDelimiter))
            {
                o      = JsonHelper.GetTokenValue <object>(translations, key, true);
                parent = translations;
                subKey = key;
            }

            return(o);
        }
        private bool ExistsKey(JObject translations, string key)
        {
            var    ks        = key.Split(keyPartDelimiterSplitter).ToList();
            object o         = null;
            JToken parent    = translations;
            var    parentKey = string.Empty;

            while (o == null && parent != null && ks.Count > 0)
            {
                var k = ks[0];
                parentKey = StringHelper.AddToString(parentKey, keyPartDelimiter, k);
                ks.RemoveAt(0);
                parent = JsonHelper.GetTokenValue <JToken>(parent, k, true);
                var subKey = string.Join(keyPartDelimiter, ks);
                o = parent != null?JsonHelper.GetTokenValue <object>(parent, subKey, true) : null;
            }

            return(o != null);
        }
        // Disabled die Warning "async method lacks await operators
        // Die methode muss als async gekennzeichnet sein.
#pragma warning disable 1998
        public async Task <ActionResult> Index()
        {
            var language = WebHelper.GetClientLanguage(Request);

            WebHelper.SetClientLanguage(Response, language);
            WebHelper.SetClientType(Response, WebHelper.ClientTypeManagement);

            var appPath = Request.ApplicationPath;

            if (Request.Url.LocalPath.Contains("private"))
            {
                appPath = StringHelper.AddToString(appPath, "/", "private");
            }

            var baseUrl = WebHelper.AssertTrailingSlash(appPath);

            if (!Request.Url.AbsolutePath.EndsWith(baseUrl))
            {
                return(Redirect(new Uri(baseUrl + Request.Url.Query, UriKind.Relative).ToString()));
            }

            var translations = WebHelper.InjectTranslations ? ManagementSettingsViaduc.Instance.GetTranslations(language) : null;
            var settings     = WebHelper.InjectSettings ? ManagementSettingsViaduc.Instance.GetSettings() : null;

            var formatting = Formatting.None;

            ViewBag.Translations = translations != null?JsonConvert.SerializeObject(translations, formatting) : string.Empty;

            ViewBag.Settings = settings != null?JsonConvert.SerializeObject(settings, formatting) : string.Empty;

            var title = ManagementSettingsViaduc.Instance.GetTranslation(language, "page.title", "Schweizerisches Bundesarchiv BAR");

            ViewBag.StaticContent =
                FrontendHelper.GetStaticIndexContent(Request, language, title, ViewBag.Translations, ViewBag.Settings, ViewBag.ModelData);

            ViewBag.PageTitle = title;
            ViewBag.Language  = language;

            return(View());
        }
        public static void Initialize()
        {
            normalizations.Clear();
            localizations.Clear();
            components.Clear();

            var routesJson = string.Empty;

            try
            {
                var routesPath = WebHelper.MapPathIfNeeded(StringHelper.AddToString("~", "/",
                                                                                    StringHelper.AddToString(DirectoryHelper.Instance.ClientDefaultPath, "/", "config/routes.def")));
                routesJson = File.Exists(routesPath) ? File.ReadAllText(routesPath) : string.Empty;
                if (!string.IsNullOrEmpty(routesJson))
                {
                    var i = routesJson.IndexOf("defaultRouteChildren", StringComparison.Ordinal);
                    i = routesJson.IndexOf("[", i, StringComparison.Ordinal);
                    var j = routesJson.IndexOf("];", i, StringComparison.Ordinal);

                    if (i > 0 && j > i)
                    {
                        routesJson = routesJson.Substring(i, j + 1 - i);
                        routesJson = routesJson.Replace("'", "\"");
                        routesJson = new Regex(@"(redirectTo|pathMatch|matcher):\s*[^,\r]+,?").Replace(routesJson, string.Empty);
                        routesJson = new Regex(@"(canActivate|resolve):\s*[^}\]]+[}\]],?").Replace(routesJson, string.Empty);
                        routesJson = new Regex(@"(component):\s*([^,\s]+)[^,\S\r]*,?").Replace(routesJson, @"$1: ""$2"",");
                        var routes = JsonConvert.DeserializeObject <JArray>(routesJson);
                        CollectLocalizations(WebHelper.SupportedLanguages, routes);
                    }
                }
                else
                {
                    Log.Information("Could not load routes: {routesPath}", routesPath);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Could not load routes: {routesJson}", routesJson);
            }
        }
Ejemplo n.º 16
0
        static WebRequestModule()
        {
            string r;

            clientDirectoriesToMapLowerCased = new HashSet <string>();
            r = string.Empty;
            Array.ForEach(clientDirectoriesToMap, s =>
            {
                clientDirectoriesToMapLowerCased.Add(s.ToLower());
                r = StringHelper.AddToString(r, "|", s.ToLower());
            });
            clientDirectoriesToMapMatcher = new Regex(string.Format("/({0})/", r), RegexOptions.IgnoreCase | RegexOptions.Singleline);

            staticDirectoriesToMapLowerCased = new HashSet <string>();
            r = string.Empty;
            Array.ForEach(staticDirectoriesToMap, s =>
            {
                staticDirectoriesToMapLowerCased.Add(s.ToLower());
                r = StringHelper.AddToString(r, "|", s.ToLower());
            });
            staticDirectoriesToMapMatcher = new Regex(string.Format("/({0})/", r), RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }
Ejemplo n.º 17
0
        private void InitTranslationsFor(string language)
        {
            try
            {
                translations[language] = new JObject();
                var path = StringHelper.AddToString(ClientConfigDirectory, @"\", $"translations.{language.ToLower()}.json");

                if (!File.Exists(path))
                {
                    return;
                }

                var trans = JsonHelper.GetJsonFromFile(path);
                if (trans != null)
                {
                    translations[language] = trans;
                }
            }
            catch (Exception ex)
            {
                Log.Debug(ex, "Could not init translations for {language}", language);
            }
        }
        public void AddOrUpdateEntry(ProcessResult result, string key, string text, int pos = 0)
        {
            var keyNormalized = StringHelper.GetNormalizedKey(key);

            if (!key.Equals(keyNormalized))
            {
                result.addInfo(
                    pos > 0
                        ? string.Format("normalizing key {0} to {1} at {2}", key, keyNormalized, pos)
                        : string.Format("normalizing key {0} to {1}", key, keyNormalized)
                    );
            }

            var translations = result.translations;

            if (translations[commonKey] == null)
            {
                translations.Add(commonKey, new JObject());
            }

            if (string.IsNullOrEmpty(key) || key.EndsWith(keyPartDelimiter))
            {
                result.addInfo($"cannot add node «{keyNormalized}»");
                return;
            }

            JToken parent = translations;
            string parentKey, subKey;
            var    o = FindByKey(translations, key, out parent, out parentKey, out subKey);

            if (o == null)
            {
                if (!key.Contains(keyPartDelimiter))
                {
                    parent = translations[commonKey];
                    subKey = key;
                }
                else
                {
                    o = AddByKey(translations, key, out parent, out parentKey, out subKey);
                }
            }

            if (parent is JObject)
            {
                // Alle Zeilenumbrüche eliminieren im Text
                if (text?.Contains(Environment.NewLine) ?? false)
                {
                    text = GetStringWithoutLineBreaks(text);
                }

                var old = o?.ToString();
                if (string.IsNullOrEmpty(old) || !text.Equals(old))
                {
                    if (string.IsNullOrEmpty(subKey))
                    {
                        result.addInfo(string.Format("cannot add node «{0}» at {1}, text='{2}'", keyNormalized, parent.Path, text));
                    }
                    else if (!string.IsNullOrEmpty(old))
                    {
                        if (!string.IsNullOrEmpty(text) && !text.Equals(old) && !key.Equals(old))
                        {
                            result.addInfo($"wont override «{keyNormalized}»: old='{old}', new='{text}'");
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(text) && !result.forDefaultLanguage)
                        {
                            o = FindByKey(result.defaultTranslations, key, out parent, out parentKey, out subKey);
                            if (o != null)
                            {
                                text = o.ToString();
                            }
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            result.addInfo(string.Format("empty text for «{0}»", keyNormalized));
                        }
                        else if (!result.forDefaultLanguage)
                        {
                            text = result.language + ":" + text;
                            result.addInfo(string.Format("added default text for «{0}»: {1}", keyNormalized, text));
                        }

                        var subKeyNLC = StringHelper.GetNormalizedKey(subKey).ToLowerCamelCase();
                        JsonHelper.AddOrSet(parent as JObject, subKeyNLC, text);
                    }
                }
                else
                {
                    var keyNormaliedLowerCamelCase = keyNormalized.ToLowerCamelCase();
                    var keyC = StringHelper.AddToString(parentKey, keyPartDelimiter, subKey);
                    if (!keyNormaliedLowerCamelCase.Equals(keyC))
                    {
                        result.addInfo(string.Format("existing entry for «{0}» with equal text='{1}' but non-normalized key «{2}»",
                                                     keyNormaliedLowerCamelCase, text, keyC));
                    }
                }
            }
            else
            {
                result.addInfo(string.Format("no parent for «{0}», text='{1}'", keyNormalized, text));
            }
        }
Ejemplo n.º 19
0
        public ElasticQueryResult <T> RunQuery <T>(ElasticQuery query, UserAccess access) where T : TreeRecord
        {
            var stopwatch = new Stopwatch();
            var info      = StringHelper.AddToString(BaseUrl, "/", elasticSettings.DefaultIndex);

            if (!string.IsNullOrEmpty(elasticSettings.DefaultTypeName))
            {
                info += "/" + elasticSettings.DefaultTypeName;
            }

            var result = new ElasticQueryResult <T>
            {
                RequestInfo        = info,
                Status             = 0,
                TimeInMilliseconds = 0,
                EnableExplanations = query.SearchParameters?.Options?.EnableExplanations ?? false
            };

            var client = clientProvider.GetElasticClient(elasticSettings, result);

            try
            {
                stopwatch.Start();
                var searchRequest = BuildSearchRequest(query, access);
                result.Response = client.Search <T>(searchRequest);

                var json = client.RequestResponseSerializer.SerializeToString(searchRequest, SerializationFormatting.Indented);
                Log.Debug(json);

                stopwatch.Stop();
                result.TimeInMilliseconds = stopwatch.ElapsedMilliseconds;
                Debug.WriteLine($"Fetched record from web in  {stopwatch.ElapsedMilliseconds}ms");
                result.Status = (int)HttpStatusCode.OK;

                ProcessQueryResult(result, query.SearchParameters?.FacetsFilters, access, client.SourceSerializer);
            }
            catch (Exception ex)
            {
                var statusCode = (ex as ElasticsearchClientException)?.Response?.HttpStatusCode;

                if (statusCode.HasValue)
                {
                    Log.Warning(ex, "Exception on Elastic query: {0}", result.RequestInfo);
                    result.Status = statusCode.Value;
                }
                else
                {
                    Log.Error(ex, "Exception on Elastic query: {0}", result.RequestInfo);
                    result.Status = (int)HttpStatusCode.InternalServerError;
                }

                var debugInformation = (ex as ElasticsearchClientException)?.DebugInformation;

                if (!string.IsNullOrEmpty(debugInformation))
                {
                    Log.Information(ex, "Additional information about the prior exception. Debug information: {0}",
                                    debugInformation);
                }

                result.Exception = ex;
            }
            finally
            {
                Log.Debug("RunQueryCompleted: {RequestInfo}, {RequestRaw}, {ResponseRaw}", result.RequestInfo, result.RequestRaw, result.ResponseRaw);
            }

            return(result);
        }
Ejemplo n.º 20
0
        private void DetectRewriteRequest(HttpContext context, string requestUrl, out string rewrittenFileUrl)
        {
            rewrittenFileUrl = null;

            var request   = context.Request;
            var dirHelper = DirectoryHelper.Instance;

            var method = request.HttpMethod.ToUpper();
            var isGet  = "GET".Equals(method);

            if (isGet)
            {
                var webPrefix = request.ApplicationPath;

                var requestPath    = request.Path;
                var subRequestPath = WebHelper.GetApplicationSubRequestPath(request);
                if ("/".Equals(subRequestPath))
                {
                    // Ignore
                }
                else
                {
                    var parts      = subRequestPath.Split(WebHelper.UrlSplitter, StringSplitOptions.RemoveEmptyEntries);
                    var folderPart = parts.FirstOrDefault();

                    var handled = false;

                    // Static rewrites
                    if (folderPart != null && staticDirectoriesToMapLowerCased.Contains(folderPart.ToLower()) ||
                        staticDirectoriesToMapMatcher.Match(subRequestPath).Success)
                    {
                        var filePath = context.Server.MapPath(requestPath);
                        if (!File.Exists(filePath))
                        {
                            if (!requestPath.Contains(".html"))
                            {
                                var incPath = StringHelper.AddToString(dirHelper.StaticDefaultPath, "/", subRequestPath);
                                filePath = context.Server.MapPath((!incPath.StartsWith(webAppRootPrefix) ? webAppRootPrefix : string.Empty) +
                                                                  incPath);
                                if (File.Exists(filePath))
                                {
                                    rewrittenFileUrl = StringHelper.AddToString(webPrefix, "/", incPath.Replace(webAppRootPrefix, string.Empty));
                                    handled          = true;
                                }
                            }
                        }
                        else
                        {
                            handled = true;
                        }
                    }

                    // Client rewrites
                    Match clientMatch = null;
                    if (!handled && (folderPart != null && clientDirectoriesToMapLowerCased.Contains(folderPart.ToLower()) ||
                                     (clientMatch = clientDirectoriesToMapMatcher.Match(subRequestPath)).Success))
                    {
                        handled = true;

                        var filePath = context.Server.MapPath(requestPath);
                        if (!File.Exists(filePath))
                        {
                            var resPath = subRequestPath;
                            if (clientMatch != null)
                            {
                                resPath = resPath.Remove(0, clientMatch.Index);
                            }

                            if (!string.IsNullOrEmpty(dirHelper.ClientDefaultPath) && !"/".Equals(dirHelper.ClientDefaultPath))
                            {
                                resPath = ReplaceFirst(resPath, dirHelper.ClientDefaultPath, "/");
                            }

                            // look in web
                            if (rewrittenFileUrl == null)
                            {
                                var incPath = StringHelper.AddToString(dirHelper.ClientDefaultPath, "/", resPath);
                                filePath = context.Server.MapPath((!incPath.StartsWith(webAppRootPrefix) ? webAppRootPrefix : string.Empty) +
                                                                  incPath);
                                if (File.Exists(filePath))
                                {
                                    rewrittenFileUrl = StringHelper.AddToString(webPrefix, "/", incPath.Replace(webAppRootPrefix, string.Empty));
                                }
                            }
                        }
                    }

                    // Link handling
                    if (!handled && !requestUrl.Contains("/" + ApiHelper.WebApiSubRoot + "/") && !requestUrl.Contains("/proxy/") &&
                        requestUrl.Contains(hashMarkerPart))
                    {
                        var redirectTo = request.RawUrl.Replace(hashMarkerPart, "/#/");
                        if (!string.IsNullOrEmpty(skipMarkerPart) && redirectTo.Contains(skipMarkerPart))
                        {
                            var i = redirectTo.IndexOf(skipMarkerPart);
                            var j = redirectTo.LastIndexOf("?", i);
                            if (j > 0 && "/".Equals(redirectTo[j - 1]))
                            {
                                j -= 1;
                            }

                            redirectTo = j > i?redirectTo.Substring(0, i) + redirectTo.Substring(j) : redirectTo.Substring(0, i);
                        }

                        redirectTo = multipleSlashReplace.Replace(redirectTo, "/");

                        context.Response.Clear();
                        context.Response.Redirect(redirectTo);
                        context.Response.End();
                    }
                }
            }
        }
        public static string GetStaticRoot(string appRoot)
        {
            var staticRoot = StringHelper.AddToString(appRoot, "/", DirectoryHelper.Instance.StaticDefaultPath);

            return(AssertTrailingSlash(staticRoot));
        }
        public HttpResponseMessage RunGeneration(string language, HttpRequestMessage request)
        {
            Initialize();

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            try
            {
                var queryString = request.GetQueryNameValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase);
                Func <string, bool> queryContains = key => queryString.ContainsKey(key) && !string.IsNullOrEmpty(queryString[key]);

                var started = DateTime.Now;
                var info    = string.Empty;

                var appInfo = Viaduc;

                var defaultFileName = "translations." + WebHelper.DefaultLanguage + ".json";
                var partialFileName = "translations." + language + ".partial.json";
                var fileName        = "translations." + language + ".json";

                var sourcePath        = queryContains("in") ? queryString["in"] : appInfo.DataPath;
                var sourceFile        = StringHelper.AddToString(sourcePath, @"\", fileName);
                var defaultSourceFile = StringHelper.AddToString(sourcePath, @"\", defaultFileName);
                var partialSourceFile = StringHelper.AddToString(sourcePath, @"\", partialFileName);

                var outputPath = queryContains("out") ? queryString["out"] : DefaultOutputRoot;
                var outputFile = StringHelper.AddToString(outputPath, @"\", fileName);

                Output.Write(string.Format("Generating {0} {1}:", appInfo.AppKey, fileName) + nl);
                Output.Write(string.Format("- {0}", JsonConvert.SerializeObject(appInfo, Formatting.Indented)) + nl);
                Output.Write(string.Format("- in {0}", sourceFile) + nl);
                Output.Write(string.Format("- out {0}", outputFile) + nl);
                Output.Write(nl);

                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                if (File.Exists(outputFile))
                {
                    File.Delete(outputFile);
                }


                var result = new ProcessResult();
                result.language = language;
                if (!File.Exists(sourceFile))
                {
                    Output.Write("File does not exist: " + sourceFile + nl);
                }
                else
                {
                    result.translations = JsonHelper.GetJsonFromFile(sourceFile);
                    if (!result.forDefaultLanguage)
                    {
                        result.defaultTranslations = JsonHelper.GetJsonFromFile(defaultSourceFile);
                    }
                }

                if (File.Exists(partialSourceFile))
                {
                    result.translationsPartial = JsonHelper.GetJsonFromFile(partialSourceFile);
                }
                else
                {
                    Output.Write("File does not exist: " + partialSourceFile + nl);
                }

                var htmlFiles = new List <FileInfo>();
                var tsFiles   = new List <FileInfo>();
                var csFiles   = new List <FileInfo>();
                appInfo.Sources.ForEach(source =>
                {
                    var dir = new DirectoryInfo(WebHelper.MapPathIfNeeded(source));
                    htmlFiles.AddRange(dir.GetFiles("*.html", SearchOption.AllDirectories));
                    tsFiles.AddRange(dir.GetFiles("*.ts", SearchOption.AllDirectories).Where(fileInfo => !fileInfo.FullName.Contains(".spec")));
                });
                {
                    var dir = new DirectoryInfo(WebHelper.MapPathIfNeeded(FrontendSrcRoot));
                    csFiles.AddRange(dir.GetFiles("*.cs", SearchOption.AllDirectories));
                }


                result.addInfo = s => AddFileInfo(result, s);
                ProcessFiles(result, "html", htmlFiles);
                ProcessFiles(result, "ts", tsFiles);
                ProcessFiles(result, "cs", csFiles);

                result.addInfo = s => AddDataInfo(result, s);
                ProcessDatas(result, appInfo.AppDatas);

                Output.Write(result.output + nl);

                if (result.filesWithInfos.Count > 0)
                {
                    Output.Write(string.Format("{0} files with infos:", result.filesWithInfos.Count) + nl);
                    foreach (var fileWithInfos in result.filesWithInfos)
                    {
                        Output.Write(string.Format("{0}", fileWithInfos.Key) + nl);
                        foreach (var fileInfo in fileWithInfos.Value)
                        {
                            Output.Write(string.Format("- {0}", fileInfo) + nl);
                        }
                    }
                }

                if (result.filesIgnored.Count > 0)
                {
                    Output.Write(string.Format("{0} files ignored:", result.filesIgnored.Count) + nl);
                    foreach (var fileIgnored in result.filesIgnored)
                    {
                        Output.Write(string.Format("- {0}", fileIgnored) + nl);
                    }
                }

                if (result.datasWithInfos.Count > 0)
                {
                    Output.Write(string.Format("{0} datas with infos:", result.datasWithInfos.Count) + nl);
                    foreach (var dataWithInfos in result.datasWithInfos)
                    {
                        Output.Write(string.Format("{0}", dataWithInfos.Key) + nl);
                        foreach (var dataInfo in dataWithInfos.Value)
                        {
                            Output.Write(string.Format("- {0}", dataInfo) + nl);
                        }
                    }
                }

                result.translations = SortPropertiesAlphabetically(result.translations);

                if (result.translations["__generated"] != null)
                {
                    JsonHelper.Remove(result.translations, "__generated");
                }

                var generated = new JObject();
                generated.Add("info", "CMI.Viaduc.Client.generatetranslations");
                generated.Add("date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                result.translations.AddFirst(new JProperty("__generated", generated));

                var json = JsonConvert.SerializeObject(result.translations, Formatting.Indented);
                File.WriteAllText(outputFile, json, Encoding.UTF8);

                info = "length=" + json.Length;

                Output.Write(nl);

                Output.Write("Elapsed: " + DateTime.Now.Subtract(started).TotalMilliseconds + nl);
                Output.Write("Output: " + info + nl);
            }
            catch (Exception ex)
            {
                Output.Write(ServiceHelper.GetExceptionInfo(ex));
            }

            response.Content = new StringContent(Output.GetOutput());

            return(response);
        }
        public ActionResult Index()
        {
            var language = WebHelper.GetClientLanguage(Request);

            ViewBag.Language = language;
            ViewBag.Title    =
                FrontendSettingsViaduc.Instance.GetTranslation(language, "page.title",
                                                               "Schweizerisches Bundesarchiv BAR");

            var viewModel = new ContentIndexModel();

            var contentHtml = string.Empty;

            var subRequestPath = WebHelper.GetApplicationSubRequestPath(Request);
            var relativeUrl    = StaticContentHelper.GetRelativeUrl(Request.ApplicationPath, subRequestPath, true);

            var contentMarkup = string.Empty;

            try
            {
                contentMarkup = StaticContentHelper.GetContentMarkupFor(relativeUrl, language);
                if (string.IsNullOrEmpty(contentMarkup))
                {
                    contentMarkup = StaticContentHelper.GetContentMarkupFor($"{language}/404.html", language);
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                contentMarkup = StaticContentHelper.GetContentMarkupFor($"{language}/500.html", language);
            }

            try
            {
                var contentNode =
                    StaticContentHelper.FindStaticContentNode(FrontendSettingsViaduc.Instance, contentMarkup);

                contentHtml = StaticContentHelper.ProcessStaticMarkupForMvc(FrontendSettingsViaduc.Instance, Request,
                                                                            relativeUrl, language, contentNode.OuterHtml);
            }
            catch (Exception ex)
            {
                contentHtml = "<textarea>" + ServiceHelper.GetExceptionInfo(ex) + "</textarea>";
            }

            ViewBag.Html = contentHtml;

            var editMode = viewModel.EditMode = Session.HasFeatureStaticContentEdit();

            viewModel.BaseUrl = Request.ApplicationPath;

            ViewBag.HtmlClasses = editMode ? "edit-mode" : string.Empty;

            var normalizedUrl = RoutingHelper.NormalizePath(language, relativeUrl);

            viewModel.LanguageLinks = new Dictionary <string, string>();
            WebHelper.SupportedLanguages.ForEach(lang =>
            {
                viewModel.LanguageLinks[lang] = StringHelper.AddToString(Request.ApplicationPath, "/",
                                                                         RoutingHelper.LocalizePath(lang, normalizedUrl));
            });

            return(View(viewModel));
        }