0

I use a form to post a file and an option field to controler. I am passing HttpPostedFileBase file to 3 methods . In two of those it is not null but in the last one it is. I am NOT assigning it value in any place. This is the code ...

My form

<form onsubmit="return check();" action="" method="post" enctype="multipart/form-data" class="form-inline">
    <div class="form-group">
        <label for="languages">Choose the language combination for translating the E BOOK </label>
        <select class=" input-large" name="languages" id="languages">

            <option value="en-fr">ENGLISH TO FRENCH</option>
            <option value="en-de">ENGLISH TO GERMAN</option>
            <option value="en-pt">ENGLISH TO PORTUGUESE</option>
            <option value="en-ru">ENGLISH TO RUSSIAN</option>
            <option value="en-sr">ENGLISH TO SERBIAN</option>
            <option value="en-es">ENGLISH TO SPANISH</option>
            <option value="fr-en">FRENCH TO ENGLISH</option>
            <option value="de-en">GERMAN TO ENGLISH</option>
            <option value="de-sr">GERMAN TO SERBIAN</option>
            <option value="pt-en">PORTUGUESE TO ENGLISH</option>
            <option value="ru-en">RUSSIAN TO ENGLISH</option>
            <option value="es-en">SPANISH TO ENGLISH</option>
        </select>
    </div>


    <div class="form-inline">
        <input type="file" class="btn btn-success" name="file" id="file" accept="text/plain, application/pdf">
        <input type="submit" class="btn btn-success" value="Upload PDF/TXT document" name="submit">
    </div>
</form>

This is the part of the controler that deals with form

