Ejemplo n.º 1
0
        private string Api(HttpContext context, string endpoint, NameValueCollection query)
        {
            var serializer = new JavaScriptSerializer()
            {
                MaxJsonLength = 16777216
            };
            var response = string.Empty;

            switch (endpoint)
            {
            case "cultures":
                response = serializer.Serialize(_manager.GetCultures().Where(x => x.LCID != DefaultCulture.Value.LCID).Select(x => x.Name));
                break;

            case "tree":
                response = serializer.Serialize(GetTree(
                                                    _manager.GetLocalizedObjects(string.IsNullOrEmpty(query["culture"]) ? DefaultCulture.Value : new CultureInfo(query["culture"]))
                                                    ));
                break;

            case "table":
                response = serializer.Serialize(_manager.GetLocalizedObjects(new CultureInfo(query["culture"]))
                                                .Where(x => x.Scope != null && x.Scope.StartsWith(query["scope"], StringComparison.InvariantCultureIgnoreCase)));
                break;

            case "edit":

                if (!string.IsNullOrEmpty(query["id"]))
                {
                    var key = 0;
                    int.TryParse(query["id"], out key);

                    if (key != 0)
                    {
                        var edit = _manager.Get(key);
                        if (edit != null)
                        {
                            edit.Translation = query["translation"];
                            _manager.Save(edit);
                        }
                    }
                }
                break;

            case "delete":
                var delete = _manager.Get(int.Parse(query["id"]));
                if (delete != null)
                {
                    _manager.Delete(delete);
                }
                break;

            case "cleardb":
                _manager.ClearDB();
                break;

            case "disable":
                var disable = _manager.Get(int.Parse(query["id"]));
                if (disable != null)
                {
                    _manager.Disable(disable);
                    response = disable.Translation;
                }
                break;

            case "create":
                try
                {
                    var culture = new CultureInfo(query["culture"]);
                    _manager.CreateCulture(new CultureInfo(query["culture"]));
                    response = culture.Name;
                }
                catch (CultureNotFoundException) { }
                break;

            case "export":

                var res     = new List <ILocalizedObject>();
                var objects = _manager.GetLocalizedObjects(new CultureInfo(query["culture"]));
                var scope   = query["scope"];

                if (!string.IsNullOrEmpty(scope))
                {
                    var scopes = scope.Split(',').Select(s => s.Trim());

                    foreach (var s in scopes)
                    {
                        res.AddRange(objects.Where(obj => obj.Scope.ToLowerInvariant().Contains(s.ToLowerInvariant())));
                    }
                }
                else
                {
                    res.AddRange(objects);
                }

                var root = _manager.GetRoot();

                var data = res.Select(x =>
                                      new
                {
                    LocaleId    = x.LocaleId,
                    Hash        = x.Hash,
                    Scope       = string.Format("{0}{1}", root, x.Scope),
                    Text        = x.Text,
                    Translation = x.Translation
                });

                var filepath = Path.GetTempFileName();

                File.WriteAllText(filepath, serializer.Serialize(data));

                context.Response.ContentType = "application/json";
                context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + query["culture"] + ".json");
                context.Response.TransmitFile(filepath);
                context.Response.End();

                break;

            case "import":
                if (context.Request.Files.Count > 0)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        using (var reader = new StreamReader(context.Request.Files[i].InputStream))
                        {
                            var json = reader.ReadToEnd();
                            _manager.Import(
                                serializer.Deserialize <IEnumerable <Repository.LocalizedObject> >(json).ToArray());
                        }
                    }
                }
                break;

            case "bulkimport":
                if (context.Request.Files.Count > 0)
                {
                    var lst = new List <ILocalizedObject>();

                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        using (var reader = new StreamReader(context.Request.Files[i].InputStream))
                        {
                            var row = 0;

                            while (!reader.EndOfStream)
                            {
                                row++;

                                var line = reader.ReadLine();

                                if (row == 1)
                                {
                                    continue;
                                }

                                if (!string.IsNullOrEmpty(line))
                                {
                                    var values = line.Split('\t');

                                    if (values.Length == 4)
                                    {
                                        lst.Add(new Repository.LocalizedObject()
                                        {
                                            Scope       = values[0],
                                            Text        = values[1],
                                            Translation = values[2],
                                            LocaleId    = int.Parse(values[3])
                                        });
                                    }
                                }
                            }
                        }
                    }
                    _manager.Import(lst.ToArray());
                }
                break;

            case "push":
                try
                {
                    if (string.IsNullOrEmpty(query["scope"]) || string.IsNullOrEmpty(query["text"]))
                    {
                        BadRequest(context);
                    }

                    else if (!LocalizationManager.Instance.GetCulture().IsDefault())
                    {
                        _manager.Translate(query["scope"], query["text"]);
                        response = "Success: \"" + query["text"] + "\" was added to scope \"" + query["scope"] + "\"";
                    }
                    else
                    {
                        response = "Success: default culture, localization was not added";
                    }
                }
                catch (Exception e)
                {
                    response = "Error: " + e.Message;
                }
                break;

            case "hint":
                try
                {
                    response = serializer.Serialize(_manager.GetLocalizedObjects(new CultureInfo(query["culture"]), query["text"])
                                                    .Where(x => !string.IsNullOrEmpty(x.Translation))
                                                    .Select(x => x.Translation)
                                                    .Distinct());
                }
                catch (CultureNotFoundException) { }
                break;

            case "search":
                try
                {
                    response = serializer.Serialize(_manager.GetLocalizedObjects(new CultureInfo(query["culture"]), query["text"], false));
                }
                catch (CultureNotFoundException) { }
                break;
            }

            return(response);
        }