//16Jul2015 refresh both grids when 'refresh' icon in outputwindow is clicked
 public void RefreshBothGrids(List <string> sortcolnames = null, string sortorder = null)//16May2013 //This can/may be called to refresh Grids from App Main window
 {
     PreExecuteSub();
     if (ds != null)//19Mar2013
     {
         IUnityContainer container = LifetimeService.Instance.Container;
         IDataService    service   = container.Resolve <IDataService>();
         ds = service.Refresh(ds);
         if (ds != null)
         {
             UIController.sortcolnames = sortcolnames; //11Apr2014
             UIController.sortorder    = sortorder;    //14Apr2014
             UIController.RefreshBothGrids(ds);
         }
     }
 }
        //In Datagrid tabs the tab title looks like this : Cars.sav(DatasetN), where N is any integer.
        //So here DatasetN is the object in memory that is dataframe( or similar).
        //Cars.sav is just extra info about the Dataset you tried to open. This extra info could be a disk filename
        // or it could also be just a memory object name if memory object name is different from 'DatasetN' style of naming
        // eg.. mydf(mydf) , Dataset1(Dataset1), Cars.sav(Dataset2), mydata.rdata(Dataset3)
        // in above example mydf, Dataset1 Dataset2, Dataset3 , all R objects exists in R memory.

        //Wrong way of naming would look something like this : mydf(Dataset1)
        // mydf is not a disk file, so lets assume it may be R dataframe obj in memory, but then we always put memory object
        // name within round brackets, so, if (Dataset1) is a memory object, the extra info 'mydf' does not make sense.
        //So 'mydf' should be named as 'Dataset1' instead.
        //Right thing would be either one of two mydf(mydf) or Dataset1(Dataset1) for non-disk datasets

        public DataSource OpenDataframe(string dframename, string sheetname, string fname = "") //13Feb2014
        {
            UAReturn   datasrc = null;
            DataSource ds      = null;

            if (!isDatasetNew(dframename /*+ sheetname*/)) // if data.frame with same name already loaded in C1DataGrid
            {
                string filename = _datasourcenames[dframename /*+ sheetname*/];
                //////////    datasrc = new UAReturn();
                //////////    datasrc = _analyticService.DataFrameLoad(filename, dframename, sheetname);
                //////////    //////////////
                //////////    if (datasrc == null)
                //////////    {
                //////////        logService.WriteToLogLevel("Could not open: " + filename, LogLevelEnum.Error);
                //////////        return null;
                //////////    }
                //////////    else if (datasrc != null && datasrc.Datasource == null)
                //////////    {
                //////////        if (datasrc.Error != null && datasrc.Error.Length > 0)
                //////////        {
                //////////            logService.WriteToLogLevel("Could not refresh/open: " + filename + ".\n" + datasrc.Error, LogLevelEnum.Error);
                //////////        }
                //////////        else
                //////////            logService.WriteToLogLevel("Could not refresh/open: " + dframename + ".\nInvalid format OR issue related to R.Net server.", LogLevelEnum.Error);

                //////////        DataSource dsnull = new DataSource() { Message = datasrc.Error };
                //////////        return dsnull;
                //////////    }

                //////////    datasrc.CommandString = "Refresh Dataframe";
                try
                {
                    if (_datasources.Keys.Contains(filename + sheetname))
                    {
                        ds = _datasources[filename + sheetname];
                    }
                    else //no need to check if it exists as we alreay checked if its new dataset or not in code above
                    {
                        ds = _datasources[_datasourcenames[dframename /*+ sheetname*/].Trim() + sheetname];
                    }

                    //So by now we know we know that Dataset name is same.
                    //And new one already overwrote old data.frame in memory.



                    //Now we need to figure out if the disk filename is same or not
                    //if same no issue. If different then we need to replace old with new filename
                    #region Overwrite with new filename if Filename is different from old one
                    //if ( !filename.ToLower().Equals(fname)) //fname.Length > 0 && filename.Length > 0 &&
                    //{
                    //    //remove old keys in _datasources _datasourcenames
                    //    if (_datasources.Keys.Contains(filename + sheetname)) //Check if dataset is already loaded in the grid
                    //    {
                    //        _datasources.Remove(filename + sheetname);//Remove old
                    //        //_datasources.Add(dsourceName.FileName + sheetname, dsourceName);///Replace ds with new one

                    //        //5Mar2014 No need to do following but we can still do it
                    //        _datasourcenames.Remove(dframename /*+ sheetname*/);
                    //        //_datasourcenames.Add(dsourceName.Name + sheetname, dsourceName.FileName);
                    //    }
                    //}

                    //update ds. if new filename then overwrite old. if blank then use DatasetNN for filename
                    if (fname.Trim().Length > 0)
                    {
                        ds.FileName = fname;
                    }
                    else
                    {
                        // ds.FileName = dframename;
                        ds.SheetName = UtilFunctions.GetSheetname(ds);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    logService.WriteToLogLevel("Error getting existing DataSource handle", LogLevelEnum.Fatal);
                }
                string existingDatasetname = ds.Name;

                //20Oct2016 save a copy for using in 'if' below
                DataSource ds_for_cleanup = ds;

                ds = Refresh(ds);

                if (ds == null)//20Oct2016 Making UI grid NULL
                {
                    ds                  = new DataSource();
                    ds.Variables        = new List <DataSourceVariable>();//making it blank
                    ds.FileName         = ds_for_cleanup.FileName;
                    ds.Name             = ds_for_cleanup.Name;
                    ds.SheetName        = UtilFunctions.GetSheetname(ds_for_cleanup);
                    ds.DecimalCharacter = ds_for_cleanup.DecimalCharacter;
                    ds.FieldSeparator   = ds_for_cleanup.FieldSeparator;
                    ds.HasHeader        = ds_for_cleanup.HasHeader;
                    ds.IsBasketData     = ds_for_cleanup.IsBasketData;
                    UIController        = LifetimeService.Instance.Container.Resolve <IUIController>();
                    UIController.RefreshBothGrids(ds);
                    //here I can also close before or after above line(whereever works)
                    //Close(ds_for_cleanup);

                    //Generating the message for null dataset
                    CommandRequest msg = new CommandRequest();
                    msg.CommandSyntax = ds_for_cleanup.Name + " been set to NULL. The reason may be, running some analysis or command on the dataset.";
                    //string title = "NULL Dataset.";
                    //if (msg != null && title != null)//16May2013
                    //    SendToOutputWindow(title, msg.CommandSyntax);
                    logService.WriteToLogLevel(msg.CommandSyntax, LogLevelEnum.Error);
                }
            }
            else // Its New Data.Frame .
            {
                string datasetname = "Dataset" + SessionDatasetCounter;//dframename;// //(_datasources.Keys.Count + 1);//can also be filename without path and extention

                //15Jun2015 dframename exists in memory so use that name for datagrid tab name enclosed in round brackets (Dataset1) or (df1)
                if (!dframename.Equals(datasetname)) //df2 and Dataset2
                {
                    datasetname = dframename;
                    //use df2 for both because df2 exists in R memory
                    //no need to increament the SessionDatasetCounter as when you try to open a disk file it will have (Dataset2)
                    // as name and it will not clash with the (df2) name.
                    //incrementing may not harm but there is no need to increment.

                    //ELSE dframename.Equals(datasetname) like both are say "Dataset2"
                    // use (Dataset2) for both because Dataset2 exists in memory
                    //Also increament the SessionDatasetCounter in this case because now later
                    //when you open Dataset from disk is should have name Dataset3 and not Dataset2
                }
                if (fname.ToLower().EndsWith(".rdata") || fname.ToLower().EndsWith(".rda"))
                {
                    dframename = fname; //pass RData filename
                }
                datasrc = _analyticService.DataFrameLoad(dframename, datasetname, "");

                if (datasrc == null)
                {
                    logService.WriteToLogLevel("Could not open: " + dframename, LogLevelEnum.Error);
                    return(null);
                }
                else if (datasrc != null && datasrc.Datasource == null)
                {
                    if (datasrc.Error != null && datasrc.Error.Length > 0)
                    {
                        logService.WriteToLogLevel("Could not open: " + dframename + ".\n" + datasrc.Error, LogLevelEnum.Error);
                    }
                    else
                    {
                        logService.WriteToLogLevel("Could not open: " + dframename + ".\nInvalid format OR issue related to R.Net server.", LogLevelEnum.Error);
                    }

                    DataSource dsnull = new DataSource()
                    {
                        Message = datasrc.Error
                    };
                    return(dsnull);
                }

                datasrc.CommandString = "Open Dataset";//21Oct2013
                ds = datasrc.Datasource.ToClientDataSource();

                if (ds != null)//03Dec2012
                {
                    //_datasources.Add(ds.FileName, ds);///key filename
                    if (!_datasources.ContainsKey(ds.FileName + ds.SheetName))             //for avoiding crash
                    {
                        _datasources.Add(ds.FileName + ds.SheetName, ds);                  ///key filename
                    }
                    if (!_datasourcenames.ContainsKey(datasetname))                        //for avoiding crash
                    {
                        _datasourcenames.Add(datasetname /*+ ds.SheetName*/, ds.FileName); //5Mar2014
                    }
                }
                ///incrementing dataset counter //// 15Jun2015
                /// if the name of the Dataset created in syntax matches to the Dataset name generated for UI grid.
                if (dframename.Equals(datasetname))
                {
                    SessionDatasetCounter++;
                }
            }
            if (fname.Length == 0)
            {
                ds.Extension = "";
                ds.FileName  = "";
            }
//04Nov2014. Dont show "Open Dataset" before subset command title.   SendToOutput(datasrc);
            return(ds);
        }
        //this is common. Called from FileOpen and OnExecute, only after checking default R packages
        private void OpenDataset(string filename, bool afterSaveAs = false)
        {
            AdvancedLogging = AdvancedLoggingService.AdvLog; //08Aug2016
            // Start Some animation for loading dataset ///
            BSkyMouseBusyHandler.ShowMouseBusy();            // ShowProgressbar_old();//ShowStatusProgressbar();//29Oct2014

            string showRDataWarningStr = confService.GetConfigValueForKey("RDataOpenWarning");
            bool   showRDataWarning    = showRDataWarningStr.ToLower().Equals("true") ? true : false;

            string               errormsg = string.Empty;
            DataSource           ds       = null;
            IOpenDataFileOptions csvo     = new OpenDataFileOptions(); //
            bool removeSpacesSPSS         = false;                     //for SPSS files.

            if (filename != null && filename.Length > 0)
            {
                if (System.IO.File.Exists(filename))
                {
                    //23Oct2016(2) Blank not working in the following.
                    string sheetname = "";                                       //23Oct2016(1) null replaced by empty. File>recent opens aonther grid tab if the current grid has become null

                    if (filename.EndsWith(".xls") || filename.EndsWith(".xlsx")) //27Jan2014
                    {
                        object tbls = service.GetOdbcTableList(filename);

                        if (tbls != null)
                        {
                            SelectTableWindow stw   = new SelectTableWindow();
                            string[]          tlist = null;

                            if (tbls.GetType().Name.Equals("String"))
                            {
                                tlist    = new string[1];
                                tlist[0] = tbls as string;
                            }
                            else if (tbls.GetType().Name.Equals("String[]"))
                            {
                                tlist = tbls as string[];
                            }

                            stw.FillList(tlist);
                            BSkyMouseBusyHandler.HideMouseBusy();// HideProgressbar_old();
                            stw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            stw.ShowDialog();
                            BSkyMouseBusyHandler.ShowMouseBusy();     // ShowProgressbar_old();
                            if (stw.SelectedTableName == null)        //cancel clicked
                            {
                                BSkyMouseBusyHandler.HideMouseBusy(); // HideProgressbar_old();//HideStatusProgressbar();//29Oct2014
                                return;
                            }
                            else
                            {
                                sheetname = stw.SelectedTableName;
                            }
                        }
                    }
                    else if (filename.ToLower().EndsWith(".rdata") && showRDataWarning && !afterSaveAs)  //dont show warning if file is auto opened after 'SaveAs'
                    {
                        if (!appwindow.RDataShowWarningDialogCheck)                                      //for first time and also when checkbox is not checked
                        {
                            string s1 = BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine1; //Not in use. Replaced by s1a, s1b
                            string s2 = "\n\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine2;
                            string s3 = "\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine3;
                            string s4 = "\n\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine4;
                            string s5 = "\n\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine5;
                            string s6 = "\n\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine6;
                            string s7 = "\n\n" + BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine7;

                            //string s1 = "Loading RDATA file may overwrite your current variables/objects in memory if variables/objects with the same name are already present in the RDATA file.";
                            string s1a = BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine1a;  //
                            string s1b = BSky.GlobalResources.Properties.Resources.OpenRDataWarnMsgLine1b;; //

                            //string s2 = "\n\nYou can cancel out of here and save your all your current variables/objects which you can load later if required.";
                            //string s3 = "\nTo save/load your current variables/object run following commands from BlueSky R command editor.";
                            //string s4 = "\n\nTo save:  save.image(file='filename.rdata') # filename.rdata is the file name where objects will be saved.";
                            //string s5 = "\n\nTo load:  load(file='filename.rdata') # filename.rdata is the file name from which objects will be loaded.";
                            //string s6 = "\n\n'filename.rdata' is filename with forward slashed path e.g. 'C:/myfolder/myobjects.rdata' ";
                            //string s7 = "\n\nDo you want to proceed? [Variables with matching names will be overwritten].";
                            //MessageBoxResult messageBoxResult = MessageBox.Show(s1a + s1b + s2 + s3 + s4 + s5 + s6 + s7, "Please Confirm...", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            //if (messageBoxResult == MessageBoxResult.Yes)
                            //{
                            //    //MessageBox.Show("You selected to proceed");
                            //}
                            //else
                            //{
                            //    //MessageBox.Show("You selected to cancel");
                            //    BSkyMouseBusyHandler.HideMouseBusy();
                            //    return;
                            //}

                            RDataWarningMessageBox rdataMBox = new RDataWarningMessageBox();
                            rdataMBox.Msg    = s1a;
                            rdataMBox.AdvMsg = s1b + s2 + s3 + s4 + s5 + s6 + s7;
                            BSkyMouseBusyHandler.HideMouseBusy();
                            rdataMBox.ShowDialog();
                            BSkyMouseBusyHandler.ShowMouseBusy();
                            if (rdataMBox.NotShowCheck)//do not show the checkbox again
                            {
                                appwindow.RDataShowWarningDialogCheck = true;
                            }
                            if (rdataMBox.ButtonClicked == "Cancel")
                            {
                                BSkyMouseBusyHandler.HideMouseBusy();
                                return;
                            }
                        }
                    }
                    else if (filename.ToLower().EndsWith(".r"))// its R script
                    {
                        //errormsg = "To open a R script, you need to switch to the 'Output and Syntax' window.\n" +
                        //    "Go to the right hand pane of the 'Output and Syntax' window and click File -> Open in the 'R Command Editor'.";

                        errormsg = BSky.GlobalResources.Properties.Resources.OpenRScriptInSynWin + "\n" +
                                   BSky.GlobalResources.Properties.Resources.OpenRScriptMenuPath;
                        ds = null;

                        BSkyMouseBusyHandler.HideMouseBusy();// HideProgressbar_old();
                        MessageBox.Show(errormsg, BSky.GlobalResources.Properties.Resources.ErrOpeningFile + "(" + filename + ")", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        SendToOutputWindow(BSky.GlobalResources.Properties.Resources.ErrOpeningDataset, filename + errormsg);
                        return;
                    }
                    else if (filename.ToLower().EndsWith(".txt") || filename.ToLower().EndsWith(".csv") || filename.ToLower().EndsWith(".dat"))
                    {
                        OpenCSVTXTOptionsWindow csvopwin = new OpenCSVTXTOptionsWindow();
                        csvopwin.Owner = appwindow;
                        csvopwin.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        BSkyMouseBusyHandler.HideMouseBusy();
                        csvopwin.ShowDialog();
                        //get all parameters
                        csvo = csvopwin.csvtxtOptions;
                        if (csvo == null)//user clicked cancel
                        {
                            return;
                        }

                        BSkyMouseBusyHandler.ShowMouseBusy();
                        //do further processing by passing it into service.open()
                    }
                    else if (filename.EndsWith(".sav"))
                    {
                        OpenSPSSoptionsWindow spssOpt = new OpenSPSSoptionsWindow();
                        spssOpt.Owner = appwindow;
                        BSkyMouseBusyHandler.HideMouseBusy();
                        spssOpt.ShowDialog();
                        BSkyMouseBusyHandler.ShowMouseBusy();
                        removeSpacesSPSS = spssOpt.TrimSpaces;
                    }
                    logService.WriteToLogLevel("Setting DataSource: ", LogLevelEnum.Info);

                    Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    long      elapsed   = 0;

                    // if RData file then get all the data.frame and tbl_df objects.
                    //Give users choice to load one or more of available data.frames in the grid.
                    if (filename.ToLower().EndsWith(".rdata")) //&& !afterSaveAs)
                    {
                        bool     isSingleDFinFile = false;     //if there is a single data.frame object in a file and no other obj.
                        bool     isOneBlank       = false;
                        string[] selectedDF       = null;
                        //get list of data.frame or tbl_df objects from R
                        object tbls = service.GetRDataDataframeObjList(filename);
                        if (tbls != null && !tbls.ToString().Equals("No Result - Check Command"))
                        {
                            string[] tlist = null;

                            if (tbls.GetType().Name.Equals("String"))
                            {
                                tlist            = new string[1];
                                tlist[0]         = tbls as string;
                                isSingleDFinFile = true;
                            }
                            else if (tbls.GetType().Name.Equals("String[]"))
                            {
                                tlist = tbls as string[];
                                if (tlist.Length == 2)
                                {
                                    if (tlist[1].Trim().Length == 0)//blank entry. Also represent there are other objs in Rdata
                                    {
                                        isOneBlank = true;
                                        //remove blank entry
                                        string tempentry = tlist[0];
                                        tlist    = new string[1];
                                        tlist[0] = tempentry;
                                    }
                                }
                            }

                            if (tlist != null && tlist.Length > 1)
                            {
                                BSkyMouseBusyHandler.HideMouseBusy();
                                SelectRdataDataframesWindow srdataw = new SelectRdataDataframesWindow();
                                srdataw.LoadListbox(tlist);
                                srdataw.ShowDialog();
                                string DlgRes = srdataw.DlgResult;
                                if (DlgRes.Equals("Ok"))
                                {
                                    BSkyMouseBusyHandler.ShowMouseBusy();
                                    selectedDF = srdataw.SelectedDFList;
                                }
                                else // 'Cancel' clicked
                                {
                                    //no code here. User aborted the loading in the grid but he already have RData file loaded.
                                    return;
                                }
                            }
                            else if (tlist != null && tlist.Length == 1)
                            {
                                selectedDF = tlist;
                            }

                            #region Load seleted data.frames
                            if (selectedDF != null || selectedDF.Length > 0)
                            {
                                string title = "RData file loaded : " + filename;
                                //SendToOutputWindow("", title, false);
                                PrintTitle(title);

                                //load all the selected dataframes
                                StringBuilder sb = new StringBuilder();
                                StringBuilder selectedDSnames = new StringBuilder("Loaded ");
                                int           selidx          = 1;
                                foreach (string s in selectedDF)
                                {
                                    if (s.Equals("UAObj$obj")) //if it is old RData BSky proprietary format.
                                    {
                                        string RDataFilename = Path.GetFileNameWithoutExtension(filename);
                                        //remove special chars if any in the RDataFilename.
                                        RDataFilename = RemoveSplChars(RDataFilename);

                                        sb.Append(RDataFilename + " <- as.data.frame(" + s + ") ;");
                                        sb.Append("BSkyLoadRefreshDataframe(" + RDataFilename + ");");
                                        selectedDSnames.Append(RDataFilename);
                                    }
                                    else
                                    {
                                        sb.Append("BSkyLoadRefreshDataframe(" + s + ");"); //s must be data.frame name and not the nested data.frame obj.
                                        selectedDSnames.Append(s);
                                        if (selidx < selectedDF.Length)
                                        {
                                            selectedDSnames.Append(", ");
                                            selidx++;
                                        }
                                    }
                                }
                                selectedDSnames.Append("Data frames.");

                                string             commands = sb.ToString();
                                SyntaxEditorWindow sewindow = LifetimeService.Instance.Container.Resolve <SyntaxEditorWindow>();
                                if (isSingleDFinFile)
                                {
                                    sewindow.RunCommands(commands, null, filename);
                                }
                                else
                                {
                                    sewindow.RunCommands(commands, null);
                                }

                                //sewindow.SendCommandToOutput("RData file loaded :: " + filename, "RData Loaded");
                                sewindow.DisplayAllSessionOutput("Load RData file");
                                //SendToOutputWindow(filename + " loaded", selectedDSnames.ToString(), false);
                                recentfiles.AddXMLItem(filename);//adding to XML file for recent docs
                                appwindow.RefreshRecent();
                                return;
                            }
                            #endregion
                        }
                        //else
                        //{
                        //    MessageBox.Show("Data frame object not found!");
                        //    SendToOutputWindow(BSky.GlobalResources.Properties.Resources.ErrOpeningDataset, filename + errormsg);
                        //}
                    }
                    else
                    {
                        ds = service.Open(filename, sheetname, removeSpacesSPSS, csvo);
                        stopwatch.Stop();
                        elapsed = stopwatch.ElapsedMilliseconds;

                        if (AdvancedLogging)
                        {
                            logService.WriteToLogLevel("PERFORMANCE:Both Dataset Opened and Col Attributes read: Time taken: " + elapsed, LogLevelEnum.Info);
                        }
                    }

                    if (ds != null && ds.Message != null && ds.Message.Length > 0) //message that is related to error
                    {
                        errormsg = "\n" + ds.Message;
                        ds       = null;//making it null so that we stop executing further

                        // errormsg = BSky.GlobalResources.Properties.Resources.OpenRScriptInSynWin + "\n"+
                        //     BSky.GlobalResources.Properties.Resources.OpenRScriptMenuPath;
                        // ds = null;
                    }

                    if (ds != null && ds.Variables.Count > 0)//07Aug2016 added count condition to not open dataset if there are no variables //03Dec2012
                    {
                        logService.WriteToLogLevel("Start Loading: " + ds.Name, LogLevelEnum.Info);
                        //controller.LoadNewDataSet(ds);

                        stopwatch = System.Diagnostics.Stopwatch.StartNew();

                        if (ds.Replace)//if dataset became NULL(dataset exists in UI grid) and now we want to replace it by reading data from file
                        {
                            controller.RefreshBothGrids(ds);
                        }
                        else
                        {
                            controller.LoadNewDataSet(ds);
                        }
                        stopwatch.Stop();
                        elapsed = stopwatch.ElapsedMilliseconds;
                        if (AdvancedLogging)
                        {
                            logService.WriteToLogLevel("PERFORMANCE:Creating virtual-Class and grid stuff: Time taken: " + elapsed, LogLevelEnum.Info);
                        }

                        logService.WriteToLogLevel("Finished Loading: " + ds.Name, LogLevelEnum.Info);
                        recentfiles.AddXMLItem(filename);//adding to XML file for recent docs
                        ActivateDatagrid(ds);
                    }
                    else
                    {
                        BSkyMouseBusyHandler.HideMouseBusy();// HideProgressbar_old();

                        //Following block is not needed
                        //StringBuilder sb = new StringBuilder();
                        //List<string> defpacklist = defaultpackges.RecentFileList;
                        //foreach(string s in defpacklist)
                        //{
                        //    sb.Append(s+", ");
                        //}
                        //sb.Remove(sb.Length - 1, 1);//removing last comma
                        //string defpkgs = sb.ToString();

                        //MessageBox.Show(errormsg, "Unable to open the file(" + filename + ")", MessageBoxButton.OK, MessageBoxImage.Warning);
                        //SendToOutputWindow("Error Opening Dataset", filename + errormsg);

                        MessageBox.Show(errormsg, BSky.GlobalResources.Properties.Resources.ErrOpeningFile + "(" + filename + ")", MessageBoxButton.OK, MessageBoxImage.Warning);
                        SendToOutputWindow(BSky.GlobalResources.Properties.Resources.ErrOpeningDataset, filename + errormsg);
                    }
                }
                else
                {
                    BSkyMouseBusyHandler.HideMouseBusy();// HideProgressbar_old();
                    MessageBox.Show(filename + " " + BSky.GlobalResources.Properties.Resources.DoesNotExist,
                                    BSky.GlobalResources.Properties.Resources.FileNotFound, MessageBoxButton.OK, MessageBoxImage.Warning);
                    //If file does not exist. It should be removed from the recent files list.
                    recentfiles.RemoveXMLItem(filename);
                }
                //18OCt2013 move up for using in msg box   Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
                appwindow.RefreshRecent();
            }
            BSkyMouseBusyHandler.HideMouseBusy();// HideProgressbar_old();// HideStatusProgressbar();//29Oct2014

            //08Apr2015 bring main window in front after file open, instead of output window
            Window1 window = LifetimeService.Instance.Container.Resolve <Window1>();
            window.Activate();
        }
Ejemplo n.º 4
0
        ////Send executed command to output window. So, user will know what he executed
        //protected override void SendToOutputWindow(string command, string title)//13Dec2013
        //{
        //    #region Get Active output Window
        //    //////// Active output window ///////
        //    OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
        //    OutputWindow ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
        //    #endregion
        //    ow.AddMessage(command, title);
        //}

        public bool OpenDataframe(string dframename)
        {
            initGlobalObjects();
            if (!AreDefaultRPackagesLoaded())
            {
                return(false);
            }
            BSkyMouseBusyHandler.ShowMouseBusy();//ShowProgressbar_old();//ShowStatusProgressbar();//29Oct2014
            bool isSuccess = false;


            string filename = controller.GetActiveDocument().FileName;
            //For Excel
            string sheetname = controller.GetActiveDocument().SheetName;

            if (sheetname == null)
            {
                sheetname = string.Empty;
            }
            // if dataset was already loaded last time then this time we want to refresh it
            bool isDatasetNew = service.isDatasetNew(dframename + sheetname);

            try
            {
                DataSource ds       = service.OpenDataframe(dframename, sheetname);
                string     errormsg = string.Empty;
                if (ds != null && ds.Message != null && ds.Message.Length > 0) //message that is related to error
                {
                    errormsg = "\n" + ds.Message;
                    ds       = null; //making it null so that we do execute further
                }
                if (ds != null)      //03Dec2012
                {
                    logService.WriteToLogLevel("Start Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                    if (isDatasetNew)
                    {
                        controller.Load_Dataframe(ds);
                    }
                    else
                    {
                        controller.RefreshBothGrids(ds); //23Jul2015 .RefreshGrids(ds);//.RefreshDataSet(ds);
                    }
                    ds.Changed = true;                   // keep track of change made, so that it can prompt for saving while closing dataset tab.
                    logService.WriteToLogLevel("Finished Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                    //recentfiles.AddXMLItem(dframename);//adding to XML file for recent docs
                    isSuccess = true;
                }
                else
                {
                    BSkyMouseBusyHandler.HideMouseBusy();//HideProgressbar_old();
                    MessageBox.Show(appwindow, BSky.GlobalResources.Properties.Resources.cantopen + " '" + dframename + "'" +
                                    "\n" + BSky.GlobalResources.Properties.Resources.reasonsAre +
                                    "\n" + BSky.GlobalResources.Properties.Resources.NotDataframe2 +
                                    "\n" + BSky.GlobalResources.Properties.Resources.FormatNotSupported2 +
                                    "\n" + BSky.GlobalResources.Properties.Resources.NoRowsColsPresent +
                                    "\n" + BSky.GlobalResources.Properties.Resources.OldSessionRunning2 +
                                    "\n" + BSky.GlobalResources.Properties.Resources.RSideIssue2,
                                    BSky.GlobalResources.Properties.Resources.warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                    SendToOutputWindow(BSky.GlobalResources.Properties.Resources.ErrOpeningDataset2, dframename + errormsg);
                }
            }
            catch (Exception ex)
            {
                logService.WriteToLogLevel("Error:" + ex.Message, LogLevelEnum.Error);
            }
            finally
            {
                //18OCt2013 move up for using in msg box   Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
                //appwindow.RefreshRecent();
                BSkyMouseBusyHandler.HideMouseBusy();//HideProgressbar_old();//HideStatusProgressbar();//29Oct2014
            }

            //if (isSuccess)
            //{
            //08Apr2015 bring main window in front after file open, instead of output window
            //Window1 window = LifetimeService.Instance.Container.Resolve<Window1>();
            //window.Activate();
            //}
            return(isSuccess);
        }
Ejemplo n.º 5
0
        //This is to finally execute a query that will return a data frame that will be loaded in a grid.
        private bool ExecuteQuery(string query, string dframename)
        {
            //Get table using custom query
            DataFrame alltablesDF = null;
            //Get list of Tables in a database.
            string command = null;// "GetDataframe(" + ConnectionString + ", databasename ='" + SelectedDatabase + "', '" + query + "','" + dframename + "')";

            if (ServerType.Equals("MS-ACCESS"))
            {
                command = "GetDataframe(" + ConnectionString + ", query= '" + query + "', datasetname='" + dframename + "')";
            }
            else
            {
                command = "GetDataframe(" + ConnectionString + ", databasename ='" + SelectedDatabase + "', query= '" + query + "', datasetname='" + dframename + "')";
            }
            //object alltables = service.ImportTableListFromSQL(command);


            UAReturn uaret = service.ImportTableListFromSQL(command);

            OutputHelper.AnalyticsData.Result = uaret;//putting DOM

            //A table is always returned with single bool value that shows whether Dataset
            //creation in R memory was success or not
            bool[] visibleRows;
            int    datanumber     = 1;                             // there is just one table that we are intrested in. Its first table in  /Root/UATableList
            bool   isDatasetReady = false;
            int    backup         = OutputHelper.FlexGridMaxCells; //backup current value

            OutputHelper.FlexGridMaxCells = 1000;                  //change to required value
            string[,] datasetReady        = OutputHelper.GetDataMatrix(datanumber, out visibleRows);
            OutputHelper.FlexGridMaxCells = backup;                //restore original value back again;
            if (datasetReady != null)
            {
                isDatasetReady = datasetReady[0, 0].ToLower().Equals("true") ? true : false;
            }
            //// Now fetching errors if any
            string[,] ew = OutputHelper.GetBSkyErrorsWarning(0, "normal");//0 for automatically finding the tablenumber
            if (ew != null)
            {
                StringBuilder errmsg = new StringBuilder();
                int           rcount = ew.GetLength(0);
                int           ccount = ew.GetLength(1);
                for (int r = 0; r < rcount; r++)
                {
                    for (int c = 0; c < ccount; c++)
                    {
                        errmsg.Append(ew[r, c] + "\n");
                    }
                }

                MessageBox.Show(errmsg.ToString(), "Errors/Warnings:", MessageBoxButton.OK, MessageBoxImage.Error);
                HideProgressbar();
            }

            if (!isDatasetReady) // if dataset was not created in R memory due to wrong query or other reasons.
            {
                return(false);
            }


            DataSource ds        = service.OpenDataframe(dframename, "");
            bool       isSuccess = false;
            string     errormsg  = string.Empty;

            if (ds != null && ds.Message != null && ds.Message.Length > 0) //message that is related to error
            {
                errormsg = "\n" + ds.Message;
                ds       = null;          //making it null so that we do execute further
            }
            if (ds != null)               //03Dec2012
            {
                bool isDatasetNew = true; // service.isDatasetNew(dframename + "");
                logService.WriteToLogLevel("Start Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                if (isDatasetNew)
                {
                    controller.Load_Dataframe(ds);
                }
                else
                {
                    controller.RefreshBothGrids(ds); //23Jul2015 .RefreshGrids(ds);//.RefreshDataSet(ds);
                }
                ds.Changed = true;                   // keep track of change made, so that it can prompt for saving while closing dataset tab.
                logService.WriteToLogLevel("Finished Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                //recentfiles.AddXMLItem(dframename);//adding to XML file for recent docs
                isSuccess = true;
            }
            else
            {
                HideProgressbar();
                MessageBox.Show("Unable to open SQL dataframe'" + dframename + "'..." +
                                "\nReasons could be one or more of the following:" +
                                "\n1. Not a data frame object." +
                                "\n2. File format not supported (or corrupt file or duplicate column names)." +
                                "\n3. Dataframe does not have row(s) or column(s)." +
                                "\n4. R.Net server from the old session still running (use task manager to kill it)." +
                                "\n5. Some issue on R side (like: required library not loaded, incorrect syntax)." +
                                "\n6. Incorrect values provided while connecting to the SQL server.",
                                "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                //SendToOutputWindow("Error Opening Dataset.(probably not a data frame)", dframename + errormsg);
            }

            HideProgressbar();
            return(true);
        }
Ejemplo n.º 6
0
        ////Send executed command to output window. So, user will know what he executed
        //protected override void SendToOutputWindow(string command, string title)//13Dec2013
        //{
        //    #region Get Active output Window
        //    //////// Active output window ///////
        //    OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
        //    OutputWindow ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
        //    #endregion
        //    ow.AddMessage(command, title);
        //}

        public bool OpenDataframe(string dframename)
        {
            ShowProgressbar();//ShowStatusProgressbar();//29Oct2014
            bool            isSuccess  = false;
            IUnityContainer container  = LifetimeService.Instance.Container;
            IDataService    service    = container.Resolve <IDataService>();
            IUIController   controller = container.Resolve <IUIController>();
            Window1         appwindow  = LifetimeService.Instance.Container.Resolve <Window1>();//for refeshing recent files list

            string filename = controller.GetActiveDocument().FileName;
            //For Excel
            string sheetname = controller.GetActiveDocument().SheetName;

            if (sheetname == null)
            {
                sheetname = string.Empty;
            }
            // if dataset was already loaded last time then this time we want to refresh it
            bool isDatasetNew = service.isDatasetNew(dframename + sheetname);

            try
            {
                DataSource ds       = service.OpenDataframe(dframename, sheetname);
                string     errormsg = string.Empty;
                if (ds != null && ds.Message != null && ds.Message.Length > 0) //message that is related to error
                {
                    errormsg = "\n" + ds.Message;
                    ds       = null; //making it null so that we do execute further
                }
                if (ds != null)      //03Dec2012
                {
                    logService.WriteToLogLevel("Start Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                    if (isDatasetNew)
                    {
                        controller.Load_Dataframe(ds);
                    }
                    else
                    {
                        controller.RefreshBothGrids(ds); //23Jul2015 .RefreshGrids(ds);//.RefreshDataSet(ds);
                    }
                    ds.Changed = true;                   // keep track of change made, so that it can prompt for saving while closing dataset tab.
                    logService.WriteToLogLevel("Finished Loading Dataframe: " + ds.Name, LogLevelEnum.Info);
                    //recentfiles.AddXMLItem(dframename);//adding to XML file for recent docs
                    isSuccess = true;
                }
                else
                {
                    HideProgressbar();
                    MessageBox.Show(appwindow, "Unable to open '" + dframename + "'..." +
                                    "\nReasons could be one or more of the following:" +
                                    "\n1. Not a data frame object." +
                                    "\n2. File format not supported (or corrupt file or duplicate column names)." +
                                    "\n3. R.Net server from the old session still running (use task manager to kill it)." +
                                    "\n4. Some issue on R side (like: required library not loaded, incorrect syntax).",
                                    "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    SendToOutputWindow("Error Opening Dataset.(probably not a data frame)", dframename + errormsg);
                }
            }
            catch (Exception ex)
            {
                logService.WriteToLogLevel("Error:" + ex.Message, LogLevelEnum.Error);
            }
            finally
            {
                //18OCt2013 move up for using in msg box   Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
                //appwindow.RefreshRecent();
                HideProgressbar();//HideStatusProgressbar();//29Oct2014
            }

            //if (isSuccess)
            //{
            //08Apr2015 bring main window in front after file open, instead of output window
            //Window1 window = LifetimeService.Instance.Container.Resolve<Window1>();
            //window.Activate();
            //}
            return(isSuccess);
        }