//Add executed command per Dataset
        public void AddCommand(string DatasetName, UAMenuCommand Command)
        {
            //Creating a copy of command for putting it in "History" menu
            UAMenuCommand uamc = new UAMenuCommand(); // new obj needed, because same obj can't be child at two places.
            uamc.commandformat = Command.commandformat;
            uamc.commandoutputformat = Command.commandoutputformat; 
            uamc.commandtemplate = Command.commandtemplate;
            uamc.commandtype = Command.commandtype;
            //29Mar2013 //If History Menu text is not present. Dont add this command to "History" menu
            if(Command.text == null || Command.text.Length < 1)
            { return; }
            uamc.text = Command.text;//Command name shown in "History" menu

            //now create menuitem for each command and add to "History" menu
            DashBoardItem item = new DashBoardItem();
            item.Command = new AUAnalysisCommandBase(); // should point to AUAnalysisCommandBase
            item.CommandParameter = uamc;
            item.isGroup = false;
            item.Name = uamc.text;// MenuName
            MenuItem newmi = CreateItem(item);

            //Check if command already in history menu ///
            bool ExistsInHistory = false;
            int miIndex = 0;
            foreach (MenuItem mi in commandhistmenu.Items)
            {
                if (mi.Header == newmi.Header)//command already in History
                {
                    ExistsInHistory = true;
                    break;
                }
                miIndex++;
            }

            // Adding command with "latest executed on top" in menu ///
            if (ExistsInHistory)
            {
                commandhistmenu.Items.RemoveAt(miIndex);
            }
            commandhistmenu.Items.Insert(0, newmi);//Adding to "History" menu
        }
        //remove executed command per Dataset
        public void RemoveCommand(string DatasetName, UAMenuCommand Command)
        {
            //Check if command already in history menu ///
            bool ExistsInHistory = false;
            int miIndex = 0;
            foreach (MenuItem mi in commandhistmenu.Items)
            {
                if (mi.Header.ToString() == Command.text)//command already in History
                {
                    ExistsInHistory = true;
                    break;
                }
                miIndex++;
            }

            // Adding command with "latest executed on top" in menu ///
            if (ExistsInHistory)
            {
                commandhistmenu.Items.RemoveAt(miIndex);
            }
        }
 //16Jul2015 refesh both grids when 'refresh' icon is clicked in output window
 public void RefreshBothgrids()//16Jul2015
 {
     string stmt = "Refresh Grids";
     UAMenuCommand uamc = new UAMenuCommand();
     uamc.commandformat = stmt;
     uamc.bskycommand = stmt;
     uamc.commandtype = stmt;
     CommandExecutionHelper auacb = new CommandExecutionHelper();
     auacb.BothGridRefreshAndPrintTitle("Refresh Data");
 }
        //For Painting Output window for BSKyFormated object. And/Or to refresh datagrid for non-analytics commands like sort, compute
        private void RefreshOutputORDataset(string objectname, CommandRequest cmd, string originalCommand, OutputWindow ow)
        {
            UAMenuCommand uamc = new UAMenuCommand();
            cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
            // is it just a list(non Bsky) or its a list that contains tables (user tables or Bsky Stat result tables)
            bool isNonBSkyList = false;
            object isNonBSkyListstr = analytics.ExecuteR(cmd, true, false);
            if (isNonBSkyListstr != null && isNonBSkyListstr.ToString().ToLower().Equals("true"))
            {
                isNonBSkyList = true;
            }
            if (isNonBSkyList)
            {
                string ewmessage = "This Object cannot be formatted using BSKyFormat. BSkyFormat can be used on Array, Matrix, Data Frame and BSky List objects only.";
                SendErrorToOutput(ewmessage, ow);//03Jul2013
                return;
            }
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $BSkySplit Result (false means non-bsky list): " + isNonBSkyList, LogLevelEnum.Info);

            cmd.CommandSyntax = objectname + "$uasummary[[7]]";
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);

            string bskyfunctioncall = (string)analytics.ExecuteR(cmd, true, false);//actual call with values
            if (bskyfunctioncall == null)
            {
                bskyfunctioncall = ""; //24Apr2014 This is when no Dataset is open. And Syntax editor is open.Not returning, instead putting blank.
            }
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $uasummary[[7]] Result : " + bskyfunctioncall, LogLevelEnum.Info);
            string bskyfunctionname = "";
            if (bskyfunctioncall.Length > 0)
            {
                if (bskyfunctioncall.Contains("("))
                    bskyfunctionname = bskyfunctioncall.Substring(0, bskyfunctioncall.IndexOf('(')).Trim();
                else
                    bskyfunctionname = bskyfunctioncall;
            }
            uamc.commandformat = objectname;// object that stores the result of analysis
            uamc.bskycommand = bskyfunctioncall.Replace('\"', '\'');// actual BSkyFunction call. " quotes replaced by '
            uamc.commandoutputformat = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyDataDirConfigBkSlash) + bskyfunctionname + ".xml" : "";//23Apr2015 
            uamc.commandtemplate = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyDataDirConfigBkSlash) + bskyfunctionname + ".xaml" : "";//23Apr2015 

            uamc.commandtype = originalCommand;
            CommandExecutionHelper auacb = new CommandExecutionHelper();
            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: CommandExecutionHelper: " , LogLevelEnum.Info);
            auacb.ExecuteSyntaxEditor(uamc, saveoutput.IsChecked == true ? true : false);//10JAn2013 edit
            auacb = null;

        }
        private void ExecuteOtherCommand(OutputWindow ow, string stmt)
        {

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Before Executing in R.", LogLevelEnum.Info);


            #region Check open close brackets before executing
            string unbalmsg;
            if (!AreBracketsBalanced(stmt, out unbalmsg))//if unbalanced brackets
            {
                CommandRequest errmsg = new CommandRequest();
                string fullmsg = "Error : " + unbalmsg;
                errmsg.CommandSyntax = "write(\"" + fullmsg.Replace("<", "&lt;").Replace('"', '\'') + "\",fp)";//
                analytics.ExecuteR(errmsg, false, false); //for printing command in file
                return;
            }
            #endregion
            ///if command is for loading dataset //
            if (stmt.Contains("UAloadDataset"))
            {
                int indexofopening = stmt.IndexOf('(');
                int indexofclosing = stmt.IndexOf(')');
                string[] parameters = stmt.Substring(indexofopening + 1, indexofclosing - indexofopening - 2).Split(',');
                string filename = string.Empty;
                foreach (string s in parameters)
                {
                    if (s.Contains('/') || s.Contains('\\'))
                        filename = s.Replace('\"', ' ').Replace('\'', ' ');
                }
                if (filename.Contains("="))
                {
                    filename = filename.Substring(filename.IndexOf("=") + 1);
                }
                FileOpenCommand fo = new FileOpenCommand();
                fo.FileOpen(filename.Trim());
                return;
            }

            object o = null;
            CommandRequest cmd = new CommandRequest();

            if (stmt.Contains("BSkySortDataframe(") ||
                stmt.Contains("BSkyComputeExpression(") || stmt.Contains("BSkyRecode("))
            {
                CommandExecutionHelper auacb = new CommandExecutionHelper();
                UAMenuCommand uamc = new UAMenuCommand();
                uamc.bskycommand = stmt;
                uamc.commandtype = stmt;
                auacb.ExeuteSingleCommandWithtoutXML(stmt);//auacb.ExecuteSynEdtrNonAnalysis(uamc);
                auacb.Refresh_Statusbar();
                //auacb = null;
            }
            else
            {

                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing in R.", LogLevelEnum.Info);

 
                 isVariable(ref stmt);///for checking if its variable then it must be enclosed within print();
                                      
                //27May2015 check if command is graphic and get its height width and then reopen graphic device with new dimensions
                 if (lastcommandwasgraphic)//listed graphic
                 {
                     if (imgDim!=null && imgDim.overrideImgDim)
                     {
                         CloseGraphicsDevice();
                         OpenGraphicsDevice(imgDim.imagewidth, imgDim.imageheight); // get image dimenstion from external source for this particular graphic.
                     }
                 }


                cmd.CommandSyntax = stmt;// command 
                o = analytics.ExecuteR(cmd, false, false);   //// get Direct Result and write in sink file

                CommandRequest cmdprn = new CommandRequest();
                if (o != null && o.ToString().Contains("Error"))//for writing some of the errors those are not taken care by sink.
                {
                    cmdprn.CommandSyntax = "write(\"" + o.ToString() + "\",fp)";// http://www.w3schools.com/xml/xml_syntax.asp
                    o = analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
                    
                    ///if there is error in assignment, like RHS caused error and LHS var is never updated
                    ///Better make LHS var null.
                    string lhvar = string.Empty;
                    GetLeftHandVar(stmt, out lhvar);
                    if (lhvar != null)
                    {
                        cmd.CommandSyntax = lhvar+" <- NULL";// assign null 
                        o = analytics.ExecuteR(cmd, false, false);
                    }
                }
            }

            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: After Executing in R.", LogLevelEnum.Info);

            
        }
        private void ExecuteXMLTemplateDefinedCommands(string stmt)//10Jul2014
        {
            CommandRequest xmlgrpcmd = new CommandRequest();

            xmlgrpcmd.CommandSyntax = stmt;
            //o = analytics.ExecuteR(xmlgrpcmd, false, false);

            UAMenuCommand uamc = new UAMenuCommand();
            uamc.bskycommand = stmt;
            uamc.commandtype = stmt;
            CommandExecutionHelper auacb = new CommandExecutionHelper();
            auacb.MenuParameter = menuParameter;
            auacb.RetVal = analytics.Execute(xmlgrpcmd);
            auacb.ExecuteXMLDefinedDialog(stmt);
        }
        private void ExecuteSplit(string stmt)
        {
            //object o = null;
            CommandRequest cmd = new CommandRequest();

            CommandExecutionHelper ceh = new CommandExecutionHelper();
            UAMenuCommand uamc = new UAMenuCommand();
            uamc.bskycommand = stmt;
            uamc.commandtype = stmt;
            cmd.CommandSyntax = stmt;
            ceh.ExecuteSplit(stmt, FElement);
            ceh = null;
        }
        private ICommand CreateCommand(UAMenuCommand cmd)
        {
            Type commandTypeObject = null;
            ICommand command = null;

            try
            {
                commandTypeObject = Type.GetType(cmd.commandtype);
                command = (ICommand)Activator.CreateInstance(commandTypeObject);
            }
            catch
            {
                    //Create new command instance using default command dispatcher
                logService.WriteToLogLevel("Could not create command. "+cmd.commandformat, LogLevelEnum.Error);
            }

            return command;
        }
        private DashBoardItem CreateItem(XmlNode node)
        {
            DashBoardItem item = new DashBoardItem();

            item.Name = GetAttributeString(node, "text");
            item.isGroup = node.HasChildNodes;

            if (node.HasChildNodes)
            {
                item.Items = new List<DashBoardItem>();
                foreach (XmlNode child in node.ChildNodes)
                    item.Items.Add(CreateItem(child));
            }
            else
            {
                UAMenuCommand cmd = new UAMenuCommand();
                cmd.commandtype = GetAttributeString(node, "command");
                if (string.IsNullOrEmpty(cmd.commandtype))
                {
                    cmd.commandtype = typeof(AUAnalysisCommandBase).FullName;
                }
                cmd.commandtemplate = GetAttributeString(node, "commandtemplate");
                cmd.commandformat = GetAttributeString(node, "commandformat");
                cmd.commandoutputformat = GetAttributeString(node, "commandoutputformat");
                cmd.text = GetAttributeString(node, "text"); //04mar2013
                //cmd.id = GetAttributeString(node, "id"); //04mar2013
                //cmd.owner = GetAttributeString(node, "owner"); //04mar2013
                item.Command = CreateCommand(cmd);
                item.CommandParameter = cmd;

                #region 11Jun2015 Set icon fullpathfilename 
                item.iconfullpathfilename = GetAttributeString(node, "icon");
                string showicon = GetAttributeString(node, "showtoolbaricon"); 
                if(showicon==null || showicon.Trim().Length == 0 || !showicon.ToLower().Equals("true"))
                {
                    item.showshortcuticon = false;
                }
                else
                {
                    item.showshortcuticon = true;
                }
                #endregion
            }
            return item;
        }
        //// Adding new output windows ////
        public void AddOutputMenuItem(string outwindowname)
        {
            DashBoardItem item = new DashBoardItem();
            item.Command = new SelectOutputWindowCommand();

            UAMenuCommand uamc = new UAMenuCommand(); //01Aug2012. There was no 'new' before
            uamc.commandformat = outwindowname;//window name is key. Action shud b taken on this.
            uamc.commandoutputformat = ""; uamc.commandtemplate = ""; uamc.commandtype = "";
            item.CommandParameter = uamc;

            item.isGroup = false;
            item.Name = outwindowname;//this should also be the key

            foreach (MenuItem output_menu in allOutputMenus)
            {
                if (output_menu.Header.ToString() == "Output")
                {
                    output_menu.Items.Add(CreateItem(item));
                }
            }
            CheckOutputMenuItem(outwindowname);//putting a check or alphabet to show which one is active
        }
        /// <summary>
        /// Creating clone of Output menu from App's main window. The section that shows names of each output window in current session.
        /// </summary>
        private void CreateClone()//List<DashBoardItem> di)
        {
            MenuItem output_menu=null;
            if (allOutputMenus.Count > 0)
                output_menu = allOutputMenus[0];//grab the first menu.(this should be from Apps main window)

                if (output_menu.Header.ToString() == "Output")
                {
                    foreach (MenuItem mi in output_menu.Items)/// windownames
                    {
                        /// default items are already being created ///
                        if (mi.Header.ToString().Equals("New Output Window") ||
                            mi.Header.ToString().Equals("Open Output") ||
                            mi.Header.ToString().Equals("Save Output") ||
                            mi.Header.GetType() == typeof(Separator))
                            continue;
                        //////creating clone////
                        DashBoardItem item = new DashBoardItem();
                        item.Command = new SelectOutputWindowCommand();

                        UAMenuCommand uamc = new UAMenuCommand(); //01Aug2012. There was no 'new' before
                        uamc.commandformat = mi.Header.ToString();//window name is key. Action shud b taken on this.
                        uamc.commandoutputformat = ""; uamc.commandtemplate = ""; uamc.commandtype = "";
                        item.CommandParameter = uamc;

                        item.isGroup = false;
                        item.Name = mi.Header.ToString();//this should also be the key
                        MenuItem createdmi = CreateItem(item);
                        createdmi.Icon = mi.Icon;

                        outputmenu.Items.Add(createdmi);
                    }
                }
        }