Tuesday, March 22, 2016

Iframe's are useful when your code takes a while to load.

I was reading a CSV file and converting it to a HTML table to display it. However, since the file was large, it was taking a while for the code to execute and the page to be rendered. Hence, I shifted the table to an iframe and the code to the corresponding page. Now the rest of the page loads fast, and only the iframe still takes three to four more seconds to load. I can handle this even better if I can show the user an image which signifies that the iframe is loading. But I don't really need that right now. And fyi, StringBuilder helped reduce the execution time by a lot!

Sample code behind the iframe page:

//Note that FileContents is a literal control on the page.


  string folderPath;
    protected void Page_Load(object sender, EventArgs e)
    {
        folderPath = @"../Something/SomeFolder/";

        PrintFile();
    }

    private void PrintFile()
    {
        Directory.CreateDirectory(folderPath);

        DirectoryInfo d = new DirectoryInfo(folderPath);
        FileInfo[] Files = d.GetFiles("*.csv");
        foreach (FileInfo file in Files)
        {
            PrintContents(file.Name);
        }

    }

    private void PrintContents(string name)
    {
        string path = folderPath + name;
        FileContents.Text = "";
        StringBuilder htmlOutput = new StringBuilder();
        using (StreamReader readFile = new StreamReader(path))
        {
            string line;
            string[] row;
            line = readFile.ReadLine();
            string[] rowHeaders = line.Split(',');

            htmlOutput.Append("<table border='1'><tr>");
         
            foreach (string s in rowHeaders)
            {
                htmlOutput.Append("<th>" + s + "</th>");
               
            }
            htmlOutput.Append("</tr>");

            while ((line = readFile.ReadLine()) != null)
            {
                row = line.Split(',');
                if (row.Length > 1)
                {
                   
                    htmlOutput.Append("<tr>");
                    foreach (string s in row)
                    {
                        htmlOutput.Append("<td>" + s + "</td>");
                       
                    }
                    
                    htmlOutput.Append("</tr>");
                }
            }
            htmlOutput.Append("</table>");
           
        }

     


        FileContents.Text = htmlOutput.ToString();

    }


RESULT:


No comments:

Post a Comment