This is my entire controler class

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace TranslationEmbedder.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, string languages)
        {

            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    //var fileName = Path.GetFileName(file.FileName);
                    var fileNameNoExtension = Path.GetFileNameWithoutExtension(file.FileName);
                    //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    //file.SaveAs(path);
                    HashSet<string> set=null;
                    var fileExtension = Path.GetExtension(file.FileName);

                    if (fileExtension.ToLower().Equals(".txt"))
                    {
                        set = HomeController.geUniqueWordsInEbook(file);
                    }

                    if (fileExtension.ToLower().Equals(".pdf"))
                    {
                        set = HomeController.geUniqueWordsInEbookPdf(file);
                    }

                    if (set == null)
                    {
                        return RedirectToAction("Index");
                    }

                    Dictionary<string, string> dic = HomeController.LoadCsvDictionary(set, languages);

                    if (fileExtension.ToLower().Equals(".txt"))
                    {
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNameNoExtension + ".html");
                        Response.ContentType = "text/html";
                        HomeController.writeHtmlEbookFromTxt(file, dic, languages);
                        Response.End();
                    }

                    if (fileExtension.ToLower().Equals(".pdf"))
                    {
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileNameNoExtension + ".html");
                        Response.ContentType = "text/html";
                        writeHtmlEbookFromPdf(file, dic, languages);
                        Response.End();
                    }


                    // Not sure what else to do here
                    return Content(String.Empty);



                }
            }

            return RedirectToAction("Index");
        }

        private void writeHtmlEbookFromPdf(HttpPostedFileBase file, Dictionary<string, string> dic,string languageCode)
        {


        }

        private static  void writeHtmlEbookFromTxt(HttpPostedFileBase file, Dictionary<string, string> dic, string languageCode)
        {


                var fileNameNoExtension = Path.GetFileNameWithoutExtension(file.FileName);

                    System.Web.HttpContext.Current.Response.Write("");
                    System.Web.HttpContext.Current.Response.Write("<!DOCTYPE html><html>");
                    System.Web.HttpContext.Current.Response.Write("<head><META HTTP-EQUIV='content-type' CONTENT='text/html; charset=utf-8'><title>" + fileNameNoExtension + "</title>");
                    System.Web.HttpContext.Current.Response.Write("<script>");
                    System.Web.HttpContext.Current.Response.Write("function speakIt(b)");
                    System.Web.HttpContext.Current.Response.Write("{");
                    System.Web.HttpContext.Current.Response.Write("if (document.getElementById(\"myCheck\").checked) {");
                    System.Web.HttpContext.Current.Response.Write("if ('speechSynthesis' in window) {");
                    System.Web.HttpContext.Current.Response.Write("var sometext=b;");
                    System.Web.HttpContext.Current.Response.Write("var msg = new SpeechSynthesisUtterance();");
                    System.Web.HttpContext.Current.Response.Write("var voices = window.speechSynthesis.getVoices();");
                    System.Web.HttpContext.Current.Response.Write("msg.text = sometext;");


                    string[] toSpeak = languageCode.Split('-');

                    switch (toSpeak[0])
                    {
                        case "de"://German
                            languageCode = "de-DE";
                            break;
                        case "en"://English
                            languageCode = "en-GB";
                            break;
                        case "es"://Spanish
                            languageCode = "es-ES";
                            break;
                        case "fr"://French
                            languageCode = "fr-FR";
                            break;
                        case "ru"://Russian
                            languageCode = "ru";
                            break;
                        case "pt"://Portuguese - Portugal
                            languageCode = "pt-PT";
                            break;
                        case "sr"://Serbian
                            languageCode = "sr-SP";
                            break;
                        case "ja"://Japanese
                            languageCode = "ja";
                            break;
                        case "he"://Hebrew
                            languageCode = "he";
                            break;
                        case "it"://Italian - Italy
                            languageCode = "it-IT";
                            break;
                        case "el"://Greek
                            languageCode = "el";
                            break;
                        case "zh"://Chinese - China
                            languageCode = "zh-CN";
                            break;
                        case "ar"://Arabic - Egypt
                            languageCode = "ar-EG";
                            break;
                        case "hy"://Armenian
                            languageCode = "hy";
                            break;
                        case "eu"://Basque
                            languageCode = "eu";
                            break;
                        case "be"://Belarusian
                            languageCode = "be";
                            break;
                        case "cs"://Czech
                            languageCode = "cs";
                            break;
                        case "da"://Danish
                            languageCode = "da";
                            break;
                        case "et"://Estonian
                            languageCode = "et";
                            break;
                        case "mk"://FYRO Macedonia
                            languageCode = "mk";
                            break;
                        case "hu"://Hungarian
                            languageCode = "hu";
                            break;
                        case "is"://Icelandic
                            languageCode = "is";
                            break;
                        case "hi"://Hindi
                            languageCode = "hi";
                            break;
                        case "id"://Indonesian
                            languageCode = "id";
                            break;
                        case "kk"://Kazakh
                            languageCode = "kk";
                            break;
                        case "ko"://Korean
                            languageCode = "ko";
                            break;
                        case "lv"://Latvian
                            languageCode = "lv";
                            break;
                        case "lt"://Lithuanian
                            languageCode = "lt";
                            break;
                        case "pl"://Polish
                            languageCode = "pl";
                            break;
                        case "sk"://Slovak
                            languageCode = "sk";
                            break;
                        case "sl"://Slovenian
                            languageCode = "sl";
                            break;
                        case "sv"://Swedish - Sweden
                            languageCode = "sv-SE";
                            break;
                        case "tr"://Turkish
                            languageCode = "tr";
                            break;
                        case "uk"://Ukrainian
                            languageCode = "uk";
                            break;
                        case "vi"://Vietnamese
                            languageCode = "vi";
                            break;
                        //...add more language support
                        default:
                            languageCode = "de-DE";
                            break;
                    }

                    System.Web.HttpContext.Current.Response.Write("msg.lang = '" + languageCode + "';");
                    System.Web.HttpContext.Current.Response.Write("speechSynthesis.speak(msg);");
                    System.Web.HttpContext.Current.Response.Write("}");
                    System.Web.HttpContext.Current.Response.Write("}");
                    System.Web.HttpContext.Current.Response.Write("}");

                    System.Web.HttpContext.Current.Response.Write("</script>");

                    System.Web.HttpContext.Current.Response.Write("<style>");

                    System.Web.HttpContext.Current.Response.Write("#ebook {");
                    System.Web.HttpContext.Current.Response.Write(" margin: auto;");
                    System.Web.HttpContext.Current.Response.Write("width: 90%;font-size: 200%;@page {counter-increment: page;counter-reset: page 1;@top-right {content: \"Page \" counter(page) \" of \" counter(pages);}}");
                    System.Web.HttpContext.Current.Response.Write("text-align: left;line-height:1.5;font-family: 'Merriweather', Georgia, 'Times New Roman', Times, serif;");
                    System.Web.HttpContext.Current.Response.Write("vertical-align: middle;");
                    System.Web.HttpContext.Current.Response.Write("word-wrap: break-word;");
                    System.Web.HttpContext.Current.Response.Write("border:3px solid #8AC007;");
                    System.Web.HttpContext.Current.Response.Write("padding: 10px;");
                    System.Web.HttpContext.Current.Response.Write("}");

                    System.Web.HttpContext.Current.Response.Write("#header-wrap {");
                    System.Web.HttpContext.Current.Response.Write("position: fixed;");
                    System.Web.HttpContext.Current.Response.Write("text-align: center;");
                    System.Web.HttpContext.Current.Response.Write("background-color: #8AC007;");
                    System.Web.HttpContext.Current.Response.Write("color: white;");
                    System.Web.HttpContext.Current.Response.Write("height: 25px;");
                    System.Web.HttpContext.Current.Response.Write("top: 0;");
                    System.Web.HttpContext.Current.Response.Write("width: 100%;");
                    System.Web.HttpContext.Current.Response.Write("z-index: 100;");
                    System.Web.HttpContext.Current.Response.Write("}");

                    System.Web.HttpContext.Current.Response.Write("</style>");
                    System.Web.HttpContext.Current.Response.Write("</head><body></br>");

                    System.Web.HttpContext.Current.Response.Write("<div id='header-wrap'></br>");
                    System.Web.HttpContext.Current.Response.Write("<span>ENABLE / DISABLE TEXT TO SPEECH : <input type=\"checkbox\" name=\"myCheck\" id=\"myCheck\" checked=\"checked\"></span></br></br>");
                    System.Web.HttpContext.Current.Response.Write("</div>");

                    System.Web.HttpContext.Current.Response.Write("<div id='ebook'>");




            System.IO.StreamReader reader = new System.IO.StreamReader(file.InputStream);
            string line="";
            while ((line = reader.ReadLine()) != null)
                {


                        string[] words = line.Split(' ');

                        foreach (string word in words)
                        {
                            string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower();
                            string value = "";
                            if (dic.ContainsKey(cleanWord))
                                value = dic[cleanWord];

                            System.Web.HttpContext.Current.Response.Write("<span  onclick =\"alert('" + value + "');speakIt('" + cleanWord + "'); \" >" + " " + word + " " + "</span>");
                        }

                        System.Web.HttpContext.Current.Response.Write("</br>");


                    }
                    System.Web.HttpContext.Current.Response.Write("</div></body></html>");


                reader.Close();




        }
        private static Dictionary<string, string> LoadCsvDictionary(HashSet<string> uniqueEbookWords,string language)
        {

            string languageFile = AppDomain.CurrentDomain.GetData("DataDirectory")+ "\\languages\\"+ language + ".csv";
            Dictionary<string, string> d = new Dictionary<string, string>();



            using (var reader = new StreamReader(System.IO.File.OpenRead(@languageFile)) )
            {

                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    var values = line.Split(',');

                    if (uniqueEbookWords.Contains(values[0].ToLower()))
                    {
                        if (!d.ContainsKey(values[0].ToLower()))
                            d.Add(values[0].ToLower(), values[1].ToLower());
                    }

                }


            }


            return d;
        }

        private static HashSet<string> geUniqueWordsInEbook(HttpPostedFileBase file)
        {
            //make two options one for PDF and one for TXT uploaded ebook...
            int counter = 0;
            string line;

            HashSet<string> uniqueWords = new HashSet<string>();

            System.IO.StreamReader file1 =new System.IO.StreamReader(file.InputStream);


            while ((line = file1.ReadLine()) != null)
            {
                string[] words = line.Split(' ');
                foreach (string word in words)
                {
                    string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower();
                    uniqueWords.Add(cleanWord);

                }

                counter++;
            }

            file1.Close();


            return uniqueWords;
        }

        private static HashSet<string> geUniqueWordsInEbookPdf(HttpPostedFileBase file)
        {
            //make two options one for PDF and one for TXT uploaded ebook...
            int counter = 0;
            string line;

            HashSet<string> uniqueWords = new HashSet<string>();

            System.IO.StreamReader file1 = new System.IO.StreamReader(file.InputStream);


            while ((line = file1.ReadLine()) != null)
            {
                string[] words = line.Split(' ');
                foreach (string word in words)
                {
                    string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower();
                    uniqueWords.Add(cleanWord);

                }

                counter++;
            }

            file1.Close();


            return uniqueWords;
        }



        public ActionResult About()
        {
            ViewBag.Message = "Watch a video that will you more about www.TRANSLATION-EMBEDDER.com project.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Feel free to contact us";

            return View();
        }

        [HttpPost]
        public ActionResult Contact(string email,string message)
        {

            if (email.Equals(""))
            {
                ViewBag.Message = "You must provide an email";
                return View();
            }

            if (message.Equals(""))
            {
                ViewBag.Message = "You must provide the message";
                return View();
            }

            ViewBag.Message = "The message is sent to us from the user with email: "+ email + ".We will responde as soon as possible. Have a nice day. ";
            sendEmail(email, message);
            return View();
        }

        private void sendEmail(string email, string message)
        {
            //http://stackoverflow.com/questions/18326738/how-to-send-email-in-asp-net-c-sharp

            /*
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);

            smtpClient.Credentials = new System.Net.NetworkCredential("jvkrneta@gmail.com", "tijanica");
            smtpClient.UseDefaultCredentials = true;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl = true;
            MailMessage mail = new MailMessage();

            //Setting From , To and CC
            mail.From = new MailAddress(email, "Translation-Embedder.com");
            mail.To.Add(new MailAddress("jvkrneta@gmail.com"));
            mail.Body = message;

            smtpClient.Send(mail);
            */
        }





    }
}   

