SQL-Server Query not executing correctly in Umbraco C# Controller

只谈情不闲聊 提交于 2019-12-14 02:47:43

问题


So my code seems to be running fine, no exceptions or errors being thrown, however when I check my db table after the "import complete" alert jumps, there is nothing there.

PLEASE NOTE:

I am referring to the query in the SaveLT function

Here is my C# controller:

using UmbracoImportExportPlugin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Persistence;
using Umbraco.Web;
using Umbraco.Web.WebApi;

namespace UmbracoImportExportPlugin.App_Code
{

    public class ImportNewDictionaryController : UmbracoAuthorizedApiController
    {
        public string basePath;

        //Locate specific path
        public void LocatePath()
        {
            this.basePath = System.Web.Hosting.HostingEnvironment.MapPath(@"/upload");
        }
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        //[System.Web.Http.HttpPost]
        public void SaveFile()
        {
            var myContext = Request.TryGetHttpContext();
            List<string> keys = new List<string>();
            if (myContext.Success)

            {
                HttpPostedFileBase myFile = myContext.Result.Request.Files["file"];
                if (myFile == null)
                {
                   throw new HttpException("invalid file");
                }
                else
                {
                    StreamReader csvreader = new StreamReader(myFile.InputStream);


                    while (!csvreader.EndOfStream)
                    {
                        var line = csvreader.ReadLine();
                        if (line != "Key")
                        keys.Add(line);
                    }
                }
                UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
                var remove = new Sql("DELETE FROM cmsDictionary");
                int rem = db.Execute(remove);

                foreach (string item in keys)
                {
                    var insert = new Sql("INSERT INTO cmsDictionary VALUES (NEWID(), null,'" + item + "')");
                    int res = db.Execute(insert);
                }
            }
        }

        [System.Web.Http.AcceptVerbs("GET", "POST")]
        public void SaveLT()
        {
            List<string> id = new List<string>();
            var myContext = Request.TryGetHttpContext();
            List<string> data = new List<string>();
            if (myContext.Success)
            {
                HttpPostedFileBase myFile = myContext.Result.Request.Files["file"];
                if (myFile == null)
                {
                    throw new HttpException("invalid file");
                }
                else
                {
                    StreamReader csvreader = new StreamReader(myFile.InputStream);


                    while (!csvreader.EndOfStream)
                    {
                        var line = csvreader.ReadLine();
                        if (line != "Value")
                            data.Add(line);
                    }
                }
                UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
                var remove = new Sql("DELETE FROM cmsLanguageText");
                int rem = db.Execute(remove);
                for (var i = 1; i < 142; i++ )
                {
                     foreach (string lang in data)
                    {
                        foreach (string ident in id)
                        {
                            Int32.Parse(ident);
                            var insertNew = new Sql("INSERT INTO cmsLanguageText (languageId, UniqueId, value) VALUES (" + ident + " , NEWID() , '" + lang + "')");
                            int res = db.Execute(insertNew);
                        }
                    }
                }
            }
        }
        public List<int> getList()
        {
            UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
            var select = new Sql("SELECT [id] FROM umbracoLanguage;");
            List<int> id = new List<int>();
            id = db.Fetch<int>(select);
            return id;
        }

        public String GetUserName()
        {
            var current = UmbracoContext.Current;
            var user = current.UmbracoUser;
            return user.Name.ToString();
        }
    }
}

This is my angular.js controller:

angular.module("umbraco")
    .controller("ILTController", function ($scope, $http) {
        $scope.fileUpload = {};
        $scope.uploadLanguage = function () {
            var uploadUrl = " /umbraco/backoffice/api/ImportNewDictionary/SaveLT";
            var fd = new FormData();

            fd.append('file', $scope.fileUpload);

            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
            .success(function (data) {
                // ok
                alert("Import Complete!");
            })
            .error(function () {
                // handle upload error
                alert("Import Unsuccessful!");
            })
        };

    });

