private void PopulateTreeView(DirectoryInfo dirInfo, TreeNode treeNode, string userPath)
        {
            TreeView1.NodeStyle.CssClass         = "FileExplorerItem Color1";
            TreeView1.SelectedNodeStyle.CssClass = "FileExplorerItem_Active Color2";



            if (!Directory.Exists(userPath))
            {
                TreeNode directoryNode = new TreeNode
                {
                    Text  = "my saved reports",
                    Value = userPath
                };

                directoryNode.NavigateUrl = "javascript: ManualSaveReportFolderSelect(this,'" + directoryNode.Value.Replace("\\", "/") + "'); ";

                TreeView1.Nodes.Add(directoryNode);
            }
            else
            {
                foreach (DirectoryInfo directory in dirInfo.GetDirectories())
                {
                    //if (directory.FullName.IndexOf(IdUser.ToString()) == -1)
                    //    continue;

                    Guid guidOutput = Guid.Empty;
                    if (Guid.TryParse(directory.Name, out guidOutput))
                    {
                        if (!(directory.Name == IdUser.ToString()))
                        {
                            continue;
                        }
                    }

                    string Text = directory.Name;
                    if (Text == IdUser.ToString())
                    {
                        Text = "my saved reports";
                    }
                    else
                    {
                        Text = directory.Name;
                    }

                    TreeNode directoryNode = new TreeNode
                    {
                        Text  = Text,
                        Value = directory.FullName
                    };

                    directoryNode.NavigateUrl = "javascript: ManualSaveReportFolderSelect(this,'" + directoryNode.Value.Replace("\\", "/") + "'); ";

                    if (treeNode == null)
                    {
                        //If Root Node, add to TreeView.
                        TreeView1.Nodes.Add(directoryNode);
                    }
                    else
                    {
                        //If Child Node, add to Parent Node.
                        treeNode.ChildNodes.Add(directoryNode);
                    }

                    //Get all files in the Directory.
                    //foreach (FileInfo file in directory.GetFiles())
                    //{
                    //    //Add each file as Child Node.
                    //    TreeNode fileNode = new TreeNode
                    //    {
                    //        Text = file.Name,
                    //        Value = file.FullName,
                    //        Target = "_blank",
                    //        NavigateUrl = (new Uri(Server.MapPath("~/"))).MakeRelativeUri(new Uri(file.FullName)).ToString()
                    //    };
                    //    directoryNode.ChildNodes.Add(fileNode);
                    //}

                    PopulateTreeView(directory, directoryNode, userPath);
                }
            }
        }
        private void CreateReport()
        {
            ReportDefinition reportDefinition;
            string           fileName;

            string directoryName;

            if (this.Request.Params["SavedReport"] == null)
            {
                // Get the full path to the directory
                // where the saved report is saved.
                directoryName = Path.Combine(
                    Request.PhysicalApplicationPath,
                    "Fileadmin",
                    "ReportDefinitions",
                    Global.Core.ClientName,
                    Global.User.Id.ToString()
                    );

                lblPageTitle.Text = Global.LanguageManager.GetText("Crosstabs");

                if (HttpContext.Current.Session["ActiveSavedReport"] != null && Directory.Exists((string)HttpContext.Current.Session["ActiveSavedReport"]))
                {
                    Directory.Delete((string)HttpContext.Current.Session["ActiveSavedReport"], true);
                }

                HttpContext.Current.Session["ActiveSavedReport"] = null;

                if (HttpContext.Current.Session["ReportDefinition"] != null && (new FileInfo(HttpContext.Current.Session["ReportDefinition"].ToString())).DirectoryName != directoryName)
                {
                    HttpContext.Current.Session["ReportDefinition"] = null;
                }
            }
            else
            {
                Guid idUser   = Guid.Parse(this.Request.Params["SavedReport"].Substring(0, 36));
                Guid idReport = Guid.Parse(this.Request.Params["SavedReport"].Substring(36, 36));

                directoryName = Path.Combine(
                    Request.PhysicalApplicationPath,
                    "Fileadmin",
                    "Temp",
                    "OpenSavedReports",
                    HttpContext.Current.Session.SessionID,
                    this.Request.Params["SavedReport"]
                    );

                if (HttpContext.Current.Session["ActiveSavedReport"] == null || Directory.Exists(directoryName) == false)
                {
                    // Get the full path to the directory
                    // where the user's reports are saved.

                    string sourceDirectoryName = "";
                    if (HttpContext.Current.Session["ManualSaveReportFolderSelect"] != null)
                    {
                        sourceDirectoryName = HttpContext.Current.Session["ManualSaveReportFolderSelect"].ToString() + "/" + idReport.ToString();
                    }


                    if (sourceDirectoryName == "")
                    {
                        sourceDirectoryName = Path.Combine(
                            Request.PhysicalApplicationPath,
                            "Fileadmin",
                            "SavedReports",
                            Global.Core.ClientName,
                            idUser.ToString(),
                            idReport.ToString()
                            );
                    }

                    if (HttpContext.Current.Session["LinkCloudSelectedReportUrl"] == null && HttpContext.Current.Session["ManualSaveReportFolderSelect"] != null)
                    {
                        HttpContext.Current.Session["LinkCloudSelectedReportUrl"] = HttpContext.Current.Session["ManualSaveReportFolderSelect"];
                    }


                    if (HttpContext.Current.Session["LinkCloudSelectedReportUrl"] == null || !Directory.Exists(sourceDirectoryName))
                    {
                        string[] paths = Directory.GetDirectories(Path.Combine(Request.PhysicalApplicationPath,
                                                                               "Fileadmin",
                                                                               "SavedReports",
                                                                               Global.Core.ClientName,
                                                                               idUser.ToString()), "*", SearchOption.AllDirectories);

                        if (paths.Where(x => x.ToLower().IndexOf(idReport.ToString().ToLower()) > -1) != null)
                        {
                            HttpContext.Current.Session["LinkCloudSelectedReportUrl"] = paths.Where(x => x.ToLower().IndexOf(idReport.ToString().ToLower()) > -1).FirstOrDefault();
                        }
                    }


                    if (HttpContext.Current.Session["LinkCloudSelectedReportUrl"].ToString().IndexOf(idReport.ToString()) != -1)
                    {
                        sourceDirectoryName = HttpContext.Current.Session["LinkCloudSelectedReportUrl"].ToString();
                    }


                    if (Directory.Exists(directoryName))
                    {
                        Directory.Delete(directoryName, true);
                    }

                    Directory.CreateDirectory(directoryName);

                    foreach (string file in Directory.GetFiles(sourceDirectoryName).OrderBy(d => new FileInfo(d).CreationTime))
                    {
                        File.Copy(file, Path.Combine(
                                      directoryName,
                                      new FileInfo(file).Name
                                      ));
                        File.SetCreationTime(Path.Combine(
                                                 directoryName,
                                                 new FileInfo(file).Name
                                                 ), File.GetCreationTime(file));
                    }


                    //foreach (string file in Directory.GetFiles(sourceDirectoryName))
                    //{
                    //    File.Copy(file, Path.Combine(
                    //        directoryName,
                    //        new FileInfo(file).Name
                    //    ));
                    //}
                }

                if (HttpContext.Current.Session["ActiveSavedReport"] == null)
                {
                    HttpContext.Current.Session["ReportDefinition"] = null;
                }

                HttpContext.Current.Session["ActiveSavedReport"] = directoryName;

                if (HttpContext.Current.Session["ReportDefinition"] != null)
                {
                    if (new FileInfo(HttpContext.Current.Session["ReportDefinition"].ToString()).DirectoryName != directoryName)
                    {
                        HttpContext.Current.Session["ReportDefinition"] = null;
                    }
                }

                ReportDefinitionInfo savedReportInfo = new ReportDefinitionInfo(Path.Combine(
                                                                                    directoryName,
                                                                                    "Info.xml"
                                                                                    ));

                lblPageTitle.Text = "<table style=\"display:inline-block\"><tbody style=\"display:inline-block\"><tr style=\"display:inline-block\"><td style=\"display:inline-block\"><img src=\"/Images/Icons/Back.png\" onclick=\"window.location='/Pages/LinkCloud.aspx'\" " +
                                    "onmouseover=\"this.src='/Images/Icons/Back_Hover.png'\" onmouseout=\"this.src='/Images/Icons/Back.png'\" style=\"cursor:pointer;\" />" +
                                    "</td><tr style=\"margin-top:-20px;display:inline-block \"><td style=\"display:inline-block\">" + savedReportInfo.Name + "</td></tr></tr></tbody></table>";
            }


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

            ReportDefinitionInfo info = new ReportDefinitionInfo(Path.Combine(
                                                                     directoryName,
                                                                     "Info.xml"
                                                                     ));

            info.LatestAccess = DateTime.Now;

            info.Save();

            // Get all the reports of the user.
            List <string> reports = info.GetReports(
                Global.Core,
                Global.IdUser.Value
                );

            if (HttpContext.Current.Session["ReportDefinition"] != null)
            {
                if (!reports.Contains(HttpContext.Current.Session["ReportDefinition"]))
                {
                    HttpContext.Current.Session["ReportDefinition"] = null;
                }
            }

            if (HttpContext.Current.Session["ReportDefinition"] == null && info.ActiveReport.HasValue)
            {
                HttpContext.Current.Session["ReportDefinition"] = Path.Combine(
                    directoryName,
                    info.ActiveReport.Value + ".xml"
                    );
            }

            // Check if for the current session a report is selected.
            if (HttpContext.Current.Session["ReportDefinition"] == null ||
                File.Exists(HttpContext.Current.Session["ReportDefinition"].ToString()) == false)
            {
                // Check if the user has reports defined.
                if (reports.Count == 0)
                {
                    fileName = Path.Combine(
                        directoryName,
                        Guid.NewGuid().ToString() + ".xml"
                        );

                    string fileNameWorkflow = Path.Combine(
                        Request.PhysicalApplicationPath,
                        "App_Data",
                        "ReportingWorkflows",
                        Global.Core.ClientName + ".xml"
                        );

                    string fileNameWeighting = Path.Combine(
                        Request.PhysicalApplicationPath,
                        "App_Data",
                        "WeightingDefaults",
                        Global.Core.ClientName + ".xml"
                        );

                    if (!File.Exists(fileNameWeighting))
                    {
                        fileNameWeighting = null;
                    }

                    reportDefinition = new ReportDefinition(
                        Global.Core,
                        fileName,
                        fileNameWorkflow,
                        fileNameWeighting,
                        Global.HierarchyFilters[fileName, false],
                        Global.UserDefaults["ReportDefinitionSettings"]
                        );

                    reportDefinition.XmlDocument.DocumentElement.SetAttribute("Name", GetUniqueReportName(string.Format(Global.LanguageManager.GetText("NewReport"), "").Trim(), directoryName));

                    reportDefinition.Save();

                    reports = info.GetReports(
                        Global.Core,
                        Global.IdUser.Value
                        );
                }
                else
                {
                    // Select the first report as the selected report.
                    fileName = reports[0];
                }

                HttpContext.Current.Session["ReportDefinition"] = fileName;
            }
            else
            {
                // Get the full path to the currently selected report's definition file.
                fileName = HttpContext.Current.Session["ReportDefinition"].ToString();
            }
            // Get the full path of the current session's report definition file.
            string directory = (new FileInfo(HttpContext.Current.Session["ReportDefinition"].ToString())).DirectoryName;

            // Run through all files of the directory.
            foreach (string file in Directory.GetFiles(directory).OrderBy(x => new FileInfo(x).CreationTime))
            {
                if (Path.GetFileName(file) == "Info.xml")
                {
                    continue;
                }
                csFilterDefinition.Source = file;
                EquationDefinition.Source = file;

                HierarchySelector.FileName = Path.Combine(
                    HttpContext.Current.Request.PhysicalApplicationPath,
                    "App_Data",
                    "HierarchySelectors",
                    Global.Core.ClientName + ".xml"
                    );

                HierarchySelector.Source = file;

                // Create a new report definition by the report definition file.
                reportDefinition = new ReportDefinition(
                    Global.Core,
                    file,
                    Global.HierarchyFilters[file]
                    );
                bool hasNewCategories1 = reportDefinition.CheckForNewCategories();

                if (hasNewCategories1)
                {
                    reportDefinition.Save();

                    reportDefinition = new ReportDefinition(
                        Global.Core,
                        file,
                        Global.HierarchyFilters[file]
                        );

                    ReportCalculator calculator = new ReportCalculator(
                        reportDefinition,
                        Global.Core,
                        HttpContext.Current.Session
                        );

                    calculator.Aggregate((string)HttpContext.Current.Session["Version"]);
                }
                if (HierarchySelector.Exists)
                {
                    HierarchySelector.Parse();
                }
                reportDefinition.Save();
            }

            csFilterDefinition.Source = fileName;
            EquationDefinition.Source = fileName;

            HierarchySelector.FileName = Path.Combine(
                HttpContext.Current.Request.PhysicalApplicationPath,
                "App_Data",
                "HierarchySelectors",
                Global.Core.ClientName + ".xml"
                );

            HierarchySelector.Source = fileName;

            // Create a new report definition by the report definition file.
            reportDefinition = new ReportDefinition(
                Global.Core,
                fileName,
                Global.HierarchyFilters[fileName]
                );
            bool hasNewCategories = reportDefinition.CheckForNewCategories();

            if (hasNewCategories)
            {
                reportDefinition.Save();

                reportDefinition = new ReportDefinition(
                    Global.Core,
                    fileName,
                    Global.HierarchyFilters[fileName]
                    );

                ReportCalculator calculator = new ReportCalculator(
                    reportDefinition,
                    Global.Core,
                    HttpContext.Current.Session
                    );

                calculator.Aggregate((string)HttpContext.Current.Session["Version"]);
            }

            if (HierarchySelector.Exists)
            {
                HierarchySelector.Parse();

                int optionCount = 0;

                foreach (Classes.Controls.HierarchySelectorSection section in HierarchySelector.Sections.Values)
                {
                    optionCount += section.OptionCount;
                }

                if (optionCount <= 1)
                {
                    pnlRightPanelHierarchy.Visible = false;
                }
                else
                {
                    pnlRightPanelHierarchy.Attributes.Add("onclick", string.Format(
                                                              "InitDragBox('boxHierarchySelectorControl');LoadHierarchySelectedItems('{0}');",
                                                              HttpUtility.UrlEncode(fileName.Replace("\\", "/"))
                                                              ));

                    if (reportDefinition.XmlDocument.DocumentElement.SelectSingleNode("HierarchyFilter") == null)
                    {
                        Page.ClientScript.RegisterStartupScript(
                            this.GetType(),
                            "ShowHierarchySelector",
                            string.Format("InitDragBox('boxHierarchySelectorControl');LoadHierarchySelectedItems('{0}');",
                                          HttpUtility.UrlEncode(fileName.Replace("\\", "/"))),
                            true
                            );
                    }
                }
            }
            else
            {
                pnlRightPanelHierarchy.Visible = false;
            }

            if (base.ContentWidth != 0)
            {
                reportDefinition.Settings.TableWidth = base.ContentWidth;
            }

            if (base.ContentHeight != 0)
            {
                reportDefinition.Settings.TableHeight = base.ContentHeight;
            }

            reportDefinition.Save();

            Crosstables.Classes.Crosstable crosstable = new Crosstables.Classes.Crosstable(
                Global.Core,
                fileName
                );

            //crosstable.FilterClickAction = "ctl00$cphContent$btnDisplayFilters";

            pnl.Controls.Add(crosstable);

            BindSettings(reportDefinition);
            BindFilteredCategories(reportDefinition);
            BindWeightingDefinition(reportDefinition);
            BindReports(reports);

            if (reportDefinition.Workflow.Selections.Count > 0)
            {
                if (bool.Parse(Global.UserDefaults["BottomBarPinned", "false"]))
                {
                    pnlWorkflowContainer.CssClass = "WorkflowPinned BorderColor1";
                }

                pnlWorkflow.Controls.Add(reportDefinition.Workflow);
            }
            else
            {
                pnlWorkflowContainer.Visible = false;
            }

            if ((fileName.IndexOf(IdUser.ToString()) == -1) && (Convert.ToBoolean(HttpContext.Current.Session["RenderValues"]) == true))
            {
                HttpContext.Current.Session["RenderValues"] = false;
                ScriptManager.RegisterClientScriptBlock(this, GetType(), "Javascript", "RenderValues();", true);
            }
        }