And only in the method

private static  void writeHtmlEbookFromTxt(HttpPostedFileBase file, Dictionary<string, string> dic, string languageCode)

do I get null for reader and my loop for looping file never runs This part:

 System.IO.StreamReader reader = new System.IO.StreamReader(file.InputStream);
            string line="";
            while ((line = reader.ReadLine()) != null)
                {


                        string[] words = line.Split(' ');

                        foreach (string word in words)
                        {
                            string cleanWord = word.Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", "").Replace("ß", "ss").Replace("?", "").Replace("!", "").Replace("«", "").Replace("»", "").Replace("[", " ").Replace("]", " ").Replace("(", " ").Replace(")", " ").Replace(",,", " ").Replace("\"", " ").Replace("-", " ").ToLower();
                            string value = "";
                            if (dic.ContainsKey(cleanWord))
                                value = dic[cleanWord];

                            System.Web.HttpContext.Current.Response.Write("<span  onclick =\"alert('" + value + "');speakIt('" + cleanWord + "'); \" >" + " " + word + " " + "</span>");
                        }

                        System.Web.HttpContext.Current.Response.Write("</br>");


                    }
                    System.Web.HttpContext.Current.Response.Write("</div></body></html>");


                reader.Close();

I tried all the things but failed to see the reasons why the same code that I use in many methods only in this case gives null for reader OBJECT.