angular.module("umbraco").directive("qwSingleLanguageUpload", function () {
    return {
        restrict: "A",
        replace: false,
        scope: {
            myValue: '=qwSingleLanguageUpload'
        },
        link: function (scope, element, attr) {
            element.bind('change', function () {
                scope.myValue = element[0].files[0];

                if (scope.$$phase) {
                    scope.$apply();
                }
            });
        }
    }
});

I'm more concerned about why it's not importing the imported content (CSV file) to the db table than the security as this is an Umbraco backoffice plugin and the import-file tab will only be accessible by certain users with certain permissions. They'll have to access the backoffice before making an SQL injection, which is pointless because anything that's being changed by this query can be changed by that user on the dashboard anyways.

Any idea why my database table might not be uploading? I've set breakpoints, and the foreach loops are running so I'm unsure what to do now.


回答1:


You set List<string> id = new List<string>() and then you do a foreach (string ident in id). As id is an empty list you have nothing to iterate through and so your INSERT statement is never reached.

Try populating id with some values to iterate through.

Unless I've misread your code in my quick read-through.




回答2:


Rather than try SQL and insert it manually into the database, Umbraco actually has a Localization Service and model for this:

[System.Web.Http.AcceptVerbs("GET", "POST")]
    public void SaveLT()
    {
            var ls = ApplicationContext.Current.Services.LocalizationService;    

            //create a holder for the item's DictionaryTranslations

            List<DictionaryTranslation> _hello = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _submit = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _form = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _bootstrap = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _world = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _heaven = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _hell = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _this = new List<DictionaryTranslation>();
            List<DictionaryTranslation> _sublime1 = new List<DictionaryTranslation>();

             //the constructor for a DictionaryItem requires the Umbraco language object and value of the translated text                       
             //so get the language object, eg from Iso Code                            
            var language = ls.GetLanguageByIsoCode("he-IL");
            var lang1 = ls.GetLanguageByIsoCode("ru");
            var lang2 = ls.GetLanguageByIsoCode("en-US");

            // here we create a french translation for our item and add it to the list    
            DictionaryTranslation hebhello = new DictionaryTranslation(language, "שלום");
            DictionaryTranslation rushello = new DictionaryTranslation(lang1, "Здравствуйте");
            DictionaryTranslation enghello = new DictionaryTranslation(lang2, "Blah");
             _hello.Add(hebhello);
             _hello.Add(rushello);
             _hello.Add(enghello);
             DictionaryTranslation hebsubmit = new DictionaryTranslation(language, "שלח");
             DictionaryTranslation russubmit = new DictionaryTranslation(lang1, "Отправить");
             DictionaryTranslation engsubmit = new DictionaryTranslation(lang2, "Submit");
             _submit.Add(hebsubmit);
             _submit.Add(russubmit);
             _submit.Add(engsubmit);
             DictionaryTranslation hebform = new DictionaryTranslation(language, "טופס");
             DictionaryTranslation rusform = new DictionaryTranslation(lang1, "форма");
             DictionaryTranslation engform = new DictionaryTranslation(lang2, "Form");
             _form.Add(hebform);
             _form.Add(rusform);
             _form.Add(engform);
             DictionaryTranslation hebbtstrp = new DictionaryTranslation(language, "אֹזֶן הַנַעַל");
             DictionaryTranslation rusbtstrp = new DictionaryTranslation(lang1, "начальная загрузка");
             DictionaryTranslation engbtstrp = new DictionaryTranslation(lang2, "Bootstrap");
             _bootstrap.Add(hebbtstrp);
             _bootstrap.Add(rusbtstrp);
             _bootstrap.Add(engbtstrp);
             DictionaryTranslation hebworld = new DictionaryTranslation(language, "עוֹלָם");
             DictionaryTranslation rusworld = new DictionaryTranslation(lang1, "Мир");
             DictionaryTranslation engworld = new DictionaryTranslation(lang2, "World");
             _world.Add(hebworld);
             _world.Add(rusworld);
             _world.Add(engworld);
             DictionaryTranslation hebheaven = new DictionaryTranslation(language, "גן העדן");
             DictionaryTranslation rusheaven = new DictionaryTranslation(lang1, "небо");
             DictionaryTranslation engheaven = new DictionaryTranslation(lang2, "Heaven");
             _heaven.Add(hebheaven);
             _heaven.Add(rusheaven);
             _heaven.Add(engheaven);
             DictionaryTranslation hebhell = new DictionaryTranslation(language, "גגֵיהִנוֹם");
             DictionaryTranslation rushell = new DictionaryTranslation(lang1, "ад");
             DictionaryTranslation enghell = new DictionaryTranslation(lang2, "Hell");
             _hell.Add(hebhell);
             _hell.Add(rushell);
             _hell.Add(enghell);
             DictionaryTranslation hebthis = new DictionaryTranslation(language, "זֶה");
             DictionaryTranslation rusthis = new DictionaryTranslation(lang1, "это");
             DictionaryTranslation engthis = new DictionaryTranslation(lang2, "This");
             _this.Add(hebthis);
             _this.Add(rusthis);
             _this.Add(engthis);
             DictionaryTranslation hebsub = new DictionaryTranslation(language, "נִשׂגָב");
             DictionaryTranslation russub = new DictionaryTranslation(lang1, "возвышенный");
             DictionaryTranslation engsub = new DictionaryTranslation(lang2, "Sublime");
             _sublime1.Add(hebsub);
             _sublime1.Add(russub);
             _sublime1.Add(engsub);

                 //get or create a DictionaryItem, (passing in the Dictionary Key)                           
            IDictionaryItem hello = ls.DictionaryItemExists("hello_button") ? ls.GetDictionaryItemByKey("hello_button") : new DictionaryItem("hello_button");
            IDictionaryItem submit = ls.DictionaryItemExists("submit_button") ? ls.GetDictionaryItemByKey("submit_button") : new DictionaryItem("submit_button");
            IDictionaryItem form = ls.DictionaryItemExists("form_button") ? ls.GetDictionaryItemByKey("form_button") : new DictionaryItem("form_button");
            IDictionaryItem btstrp = ls.DictionaryItemExists("bootstrap_button") ? ls.GetDictionaryItemByKey("bootstrap_button") : new DictionaryItem("bootstrap_button");
            IDictionaryItem world = ls.DictionaryItemExists("world_button") ? ls.GetDictionaryItemByKey("world_button") : new DictionaryItem("world_button");
            IDictionaryItem heaven = ls.DictionaryItemExists("heaven_button") ? ls.GetDictionaryItemByKey("heaven_button") : new DictionaryItem("heaven_button");
            IDictionaryItem hell = ls.DictionaryItemExists("hell_button") ? ls.GetDictionaryItemByKey("hell_button") : new DictionaryItem("hell_button");
            IDictionaryItem This = ls.DictionaryItemExists("this_button") ? ls.GetDictionaryItemByKey("this_button") : new DictionaryItem("this_button");
            IDictionaryItem sublime = ls.DictionaryItemExists("sublime_button") ? ls.GetDictionaryItemByKey("sublime_button") : new DictionaryItem("sublime_button");
             // set the translations created above    
            hello.Translations = _hello;
            submit.Translations = _submit;
            form.Translations = _form;
            btstrp.Translations = _bootstrap;
            world.Translations = _world;
            heaven.Translations = _heaven;
            hell.Translations = _hell;
            This.Translations = _this;
            sublime.Translations = _sublime1;

             //now save the dictionary item and translations to Umbraco    
            UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
            var remove = new Sql("DELETE FROM cmsLanguageText");
            int rem = db.Execute(remove);
            ls.Save(hello);
            ls.Save(submit);
            ls.Save(form);
            ls.Save(btstrp);
            ls.Save(world);
            ls.Save(heaven);
            ls.Save(hell);
            ls.Save(This);
            ls.Save(sublime);


    }

Everything has to be put in manually, however it does the job and as long as you know the syntax it's easy.



来源:https://stackoverflow.com/questions/36862265/sql-server-query-not-executing-correctly-in-umbraco-c-sharp-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!