public void ExecuteSplit(string command = null, FrameworkElement fe = null)
        {
            CommandRequest cr = new CommandRequest();

            cr.CommandSyntax = command;
            string stmt = command;                       //cmd.CommandSyntax;

            if (stmt.Contains("BSkySetDataFrameSplit(")) ///executes when SPLIT is fired from menu
            {
                bool setsplit = false;
                int  startind = 0; int endind = 0;
                if (stmt.Contains("col.names"))
                {
                    startind = stmt.IndexOf("c(", stmt.IndexOf("col.names"));// index of c(
                }
                else
                {
                    startind = stmt.IndexOf("c(");// index of c(
                }
                if (startind > 0)
                {
                    endind = stmt.IndexOf(")", startind);
                }
                if (startind > 0 && endind > startind)
                {
                    int    len = endind - startind + 1;         // finding the length of  c(......)
                    string str = stmt.Substring(startind, len); // this will contain c('tg0','tg1') or just c()
                    string ch  = null;
                    if (str.Contains("'"))
                    {
                        ch = "'";
                    }
                    if (str.Contains('"'))
                    {
                        ch = "\"";
                    }
                    if (ch != null && ch.Length > 0)
                    {
                        int i = str.IndexOf(ch);
                        int j = -1;
                        if (i >= 0)
                        {
                            j = str.IndexOf(ch, i + 1);
                        }
                        if (j < 0)
                        {
                            j = i + 1;
                        }
                        string sub = str.Substring(i + 1, (j - i - 1)).Trim();
                        if (i < 0)
                        {
                            i = str.IndexOf("'");
                        }
                        if (i >= 0)
                        {
                            if (sub.Length > 0)
                            {
                                setsplit = true;
                            }
                        }
                    }
                }
                //Executing the command in R///
                analytics.ExecuteR(cr, false, false);

                ////Creating a command output////11Jul2014

                CommandOutput splitCo = new CommandOutput();
                splitCo.NameOfAnalysis     = "Split:#" + setsplit;
                splitCo.IsFromSyntaxEditor = false;

                AUParagraph aup = new AUParagraph();
                aup.FontSize    = BSkyStyler.BSkyConstants.TEXT_FONTSIZE; //App.HEADER_FONTSIZE;
                aup.Text        = stmt;
                aup.ControlType = "Header";                               // treenodename.Length < treenodecharlen ? treenodename : treenodename.Substring(0, treenodecharlen);
                splitCo.Add(aup);

                //////////  Setting/Unsetting Macro  for SPLIT //////////
                if (setsplit)
                {
                    OutputHelper.AddGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name), fe);
                    //window.Template = null; //11Mar2013 release the XAML object. ie obj is no more child of window.
                    AddToSyntaxSession(splitCo); //11Jul2014 SendToOutputWindow(dialogTitle, stmt);
                    Refresh_Statusbar();         // RefreshGrids();
                    return;                      // no need to do any thing further
                }
                else // unset split
                {
                    OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                    //if (window != null && window.Template != null)
                    //    window.Template = null; //11Mar2013 release the XAML object. ie obj is no more child of window.
                    AddToSyntaxSession(splitCo); //11Jul2014 SendToOutputWindow(dialogTitle, stmt);
                    Refresh_Statusbar();         // RefreshGrids();
                    return;                      // no need to do any thing further
                }
            }
        }
        //For commands : Dialog may or may not be shown but surely XML template is not present.
        public void ExeuteSingleCommandWithtoutXML(string command = "")
        {
            if (command != null && command.Length > 0)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = command;
            }
            if (cmd.CommandSyntax == null || cmd.CommandSyntax.Length < 1)
            {
                cmd = new CommandRequest();
                cmd.CommandSyntax = "print('No command to execute')";
            }

            if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))// if its relaod dataset commmand then prepare some parameter before executing the command
            {
                DataSource tempds   = UIController.GetActiveDocument();
                string     filename = tempds.FileName.Replace("\\", "/");
                string     filetype = tempds.FileType;
                string     temp     = new string(cmd.CommandSyntax.ToCharArray());

                cmd.CommandSyntax = temp.Replace("fullpathfilename", "fullpathfilename='" + filename + "'").Replace("filetype", "filetype='" + filetype + "'");;

                //Restting split if all data and attributes are loaded
                int    idx       = temp.IndexOf("=", temp.IndexOf("loaddataonly")); // index of  '=' after 'loaddataonly'
                int    idxcomma  = temp.IndexOf(",", temp.IndexOf("loaddataonly")); // index of  ',' after 'loaddataonly'
                string boolvalue = temp.Substring(idx + 1, idxcomma - idx - 1).Trim();
                if (boolvalue.Equals("FALSE"))                                      //loaddataonly = false then we need to reset SPLIT in C# also
                {
                    OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                }
            }
            //retval = analytics.Execute(cmd);
            if (bdt != null)
            {
                if (!bdt.IsBatchCommand && bdt.IsCommandOnly && !bdt.IsXMLDefined && !cmd.CommandSyntax.Contains("BSkySetDataFrameSplit("))
                {
                    SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                    ExecuteInSyntaxEditor(true, dialogTitle);//GenerateOutputTablesForNonXAML(null);// ExecuteXMLDefinedDialog();
                }
            }

            if (cmd.CommandSyntax.Contains("BSkySortDataframe(") || cmd.CommandSyntax.Contains("BSkyComputeExpression(") ||
                cmd.CommandSyntax.Contains("BSkyRecode("))
            {
                retval = analytics.Execute(cmd);
                OutputHelper.AnalyticsData.Result = retval;                    //putting latest DOM
                string[,] ew = OutputHelper.GetBSkyErrorsWarning(1, "normal"); //08Nov2014

                if (cmd.CommandSyntax.Contains("BSkySortDataframe"))           //11Apr2014 putting sort icon
                {
                    //single column logic
                    //int startidx = cmd.CommandSyntax.IndexOf("'");
                    //int endidx= cmd.CommandSyntax.IndexOf("'", startidx+1);
                    //int leng = endidx - startidx-1;
                    //string colname = cmd.CommandSyntax.Substring(startidx+1, leng);

                    //sort order 14Apr2014
                    string srtodr = string.Empty;
                    // descending=TRUE in command. There is just 1 boolean in sort so this 'if' will work
                    if (cmd.CommandSyntax.Contains("TRUE"))
                    {
                        srtodr = "desc";
                    }
                    else
                    {
                        srtodr = "asc";
                    }

                    //mulitiple col logic
                    List <string> collst   = new List <string>();
                    int           startidx = cmd.CommandSyntax.IndexOf("c(");
                    if (startidx == -1) //no items in target listbox. No need of this if sort dialog has OK disabled when no items in target
                    {
                        return;
                    }
                    int      endidx  = cmd.CommandSyntax.IndexOf(")", startidx + 1);
                    int      leng    = endidx - startidx - 1;
                    string   selcols = cmd.CommandSyntax.Substring(startidx + 2, leng - 1).Replace("'", ""); // +2 is the length of "c(", -1 for )
                    string[] cols    = selcols.Split(',');
                    for (int j = 0; j < cols.Length; j++)                                                    //string s in cols)
                    {
                        collst.Add(cols[j]);
                    }
                    RefreshGrids(collst, srtodr);
                }
                else
                {
                    //testing something. If success, we dont need this. RefreshGrids();
                }

                //16Apr2014
                //must be excuted at the end after data is reloaded otherwise split is not refresh in statusbar.
                if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))
                {
                    Refresh_Statusbar();
                }

                ////Finally show messages in output
                //SendToOutputWindow(dialogTitle, cmd.CommandSyntax);
                //Show errors if any 08Nov2014
                if (ew != null && ew[0, 0] != null)
                {
                    //SendToOutputWindow("", ew[0, 2]);
                    CommandOutput ewmsg = new CommandOutput();
                    ewmsg.NameOfAnalysis     = "Errors/Warnings";
                    ewmsg.IsFromSyntaxEditor = false;

                    AUParagraph ewtypeaup = new AUParagraph();
                    ewtypeaup.FontSize    = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    ewtypeaup.Text        = (ew[0, 0] != null)?ew[0, 0]:"no type info";
                    ewtypeaup.ControlType = "Type:";
                    ewmsg.Add(ewtypeaup);

                    AUParagraph usrmsgaup = new AUParagraph();
                    usrmsgaup.FontSize    = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    usrmsgaup.Text        = (ew[0, 1] != null) ? ew[0, 1] : "no user message info";
                    usrmsgaup.ControlType = "User Message:";
                    ewmsg.Add(usrmsgaup);

                    AUParagraph rmsgaup = new AUParagraph();
                    rmsgaup.FontSize    = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//App.TEXT_FONTSIZE;
                    rmsgaup.Text        = (ew[0, 2] != null) ? ew[0, 2] : "no R message info";
                    rmsgaup.ControlType = "R Message:";
                    ewmsg.Add(rmsgaup);

                    AddToSyntaxSession(ewmsg);
                }
            }
        }
        ////// For Analysis Command Execution from Syntax Editor /////
        public void ExecuteSyntaxEditor3(object param, bool selectedForDump)
        {
            parameter = param;
            OnPreExecute(parameter);
            if (!canExecute)
            {
                return;
            }
            object obj = null;
            string dialogcommandstr = null;

            try
            {
                //here TemplateFileName xaml will have same name as the analysis command function name
                // say- function called frm SynEdtr was 'bsky.my.func()' then in bin\Config\ 
                // dialog xaml, 'bsky.my.func.xaml' and
                // output template file 'bsky.my.func.xml' must exist
                // ie.. func name = xaml name = xml name
                XmlReader xmlr = XmlReader.Create(TemplateFileName);
                xmlr.ReadToFollowing("BSkyCanvas");
                xmlr.MoveToAttribute("CommandString");
                dialogcommandstr = xmlr.Value.Replace(" ", string.Empty).Replace('\"', '\'');
                xmlr.Close();
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                return;
            }
            element             = obj as FrameworkElement;
            window              = new BaseOptionWindow();
            window.Template     = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;
            ////////////test///////
            //// take two strings and then try to make merged dictionary. remove extra spaces. replace " with '
            //string bksytemplate="bsky.CrossTable(x=c({Rows}),y=c({columns}),layers=c({layers}),datasetname='{%DATASET%}',chisq={chisq})";
            //string bskycommand="bsky.CrossTable(x=c('store','contact'),y='regular',layers=c('gender'),datasetname='Dataset1',chisq=FALSE)";
            //string dialogcommandstr = "bsky.one.sm.t.test(vars=c({SelectedVars}),mu={testValue},conf.level=0.89,datasetname='{%DATASET%}',missing=0)";
            string bskycommand = ((UAMenuCommand)parameter).bskycommand.Replace(" ", string.Empty); //"bsky.one.sm.t.test(vars=c('tg0','tg2','tg3'),mu=30,conf.level=0.89,datasetname='Dataset1',missing=0)";

            Dictionary <string, string> dialogkeyvalpair      = new Dictionary <string, string>();  //like: key=mu, val= {testValue}
            Dictionary <string, string> bskycommandkeyvalpair = new Dictionary <string, string>();  //like: key=mu, val= 30
            Dictionary <string, string> merged = new Dictionary <string, string>();                 //like: key=testValue, val = 30

            OutputHelper.getArgumentSetDictionary(dialogcommandstr, dialogkeyvalpair);
            OutputHelper.getArgumentSetDictionary(bskycommand, bskycommandkeyvalpair);
            OutputHelper.MergeTemplateCommandDictionary(dialogkeyvalpair, bskycommandkeyvalpair, merged);

            foreach (KeyValuePair <string, string> pair in merged)
            {
                if (!pair.Key.Contains("%"))
                {
                    OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value);
                }
            }
            //foreach (Match m in mc)
            //{
            //    //Console.WriteLine(s.Index + " : " + s.ToString());// {SelectedVars} {testValue} {%DATASET%}
            //    if (!m.ToString().Contains("%"))
            //    {
            //        args = OutputHelper.getArgument(bskycommand, m.Index);
            //        uiElementName = m.ToString().Replace('{', ' ').Replace('}', ' ').Trim();
            //        OutputHelper.SetValueFromSynEdt(element, uiElementName, args);
            //    }
            //}
            //OutputHelper.SetValueFromSynEdt(element, "SelectedVars");
            //OutputHelper.SetValueFromSynEdt(element, "testValue");

            //For Chisq check box only
            //FrameworkElement chkElement = element.FindName("chisq") as FrameworkElement;
            if (true)//window.DialogResult.HasValue && window.DialogResult.Value)
            {
                //analytics can be sent from parent function(in SyntaxEditorWindow)
                //IAnalyticsService analytics = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
                //IConfigService confService = LifetimeService.Instance.Container.Resolve<IConfigService>();//23nov2012
                cmd = new CommandRequest();

                OutputHelper.Reset();
                OutputHelper.UpdateMacro("%DATASET%", UIController.GetActiveDocument().Name);

                ///////////for chisq //// 29Mar2012 ///
                //if ((chkElement != null) && (bool)((chkElement as CheckBox).IsChecked))
                //    OutputHelper.UpdateMacro("%CHISQ%", "chisq");
                /////////////for chisq //// 29Mar2012 ///

                BSkyCanvas canvas = element as BSkyCanvas;
                if (canvas != null && !string.IsNullOrEmpty(canvas.CommandString))
                {
                    UAMenuCommand command = (UAMenuCommand)parameter;
                    cmd.CommandSyntax = command.commandformat; //OutputHelper.GetCommand(canvas.CommandString, element);// can be used for "Paste" for syntax editor
                    UAReturn retval = null;                    //retval = new UAReturn(); retval.Data = LoadAnalysisBinary();
                    #region Execute BSky command
                    try
                    {
                        retval            = analytics.Execute(cmd); // RService called and DOM returned for Analysis commands
                        cmd.CommandSyntax = command.commandtype;    ////for header area ie NOTES
                        //SaveAnalysisBinary(retval.Data);
                        ///Added by Anil///07Mar2012
                        bool myrun = false;
                        if (cmd.CommandSyntax.Contains("BSkySetDataFrameSplit("))///executes when SPLIT is fired from menu
                        {
                            bool setsplit = false;
                            int  startind = 0;
                            if (cmd.CommandSyntax.Contains("col.names"))
                            {
                                startind = cmd.CommandSyntax.IndexOf("c(", cmd.CommandSyntax.IndexOf("col.names"));// index of c(
                            }
                            else
                            {
                                startind = cmd.CommandSyntax.IndexOf("c(");// index of c(
                            }

                            int    endind = cmd.CommandSyntax.IndexOf(")", startind);
                            int    len    = endind - startind + 1;                      // finding the length of  c(......)
                            string str    = cmd.CommandSyntax.Substring(startind, len); // this will contain c('tg0','tg1') or just c()
                            string ch     = null;
                            if (str.Contains("'"))
                            {
                                ch = "'";
                            }
                            if (str.Contains('"'))
                            {
                                ch = "\"";
                            }
                            if (ch != null && ch.Length > 0)
                            {
                                int i = str.IndexOf(ch);
                                int j = -1;
                                if (i >= 0)
                                {
                                    j = str.IndexOf(ch, i + 1);
                                }
                                if (j < 0)
                                {
                                    j = i + 1;
                                }
                                string sub = str.Substring(i + 1, (j - i - 1)).Trim();
                                if (i < 0)
                                {
                                    i = str.IndexOf("'");
                                }
                                if (i >= 0)
                                {
                                    if (sub.Length > 0)
                                    {
                                        setsplit = true;
                                    }
                                }
                            }

                            //////////  Setting/Unsetting Macro  for SPLIT //////////
                            if (setsplit)
                            {
                                OutputHelper.AddGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name), element);
                                return;// no need to do any thing further
                            }
                            else // unset split
                            {
                                OutputHelper.DeleteGlobalObject(string.Format("GLOBAL.{0}.SPLIT", UIController.GetActiveDocument().Name));
                                return;// no need to do any thing further
                            }
                        }
                        ////////////////////////////
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Couldn't Execute the command");
                        logService.WriteToLogLevel("Couldn't Execute the command", LogLevelEnum.Error, ex);
                        return;
                    }
                    #endregion
                    //UAReturn retval = new UAReturn();
                    retval.Success = true;
                    AnalyticsData data = new AnalyticsData();
                    data.SelectedForDump = selectedForDump;   //10Jan2013
                    data.PreparedCommand = cmd.CommandSyntax; //storing command
                    data.Result          = retval;
                    data.AnalysisType    = cmd.CommandSyntax; //"T-Test"; For Parent Node name 02Aug2012
                    data.InputElement    = element;
                    data.DataSource      = ds;
                    data.OutputTemplate  = ((UAMenuCommand)parameter).commandoutputformat;
                    UIController.AnalysisComplete(data);
                }
            }

            //OnPostExecute(parameter);
        }