Jovo Krneta
  • 548
  • 1
  • 14
  • 36
  • I suspect that something else is null here. The `reader` variable cannot be null because you are assigning it a value here: `new StreamReader(file.InputStream)`. – Darin Dimitrov Apr 09 '16 at 15:14
  • This is used for parsing an ebook . First I find all the unique words - this is put in a HashSet collection - and the HashSet in filled(checked)...then for these unique words I get a Dictionary with translations (also filled in) . And at the end when I am to write a new book I can not parse the same book which I have already parsed when I was getting unique words from e book. – Jovo Krneta Apr 09 '16 at 15:20

2 Answers2

3

You cannot read the file stream twice. Inside your geUniqueWordsInEbook method you have already read the file.InputStream and even closed it at the end. That's the reason why you cannot read it a second time in the writeHtmlEbookFromTxt method. You will need to do the 2 operations in a single pass while reading the file contents. So basically you will have to reorganize your code so that the 2 operations happen in a single place while reading through the file stream.

If you do not expect the uploaded files to be very big you can load their contents in memory (in a byte[]) which you can pass through your methods. But this will be an overkill for large files.

Another option would be to save the uploaded file to the disk on your webserver and then read from this uploaded file multiple times.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is there a way around this ... just to avoid big methods – Jovo Krneta Apr 09 '16 at 15:29
  • No, there's no way. The uploaded files stream is forward readonly. Once you have read through it, you can no longer do anything else. You cannot reverse it and read it again. Another possibility is to save the uploaded file on the disk of your webserver and then read through it many times. – Darin Dimitrov Apr 09 '16 at 15:30
  • Thanks for the quick response! – Jovo Krneta Apr 09 '16 at 15:31
