////// 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);
        }
        ////// For Analysis Command Execution from Syntax Editor /////28Mar2013 Using this one and not the other one below this method
        public void ExecuteSyntaxEditor(object param, bool SelectedForDump)
        {
            parameter = param;//set Global var.
            selectedForDump = SelectedForDump;//set Global var
            OnPreExecute(param);
            if (!canExecute) return;
            object obj = null;
            string dialogcommandstr = null;
            string HistMenuText = string.Empty;//29Mar2013
            try
            {
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: dialog xaml:" + TemplateFileName, LogLevelEnum.Info);
                //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");

                //Following commented code can be used to Add command to "History" menu when executed from Syntax Editor
                //But "Title" from XAML may not same as "text" attr from menu.xml
                //So the same command executed from Syntax Editor and Main App's menu will show duplicate
                ////xmlr.MoveToAttribute("Title");//29Mar2013 For "History" Text
                ////HistMenuText = xmlr.Value;//29Mar2013 For "History" Text
                ////UAMenuCommand uam = (UAMenuCommand)param;
                ////uam.text = HistMenuText;
                ////parameter = uam;//set Global var

                xmlr.MoveToAttribute("CommandString");
                dialogcommandstr = xmlr.Value.Replace(" ", string.Empty).Replace('\"', '\'');
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: dialog command string:" + dialogcommandstr, LogLevelEnum.Info);
                xmlr.Close();
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                //18Aug2014 Supressing this message box as we dont need it. But we still pass message in log.
                //MessageBox.Show("XAML missing or has improper format! Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                GenerateOutputTablesForNonXAML(param);
                return;
            }
            //obj = GetSessionDialog(); // same dialog cant be used as its child of the another parent in AUAnalysisCommandBase
            element = obj as FrameworkElement;
            window = new BaseOptionWindow();
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;
            
            {
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Dialog controls value mapping.", LogLevelEnum.Info);
                ////////////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)";
                if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Command:" + bskycommand, LogLevelEnum.Info);

                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 (AdvancedLogging)
                    {
                        string mapping = "Element:" + element.Name + ". Key:" + pair.Key + ". Value:" + pair.Value;
                        logService.WriteToLogLevel("ExtraLogs:\n" + mapping, LogLevelEnum.Info);
                    }
                    if (!pair.Key.Contains("%"))// This should only skip macros(words enclosed within %) and not other formats.
                    {
                        OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value); //Filling dialog with values
                    }
                }
            }
            //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)
                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
                    if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Getting DOM", LogLevelEnum.Info);
                    retval = analytics.Execute(cmd); //ExecuteBSkyCommand(true);
                    ExecuteXMLDefinedDialog(cmd.CommandSyntax);//no need to pass parameters here. Just to match func signature
                }
                //16Apr2013 till this point command has already been executed. So now we store this command for "History"
                // moved here from common function ExecuteBSkyCommand b'coz for command batch dialog SaveHistory should execute once.
                //SaveInHistory(); // not sure if needed to be commented
            }

            //OnPostExecute(parameter);

            //Cleanup. Remove Canvas children and make it null. then make Window.templace null
            BSkyCanvas canv = element as BSkyCanvas;
            int count = canv.Children.Count;
            canv.Children.RemoveRange(0, count);
            window.Template = null;
        }
        public void Execute(object param)
        {
            IAdvancedLoggingService advlog = LifetimeService.Instance.Container.Resolve<IAdvancedLoggingService>(); ;//01May2015
            advlog.RefreshAdvancedLogging();
            AdvancedLogging = AdvancedLoggingService.AdvLog;//01May2015
            bool reloaddiskfiledata = false;
            //26Jun2014 isXmlTemplateDefined = false;
            parameter = param;////set Global var
            selectedForDump = false; //this parameter is only for Analytics(or non-Analytics)commands exected from Syntax Editor
            OnPreExecute(parameter);
            if (!canExecute)
            {
                canExecute = true;//06Nov2012.Fixed. if no dataset loaded.run one smpl. then load dataset. cant run one sampl now.
                return;
            }

            //for getting dialog xaml filename in logs.
            logService.WriteToLogLevel("XAML name : " + TemplateFileName, LogLevelEnum.Info);

            object obj = null;
            string dialogkey = string.Empty;//13Feb2013
            bool isOldDialog = false;//13Feb2013
            try
            {
                //Added by Aaron 06/15/2014
                BSkyCanvas.applyBehaviors = false;

                /// TemplateFilename /// for XAML filename
                dialogkey = TemplateFileName + UIController.GetActiveDocument().FileName + UIController.GetActiveDocument().Name;
                //if obj is already in dictionary for particular dataset which is currently open
                //then load obj from dictionary
                if (sdc.SessionDialogList.ContainsKey(dialogkey))
                {
                    obj = sdc.SessionDialogList[dialogkey];//gets the exisiting dialog
                    isOldDialog = true;
                }
                else//else use XAML dialog file and create obj and then store obj in dictionary with dataset name.
                {

                    //Added by Aaron 06/15/2014
                    string CurrentDatasetName = UIController.GetActiveDocument().Name;
                    string changedxaml = string.Empty;

                    changedxaml = FixRadioGroupNameUsingFiling(TemplateFileName, CurrentDatasetName + Path.GetFileName(TemplateFileName));
                    /////////////////////////////

                    XmlReader xmlReader = XmlReader.Create(new StringReader(changedxaml));
                    obj = System.Windows.Markup.XamlReader.Load(xmlReader);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                //GenerateOutputTablesForNonXAML(param);
                return;
            }

            BSkyCanvas cs = obj as BSkyCanvas;
            BSkyCanvas.applyBehaviors = true;
            BSkyCanvas.first = cs;
            var converter = new System.Windows.Media.BrushConverter();

            cs.Background = (Brush)converter.ConvertFrom("#FFEEefFf");

            cmd = new CommandRequest();//set Global var
            element = obj as FrameworkElement;////set Global var
            window = new BaseOptionWindow();////set Global var
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)


            // If a form is displayed as modal, the code following the ShowDialog method is not executed  
            // until the dialog box is closed. However, when a form is shown as modeless, the code following 
            // the Show method is executed immediately after the form is displayed.
            if (!cs.Command)//26Jun2014 !isCommandOnlyDialog)
                window.ShowDialog();
            //Added by Aaron 07/20/2014
            //If GetOverwrittenVars returns true tells me that a user has selected a dataset or variable to be created by the analytical command but that 
            //variable already exists. Hence the command should not be executed.
            if (window.GetOverwrittenVars()) return;
            /////13Feb2013 Store obj in dictionary if not already there ////
            if (!isOldDialog)
            {
                sdc.SessionDialogList.Add(dialogkey, obj);
            }

            commandwindow = element;

            OutputHelper.Reset();
            OutputHelper.UpdateMacro("%DATASET%", UIController.GetActiveDocument().Name);
            //OutputHelper.UpdateMacro("%DATASET%", "bskyCurrentDatasetSplitSliceObj"); //09Jun2014 in case of split slice name is Dataset name

            if ((window.DialogResult.HasValue && window.DialogResult.Value) || cs.Command)
            {
                BSkyCanvas canvas = element as BSkyCanvas;

                if (canvas != null && !string.IsNullOrEmpty(canvas.CommandString))
                {
                    //following is important as its substituting params with values.
                    cmd.CommandSyntax = OutputHelper.GetCommand(canvas.CommandString, element);// can be used for "Paste" for syntax editor
                    if (cmd.CommandSyntax.Contains("BSkyReloadDataset("))// if its relaod dataset commmand then prepare some parameter before executing the command
                    {
                        reloaddiskfiledata = true;
                        SubstituteFilenameAndType();//get filename and file type of disk file that is supposed to get reloaded.

                    }
                    CollectDialogProperties(canvas); // get all dialog properties

                    ShowMouseBusy();

                    #region Loading Dialog's required R Packages //30Apr2015
                    //following single line just for testing. Comment it and uncomment next line for production.
                    //string pkgs = "zoo;sem;aa;;nlme;bb;class;"; 
                    string pkgs = dlgprop.RequiredRPacakges;
                    if (!string.IsNullOrEmpty(pkgs))
                    {
                        bool packageMissing = false;
                        string statmsg = LoadDialogRPacakges(pkgs, out packageMissing);//pass semi colon separated list of R packages.
                        if (statmsg.Trim().Length > 0 && (statmsg.ToLower().Contains("error") || packageMissing))
                        {
                            // statmsg has message like : XYZ package not found. Please install it from CRAN
                            string lastmsg = "\nPlease install the above mentioned R package(s).\nGo To Tools -> Package -> Install package from CRAN.\nInstall missing R packages and execute the dialog again.";
                            MessageBox.Show(canvas.Title + " needs the following R package(s):\n\n" + statmsg + lastmsg, "Error: Missing R Package(s)", MessageBoxButton.OK, MessageBoxImage.Stop);
                            logService.WriteToLogLevel("Dialog's required R package loading error:\n" + statmsg, LogLevelEnum.Error);
                            if (window != null)
                                window.Template = null; //13Feb2013 release the XAML object. ie obj is no more child of window.
                            HideMouseBusy();
                            return;//Skip dialog execution further.(as all required packages failed to load. And dialog commands will not execute properly)
                        }
                    }
                    #endregion

                    #region PASTE clicked on the dialog
                    //Check if OK or Syntax was clicked
                    if (window.Tag != null && window.Tag.ToString().Equals("Syntax"))//21Jan2013
                    {
                        PasteInOutputSyntax();//06May2015 PasteSyntax();
                    }
                    #endregion

                    #region OK clicked on the dialog
                    if ((window.Tag != null && window.Tag.ToString().Equals("Ok")) || dlgprop.IsCommandOnly)//26Jun2014 isCommandOnlyDialog)//21Jan2013 Dont use else if is Syntax stay dialog workaround is in use.
                    {
                        dialogTitle = (window.Title != null) ? window.Title : string.Empty;
                        string batchcommtitle = dialogTitle;

                        dsvs = UIController.GetActiveDocument().Variables;//list of exisiting vars in active dataset

                        try
                        {
                            string dlgcommands = string.Join(";", dlgprop.Commands);
                            if (dlgcommands.Contains("BSkyIndSmTTest") || dlgcommands.Contains("BSkyOneSmTTest") || dlgcommands.Contains("BSkyCrossTable"))
                            {
                                //30Apr2015 This is block is probably needed because 3 of our Template based dialogs have internal split handler.
                                cmd.CommandSyntax = GetSliceSubstitutedCommands(dlgprop.Commands, 1);
                                PrintDialogTitle(dialogTitle);//30Apr2015

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: before executing in Syntax.", LogLevelEnum.Info);


                                ExecuteInSyntaxEditor(true, dialogTitle);

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: after executing in Syntax.", LogLevelEnum.Info);


                            }
                            else
                            {
                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: before executing as BatchCommand.", LogLevelEnum.Info);


                                //this can handle template based dialogs but split handling may get tricky. To make it
                                //work here, probably, turn off split handling from within these template based dialogs.
                                //this is just ahint, we nned to try and make sure.
                                ExecuteBatch(dlgprop.Commands); //Execute single and multiple commands as batch commands(ie..execute in Syntax)

                                if(AdvancedLogging)logService.WriteToLogLevel("ExtraLogs: after executing as BatchCommand.", LogLevelEnum.Info);


                            }

                            //15Jan2015
                            //Following was the original code.But 'if/else' was introduced above just to resctrict XML templated 
                            //dialog to run differently in case of split set.
                            if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: successful execution.", LogLevelEnum.Info);


                        }
                        catch (Exception e)
                        {
                            MessageBox.Show("Couldn't Execute the command");
                            logService.WriteToLogLevel("Couldn't Execute the command", LogLevelEnum.Error, e);
                            if (window != null)
                                window.Template = null; //25Mar2013 release the XAML object. ie obj is no more child of window.
                            return;
                        }
                        //save current dialog in 'History' menu
                        SaveInHistory();
                    }
                    #endregion

                    HideMouseBusy();
                }
            }

            // if its relaod dataset commmand then we need to refresh grid and status bar
            if (reloaddiskfiledata)// (cmd.CommandSyntax.Contains("BSkyReloadDataset("))
            {
                RefreshGridAndStatus();//uncomment this line if executing in Syntax. Comment it if executing using old method.
            }

            window.Template = null; //13Feb2013 release the XAML object. ie obj is no more child of window.
            OnPostExecute(parameter);
        }
        ////// For Analysis Command Execution from Syntax Editor /////28Mar2013 Using this one and not the other one below this method
        public void ExecuteSyntaxEditor(object param, bool SelectedForDump)
        {
            parameter = param;//set Global var.
            selectedForDump = SelectedForDump;//set Global var
            OnPreExecute(param);
            if (!canExecute) return;
            object obj = null;
            string dialogcommandstr = null;
            string HistMenuText = string.Empty;//29Mar2013
            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();
                BSkyCanvas.applyBehaviors = false; //21Jul2014
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                //18Aug2014 Supressing this message box as we dont need it. But we still pass message in log.
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                GenerateOutputTablesForNonXAML(param);
                return;
            }

            BSkyCanvas.applyBehaviors = true;//21Jul2014
            element = obj as FrameworkElement;
            window = new BaseOptionWindow();
            window.Template = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;
            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("%"))// This should only skip macros(words enclosed within %) and not other formats.
                {
                    OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value); //Filling dialog with values
                }
            }


            //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)
                cmd = new CommandRequest();

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

                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

                    retval = analytics.Execute(cmd); //ExecuteBSkyCommand(true);
                    ExecuteXMLDefinedDialog();
                }
            }

            OnPostExecute(parameter);
        }
        ////// 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);
        }
        ////// For Analysis Command Execution from Syntax Editor /////28Mar2013 Using this one and not the other one below this method
        public void ExecuteSyntaxEditor(object param, bool SelectedForDump)
        {
            parameter       = param;           //set Global var.
            selectedForDump = SelectedForDump; //set Global var
            OnPreExecute(param);
            if (!canExecute)
            {
                return;
            }
            object obj = null;
            string dialogcommandstr = null;
            string HistMenuText     = string.Empty;//29Mar2013

            try
            {
                if (AdvancedLogging)
                {
                    logService.WriteToLogLevel("ExtraLogs: dialog xaml:" + TemplateFileName, LogLevelEnum.Info);
                }
                //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");

                //Following commented code can be used to Add command to "History" menu when executed from Syntax Editor
                //But "Title" from XAML may not same as "text" attr from menu.xml
                //So the same command executed from Syntax Editor and Main App's menu will show duplicate
                ////xmlr.MoveToAttribute("Title");//29Mar2013 For "History" Text
                ////HistMenuText = xmlr.Value;//29Mar2013 For "History" Text
                ////UAMenuCommand uam = (UAMenuCommand)param;
                ////uam.text = HistMenuText;
                ////parameter = uam;//set Global var

                xmlr.MoveToAttribute("CommandString");
                dialogcommandstr = xmlr.Value.Replace(" ", string.Empty).Replace('\"', '\'');
                if (AdvancedLogging)
                {
                    logService.WriteToLogLevel("ExtraLogs: dialog command string:" + dialogcommandstr, LogLevelEnum.Info);
                }
                xmlr.Close();
                obj = System.Windows.Markup.XamlReader.Load(XmlReader.Create(TemplateFileName));
            }
            catch (Exception ex)
            {
                //18Aug2014 Supressing this message box as we dont need it. But we still pass message in log.
                //MessageBox.Show("XAML missing or has improper format! Could not create template from " + TemplateFileName);
                logService.WriteToLogLevel("SynEdtr:Could not create template from " + TemplateFileName, LogLevelEnum.Error, ex);
                GenerateOutputTablesForNonXAML(param);
                return;
            }
            //obj = GetSessionDialog(); // same dialog cant be used as its child of the another parent in AUAnalysisCommandBase
            element             = obj as FrameworkElement;
            window              = new BaseOptionWindow();
            window.Template     = element;
            element.DataContext = this; // loading vars in left listbox(source)
            ///window.ShowDialog();
            commandwindow = element;

            {
                if (AdvancedLogging)
                {
                    logService.WriteToLogLevel("ExtraLogs: Dialog controls value mapping.", LogLevelEnum.Info);
                }
                ////////////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)";
                if (AdvancedLogging)
                {
                    logService.WriteToLogLevel("ExtraLogs: Command:" + bskycommand, LogLevelEnum.Info);
                }

                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 (AdvancedLogging)
                    {
                        string mapping = "Element:" + element.Name + ". Key:" + pair.Key + ". Value:" + pair.Value;
                        logService.WriteToLogLevel("ExtraLogs:\n" + mapping, LogLevelEnum.Info);
                    }
                    if (!pair.Key.Contains("%"))                                        // This should only skip macros(words enclosed within %) and not other formats.
                    {
                        OutputHelper.SetValueFromSynEdt(element, pair.Key, pair.Value); //Filling dialog with values
                    }
                }
            }
            //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)
                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
                    if (AdvancedLogging)
                    {
                        logService.WriteToLogLevel("ExtraLogs: Getting DOM", LogLevelEnum.Info);
                    }
                    retval = analytics.Execute(cmd);            //ExecuteBSkyCommand(true);
                    ExecuteXMLDefinedDialog(cmd.CommandSyntax); //no need to pass parameters here. Just to match func signature
                }
                //16Apr2013 till this point command has already been executed. So now we store this command for "History"
                // moved here from common function ExecuteBSkyCommand b'coz for command batch dialog SaveHistory should execute once.
                //SaveInHistory(); // not sure if needed to be commented
            }

            //OnPostExecute(parameter);

            //Cleanup. Remove Canvas children and make it null. then make Window.templace null
            BSkyCanvas canv  = element as BSkyCanvas;
            int        count = canv.Children.Count;

            canv.Children.RemoveRange(0, count);
            window.Template = null;
        }