public ResultViewControl(tableViewModel tvm, bool getResultByTreeView)
        {

            InitializeComponent();
            if (tvm != null)
            {
                MainGirdViewControl mainGridView = new MainGirdViewControl(tvm, getResultByTreeView);
                result = mainGridView.result;
                _tableName = tvm._table.name;
                tvm1 = tvm;

                if (this.StackPanelResultViewControl.Children.Count == 0)
                {
                    this.StackPanelResultViewControl.Children.Add(mainGridView);
                    this.ResultTab.IsSelected = true;             
                    this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
                    int mainGridWidth = (((FastDB.ResultViewModel)(mainGridView.MainDataGrid.DataContext)).EndColumn * 160);
                    {
                        mainGridView.MainDataGrid.Width = mainGridWidth;
                    }
                    mainGridView.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                }
                this.DataContext = result;
            }
        }
        private void RunQueryBtn_Click(object sender, RoutedEventArgs e)
        {
            MainWindow mainWindow = (MainWindow)GetTopLevelControl(this.ShortCutsToolBar);
            isAllTabValidated = mainWindow.ValidateAllTabCntrls(this);

            SelectQueryBuilder queryBuilder = mainWindow.LoadSelectQueryBuilderNew(this);
            string queryString;
            if (queryBuilder != null)
            {
                queryString = queryBuilder.BuildQuery();
            }
            XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
            StringWriter writer = new StringWriter();
            SerializerObj.Serialize(writer, queryBuilder);
            DateTime startTime = DateTime.Now;
            TabItem rvctabItem = RVCTAbControl.SelectedItem as TabItem;
            if (XmlSQLTabTxt.Text != null && rvctabItem.Name == "XmlSQLTab")
            {
                try
                {
                    connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                    CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                    connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                    DataTable dataTable = new DataTable();
                    string sqldata = "";
                    dataTable = (MySQLData.DataAccess.ADODataBridge.getData(connectionString, XmlSQLTabTxt.Text));
                    DataView dataView = new DataView(dataTable);
                    ResultViewModel rvm = new ResultViewModel(dataView);
                    MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName, sqldata);

                    CloseableTabItem tabItem = (CloseableTabItem)this.ResultTab;

                    rvm.isModified = true;
                    rvm.isNew = true;

                    mainGridView1.DataContext = rvm;
                    tabItem.Content = mainGridView1;
                    mainGridView1.MainDataGrid.Width = dataTable.Columns.Count * 160;
                    mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                    this.DataContext = rvm;
                    this.ResultTab.IsSelected = true;
                    lblXmlSQLTabErrorMessage.Visibility = System.Windows.Visibility.Hidden;

                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    if (isErrorLoggingOn)
                    {
                        lblXmlSQLTabErrorMessage.Visibility = System.Windows.Visibility.Visible;
                        lblXmlSQLTabErrorMessage.Height = 20;
                        lblXmlSQLTabErrorMessage.Content = ex.Message;
                        LogError.Log_Err("btnRunQuery_Click", ex);
                    }
                }
                catch (Exception ex)
                {
                    if (isErrorLoggingOn)
                    {
                        LogError.Log_Err("btnRunQuery_Click", ex);
                    }
                }
                Mouse.OverrideCursor = null;
            }
            else if (isAllTabValidated)
            {
                if (mainWindow.queryString != String.Empty)
                {
                    if (queryBuilder != null)
                    {
                        CloseableTabItem tabItem = (CloseableTabItem)this.ResultTab;

                        if (tabItem.Content == null)
                        {
                            Mouse.OverrideCursor = Cursors.Wait;
                            try
                            {
                                if (queryBuilder.CrossTabClause != null)
                                {
                                    if (queryBuilder.CrossTabClause.Col == null)
                                    {
                                        MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                        result = mainGridView1.result;

                                        result.isModified = true;
                                        result.isNew = true;

                                        mainGridView1.DataContext = result;
                                        tabItem.Content = mainGridView1;

                                        mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                        mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                                        this.DataContext = result;
                                        this.ResultTab.IsSelected = true;
                                    }
                                    else
                                    {
                                        if (this.StackPanelResultViewControl.Children.Count == 1)
                                        {
                                            if ((MainGirdViewControl)this.StackPanelResultViewControl.Children[0] != null)
                                            {
                                                this.StackPanelResultViewControl.Children.RemoveAt(0);
                                            }
                                        }
                                        CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                        result = crossTabViewControl.result;
                                        this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                    }
                                }
                            }
                            catch (MySql.Data.MySqlClient.MySqlException ex)
                            {
                                if (isErrorLoggingOn)
                                {
                                    LogError.Log_Err("btnRunQuery_Click", ex);
                                }
                            }
                            catch (Exception ex)
                            {
                                if (isErrorLoggingOn)
                                {
                                    LogError.Log_Err("btnRunQuery_Click", ex);
                                }
                            }
                            Mouse.OverrideCursor = null;
                        }
                        else
                        {

                            ResultViewModel rv = (ResultViewModel)this.result;
                            if (rv.isNew)
                            {
                                // we still let user run the query, query still new and modified= true
                                Mouse.OverrideCursor = Cursors.Wait;
                                try
                                {
                                    if (queryBuilder.CrossTabClause != null)
                                    {
                                        if (queryBuilder.CrossTabClause.Col == null)
                                        {
                                            if (queryBuilder.GroupByColumns.Count == 0 && queryBuilder.SelectedColumns.Count == 0)
                                            {
                                                foreach (SQLBuilder.Clauses.Column col in this.SelectTabCntrl.lstToSelecteColFrom.Items)
                                                {
                                                    queryBuilder.SelectColumn(col);
                                                }
                                            }
                                            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = mainGridView1.result;

                                            result.isModified = true;
                                            result.isNew = true;

                                            mainGridView1.DataContext = result;
                                            tabItem.Content = mainGridView1;

                                            mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                            mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                            this.DataContext = result;
                                            this.ResultTab.IsSelected = true;
                                        }
                                        else
                                        {
                                            if (this.StackPanelResultViewControl.Children.Count == 1)
                                            {
                                                if (this.StackPanelResultViewControl.Children[0] != null)
                                                {
                                                    this.StackPanelResultViewControl.Children.RemoveAt(0);
                                                }
                                            }
                                            CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = crossTabViewControl.result;
                                            this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                            this.ResultTab.IsSelected = true;
                                        }
                                    }
                                }
                                catch (MySql.Data.MySqlClient.MySqlException ex)
                                {
                                    if (isErrorLoggingOn)
                                    {
                                        LogError.Log_Err("btnRunQuery_Click", ex);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (isErrorLoggingOn)
                                    {
                                        LogError.Log_Err("btnRunQuery_Click", ex);
                                    }
                                }
                                Mouse.OverrideCursor = null;
                            }
                            else
                            {
                                // it is old
                                //check to see if old querybuilder and new querybuilder is same, if different CompairQueryBuilder retuns true
                                if (mainWindow.CompairQueryBuilder(rv.QueryBulder, queryBuilder))
                                {
                                    Mouse.OverrideCursor = Cursors.Wait;
                                    try
                                    {
                                        string directoryPath = String.Empty;
                                        if (result != null)
                                        {
                                            if (result.directoryPath != null)
                                            {
                                                directoryPath = result.directoryPath;
                                            }
                                        }

                                        if (queryBuilder.CrossTabClause != null && queryBuilder.CrossTabClause.Col != null)
                                        {
                                            if (this.StackPanelResultViewControl.Children.Count == 1)
                                            {
                                                if (this.StackPanelResultViewControl.Children[0] != null)
                                                {
                                                    this.StackPanelResultViewControl.Children.RemoveAt(0);
                                                }
                                            }
                                            CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = crossTabViewControl.result;
                                            this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
                                            this.ResultTab.IsSelected = true;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                        }
                                        else
                                        {
                                            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
                                            result = mainGridView1.result;
                                            mainGridView1.DataContext = result;
                                            tabItem.Content = mainGridView1;

                                            mainGridView1.MainDataGrid.Width = result.EndColumn * 160;
                                            mainGridView1.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                            CloseableTabItem ti = (CloseableTabItem)mainWindow.tabControl1.SelectedItem;
                                            ti.labelStar.Content = "*";
                                        }

                                        if (directoryPath != String.Empty)
                                        {
                                            result.directoryPath = directoryPath;
                                        }

                                        result.isModified = true;
                                        result.isNew = false;

                                        this.DataContext = result;
                                        this.ResultTab.IsSelected = true;
                                    }
                                    catch (MySql.Data.MySqlClient.MySqlException ex)
                                    {
                                        if (isErrorLoggingOn)
                                        {
                                            LogError.Log_Err("btnRunQuery_Click", ex);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (isErrorLoggingOn)
                                        {
                                            LogError.Log_Err("btnRunQuery_Click", ex);
                                        }
                                    }
                                    Mouse.OverrideCursor = null;
                                }
                                this.ResultTab.IsSelected = true;
                            }
                        }
                    }
                }
                XmlSQLTabTxt.Text = queryBuilder.BuildQuery();
            }
            
            Console.WriteLine("Cross Tabulation View Control execution time: " + (DateTime.Now - startTime));
        }
        public void CheckQueryNeededToBeSaved(CloseableTabItem tabItem, String caller)
        {
            /*****************To Save Modified Query***********/

            string directoryPath = this.result.directoryPath;

            MainWindow mainWindow = (MainWindow)GetTopLevelControl(this.ShortCutsToolBar);
            mainWindow.ValidateAllTabCntrls(this);
            SelectQueryBuilder queryBuilder = mainWindow.LoadSelectQueryBuilderNew(this);

            MainGirdViewControl mainGridView1 = new MainGirdViewControl(queryBuilder, mainWindow.CurrentDatabaseName);
            this.result = mainGridView1.result;
            if (directoryPath != null)
            {
                this.result.isModified = true;
                this.result.isNew = false;
                this.result.directoryPath = directoryPath;
            }
            else
            {
                this.result.isModified = true;
                this.result.isNew = true;
            }

            /********************************************/

            ResultViewModel rv = (ResultViewModel)this.result;   

            if (this.Content != null)
            {
                if (rv.isModified)
                {
                    if (rv.isNew == false)
                    {
                        switch (caller)
                        {
                            case "Save":

                                string FileName = rv.directoryPath + tabItem.Header.ToString() + ".xml";
                                if (FileName != System.String.Empty)
                                {
                                    XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                    StreamWriter swriter = new StreamWriter(FileName);
                                    SerializerObj.Serialize(swriter, rv.QueryBulder);

                                    swriter.Flush();
                                    swriter.Close();
                                    tabItem.Header = tabItem.Header.ToString();
                                    //we saved the query change isModified to false
                                    rv.isModified = false;
                                    tabItem.labelStar.Content = "";
                                    MessageBox.Show("query saved successfully");
                                }
                                break;

                            case "SaveAs":

                                MainWindow mw = new MainWindow();
                                string FileName1 = mw.OpenSaveDialog(tabItem.Name);

                                if (FileName1 != System.String.Empty)
                                {
                                    XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                    StreamWriter swriter = new StreamWriter(FileName1);
                                    SerializerObj.Serialize(swriter, rv.QueryBulder);

                                    swriter.Flush();
                                    swriter.Close();
                                    string[] splitedArray = FileName1.Split('\\');
                                    string tabItemHeader = splitedArray[splitedArray.Length - 1].Remove((splitedArray[splitedArray.Length - 1]).Length - 4, 4);
                                    tabItem.Header = tabItemHeader;
                                    //we saved the query change isModified to false
                                    rv.isModified = false;
                                    tabItem.labelStar.Content = "";
                                    MessageBox.Show("query saved successfully");
                                }
                                break;

                            case "SaveXML":

                                FileName = ConfigurationManager.AppSettings["DerivedTablesPath"].ToString() + flName + ".xml";
                                if (File.Exists(FileName))
                                {
                                    MessageBox.Show("File already exists....");
                                }
                                else
                                {
                                    if (FileName != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileName);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        tabItem.Header = tabItem.Header.ToString();

                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");

                                        connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                                        CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                                        connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                                        DependencyObject parent = this.GetTopLevelControl(this);

                                        try
                                        {
                                            List<MySQLData.Schema> schemas = MySQLData.DataAccess.ADODataBridge.getSchemaTree(connectionString, CurrentDatabaseName, ConfigurationManager.AppSettings["DerivedTablesPath"]);//DataAccess.GetDatabases();
                                            MainViewModel viewModel = new MainViewModel(schemas);

                                            if (parent != null)
                                            {
                                                MainWindow m = (MainWindow)parent;
                                                m.MainTreeView.DataContext = viewModel;
                                                listOfTable = new List<MySQLData.Table>();
                                                foreach (MySQLData.Schema schema in schemas)
                                                {
                                                    listOfTable.AddRange(schema.tables);
                                                }
                                                if (listOfTable != null)
                                                {

                                                }
                                            }

                                        }
                                        catch (MySql.Data.MySqlClient.MySqlException ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        if (parent != null)
                                        {
                                            MainWindow m = (MainWindow)parent;
                                            var collView = CollectionViewSource.GetDefaultView(m.tabControlCustomQuery.Items);
                                            collView.CurrentChanging += this.OnTabItemSelecting;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    else
                    {
                        switch (caller)
                        {
                            case "Save":
                                if (rv.TotalIRows != 0)
                                {
                                    SaveNewQuery(tabItem, rv.QueryBulder);
                                }
                                break;

                            case "SaveAs":

                                if (rv.TotalIRows != 0)
                                {
                                    //save save as the query
                                    MainWindow mw = new MainWindow();
                                    string FileName = mw.OpenSaveDialog(tabItem.Name);

                                    if (FileName != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileName);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        string[] splitedArray = FileName.Split('\\');
                                        string tabItemHeader = splitedArray[splitedArray.Length - 1].Remove((splitedArray[splitedArray.Length - 1]).Length - 4, 4);
                                        tabItem.Header = tabItemHeader;
                                        //we saved the query change isModified to false
                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");
                                    }
                                }
                                break;

                            case "SaveXML":
                                string FileNameXML = ConfigurationManager.AppSettings["DerivedTablesPath"].ToString() + flName + ".xml";
                                if (File.Exists(FileNameXML))
                                {
                                    MessageBox.Show("File already exists....");
                                }
                                else
                                {
                                    if (FileNameXML != System.String.Empty)
                                    {
                                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SelectQueryBuilder));
                                        StreamWriter swriter = new StreamWriter(FileNameXML);
                                        SerializerObj.Serialize(swriter, rv.QueryBulder);

                                        swriter.Flush();
                                        swriter.Close();
                                        tabItem.Header = tabItem.Header.ToString();

                                        rv.isModified = false;
                                        tabItem.labelStar.Content = "";
                                        MessageBox.Show("query saved successfully");


                                        connectionString = ConfigurationManager.AppSettings["DefaultDBConn"];
                                        CurrentDatabaseName = ConfigurationManager.AppSettings["DefaultDatabase"];

                                        connectionString = connectionString + "Database=" + CurrentDatabaseName + ";";
                                        DependencyObject parent = this.GetTopLevelControl(this);

                                        try
                                        {
                                            List<MySQLData.Schema> schemas = MySQLData.DataAccess.ADODataBridge.getSchemaTree(connectionString, CurrentDatabaseName, ConfigurationManager.AppSettings["DerivedTablesPath"]);
                                            MainViewModel viewModel = new MainViewModel(schemas);

                                            if (parent != null)
                                            {
                                                MainWindow m = (MainWindow)parent;
                                                m.MainTreeView.DataContext = viewModel;
                                                listOfTable = new List<MySQLData.Table>();
                                                foreach (MySQLData.Schema schema in schemas)
                                                {
                                                    listOfTable.AddRange(schema.tables);
                                                }
                                                if (listOfTable != null)
                                                {
                                                    
                                                }
                                            }

                                        }
                                        catch (MySql.Data.MySqlClient.MySqlException ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            if (isErrorLoggingOn)
                                            {
                                                LogError.Log_Err("MainWindow Constructor", ex);
                                                DisplayErrorMessage();
                                            }
                                        }
                                        if (parent != null)
                                        {
                                            MainWindow m = (MainWindow)parent;
                                            var collView = CollectionViewSource.GetDefaultView(m.tabControlCustomQuery.Items);
                                            collView.CurrentChanging += this.OnTabItemSelecting;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
                else
                {
                    switch (caller)
                    {
                        case "Save":
                            break;
                        case "SaveAs":
                            break;
                        case "SaveXML":
                            break;
                        case "CloseTab":
                            TabControl tabControl = tabItem.Parent as TabControl;
                            if (tabControl != null)
                                tabControl.Items.Remove(tabItem);
                            break;
                    }
                }
            }
            else
            {
                if (caller == "CloseTab")
                {
                    TabControl tabControl = tabItem.Parent as TabControl;
                    if (tabControl != null)
                        tabControl.Items.Remove(tabItem);
                }
            }
        }
 public ResultViewControl(SQLBuilder.SelectQueryBuilder QuerryBuilder, string CurrentDatabaseName)
 {
     InitializeComponent();
     if (QuerryBuilder.CrossTabClause != null)
     {
         if (QuerryBuilder.CrossTabClause.Col == null)
         {
             if (this.StackPanelResultViewControl.Children.Count == 0)
             {
                 MainGirdViewControl mainGridView = new MainGirdViewControl(QuerryBuilder, CurrentDatabaseName);
                 result = mainGridView.result;
                 this.StackPanelResultViewControl.Children.Add(mainGridView);
                 this.ResultTab.IsSelected = true;
                 this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
                 int mainGridWidth = (((FastDB.ResultViewModel)(mainGridView.MainDataGrid.DataContext)).EndColumn * 160);
                 {
                     mainGridView.MainDataGrid.Width = mainGridWidth;
                 }
                 mainGridView.MainDataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;    //zahed
             }
         }
         else
         {
             if (this.StackPanelResultViewControl.Children.Count == 1)
             {
                 if ((MainGirdViewControl)this.StackPanelResultViewControl.Children[0] != null)
                 {
                     this.StackPanelResultViewControl.Children.RemoveAt(0);
                 }
             }
             CrossTabulationViewControl crossTabViewControl = new CrossTabulationViewControl(QuerryBuilder, CurrentDatabaseName);
             result = crossTabViewControl.result;
             this.ResultTab.IsSelected = true;
             this.CustomQueryAccordion.SelectionMode = AccordionSelectionMode.ZeroOrMore;
             this.StackPanelResultViewControl.Children.Add(crossTabViewControl);
         }
     }
     this.DataContext = result;
 }