0

I hope it would be helpful to you.

Controler:

[HttpPost]
    public ActionResult Create(HttpPostedFileBase FileData)
    {
        string fpath = "";
        try
        {
            if (Request.Files.Count > 0)
            {
                try
                {

                    HttpPostedFileBase file = FileData;
                    string fname;
                    // want to check extension then use this method
                    //if (CheckExtension(file.ContentType.ToLower()))
                    //{
                        // Checking for Internet Explorer  
                        string extension = System.IO.Path.GetExtension(file.FileName);

                        if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                            string[] testfiles = file.FileName.Split(new char[] { '\\' });
                            fname = Guid.NewGuid() + extension; //+ testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                            fname = Guid.NewGuid() + extension; //+ file.FileName;
                        }

                        // Get the complete folder path and store the file inside it.  
                        fname = System.IO.Path.Combine(Server.MapPath("~/Content/"), fname);
                        file.SaveAs(fname);

                        return Content("Successfully Uploaded");
                    //}

                }
                catch (Exception ex)
                {
                    return Content("Error occurred. Error details: " + ex.Message);
                }
            }

        }
        catch (Exception)
        {
            return Content(Response.StatusCode.ToString() + " Bad Requrest error." + fpath);
        }
        return Content("No files selected.");
    }

    public bool CheckExtension(string Ext)
    {
        if (Ext == "application/pdf")
        {
            return true;
        }
        else if (Ext == "text/plain")
        {
            return true;
        }
        else if (Ext == "application/msword")
        {
            return true;
        }
        else if (Ext == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        {
            return true;
        }
        else
        {
            return false;
        }
    }

View:

@using (Html.BeginForm("Create", "Home", null, FormMethod.Post, new { id = "formU", enctype = "multipart/form-data" })){

<div class="modal-body">
    <div class="form-horizontal">
        @Html.ValidationSummary(true)

        <label for="file">Filename:</label>
        <input type="file" name="File" id="File" style="width:240px" />

        <div class="form-group">
            <input id="submit" type="submit" value="Submit" class="btn btn-success" />
        </div>
    </div>
</div>}

you can also download source code from git hub repository click here

Devendra Gohel
  • 112
  • 1
  • 5