public UAReturn RefreshDataset(ServerDataSource dataSource)//04Mar2015 refresh on new row added by compute
        {
            UAReturn result = new UAReturn() { Success = false };
            if (true)//dispatcher.GetErrorText().Contains(BSky.Statistics.R.RService.RCommandReturn.Success))
            {
                //Get matrix columns
                string subCommand = RCommandStrings.GetDataFrameColumnNames(dataSource);

                object colnames = dispatcher.EvaluateToObject(subCommand, false);
                //if colnames are null. Because we were unable to open the dataset because of any reason.
                if (colnames == null)
                {
                    CloseDataset(dataSource);
                    result.Success = false;
                    result.Error = "Error Opening Dataset.";
                    return result;
                }

                //if colnames are duplicate then we dont load the dataset and show error message. Also we clean R
                if (isDuplicateColnames(colnames))
                {
                    CloseDataset(dataSource);
                    result.Success = false;
                    result.Error = "Dulicate Column Names in Dataset";
                    return result;
                }
                if (colnames != null)
                {
                    string[] columnNames = null;//var columnNames = new string[] { "aaa", "bbb" };
                    Type retType = colnames.GetType();
                    if (retType.Name == "String[]")//for multicols
                    {
                        columnNames = (String[])colnames;
                    }
                    else if (retType.Name == "String")//for single col
                    {
                        columnNames = new string[1];
                        columnNames[0] = (String)colnames;
                    }
                    else
                    {
                        return new UAReturn() { Success = false };
                    }

                    //maximum factors allowed
                    object maxf = (getMaxFactors(dataSource));
                    //sym = maxf as SymbolicExpression;

                    int mxf;//sym.AsInteger()[0];
                    bool parseSuccess = int.TryParse(maxf.ToString(), out mxf);
                    dataSource.MaxFactors = parseSuccess ? mxf : 40; //Hardcoded Default max factor count   //int.Parse(maxf.ToString());

                    dataSource.Variables.Clear();
                    int rowcount = GetRowCount(dataSource);//31Dec2014
                    int columnindex = 1;
                    SymbolicExpression symex = null;
                    foreach (object s in columnNames)
                    {
    
                        symex = dispatcher.EvaluateToSymExp(string.Format("UAgetColProperties(dataSetNameOrIndex='{0}', colNameOrIndex={1}, asClass=FALSE)", dataSource.Name, columnindex));
                        GenericVector gv = symex.AsList();

                        string colclass = dispatcher.RawEvaluateGetstring(string.Format("class({0}[[{1}]])", dataSource.Name, columnindex));//,true);
                        if (colclass == null)
                        {
                            colclass = "";
                        }

                        string lab = (gv[2] != null && gv[2].AsCharacter() != null && gv[2].AsCharacter()[0] != null) ? gv[2].AsCharacter()[0].ToString() : string.Empty;
                        DataColumnTypeEnum dtyp = (gv[1] != null && gv[1].AsCharacter() != null && gv[1].AsCharacter()[0] != null) ? GetCovertedDataType(gv[1].AsCharacter()[0].ToString()) : DataColumnTypeEnum.Character;
                        string mistyp = (gv[5] != null && gv[5].AsCharacter() != null && gv[5].AsCharacter()[0] != null) ? gv[5].AsCharacter()[0].ToString() : string.Empty;
                        

                        DataSourceVariable var = new DataSourceVariable()
                        {
                            Name = s.ToString(),
                            Label = lab,
                            DataType = dtyp,
                            DataClass = colclass,
                            Measure = DataColumnMeasureEnum.Scale,
                            Width = 4,
                            Decimals = 0,
                            Columns = 8,
                            MissType = mistyp,
                            RowCount = rowcount //GetVectorLength(dataSource, s.ToString())

                        };

                        if (symex != null)
                        {

                            //if (gv.Length == 1)
                            {
                                ////Set Measure
                                switch (gv[7].AsCharacter()[0].ToString())
                                {
                                    case "factor":
                                        var.Measure = DataColumnMeasureEnum.Nominal;
                                        break;

                                    case "ordinal":
                                        var.Measure = DataColumnMeasureEnum.Ordinal;
                                        break;

                                    default:
                                        if(var.DataType == DataColumnTypeEnum.Character) //02Jun2015 treating "character" type as Nominal in UI. In R its not factor
                                        {
                                            var.Measure = DataColumnMeasureEnum.Nominal;
                                        }
                                        else
                                        var.Measure = DataColumnMeasureEnum.Scale;
                                        break;
                                }

                                CharacterVector cv = gv[3].AsCharacter();
                                string[] vals = cv.ToArray();
                                if (vals != null && vals.Length > 0)
                                {
                                    if (vals.Length > 1)
                                    {
                                        var.Values.AddRange(vals);//more than 1 strings
                                    }
                                    else if (vals[0].Trim().Length > 0)
                                    {
                                        var.Values.Add(vals[0]);//1 string
                                    }
                                }

                                if (!(var.MissType == "none"))
                                {
                                    CharacterVector cvv = gv[3].AsCharacter();
                                    string[] misvals = cvv.ToArray();
                                    if (misvals != null && misvals.Length > 0)
                                    {
                                        if (misvals.Length > 1)
                                        {
                                            var.Missing.AddRange(misvals);//more than 1 strings
                                        }
                                        else if (misvals[0].Trim().Length > 0)
                                        {
                                            var.Missing.Add(misvals[0]);//1 string
                                        }
                                    }
                                }
                                else
                                {
                                    string misval = "none";
                                    var.Missing.Add(misval);
                                }

                            }
                        }

                        if (dataSource.Extension == "rdata")// if filetype is RDATA.
                        {
                            if (gv[9].AsCharacter() != null && gv[9].AsCharacter()[0].ToString() != "-2146826288")
                                var.Width = Int32.Parse(gv[9].AsCharacter()[0].ToString());

                            if (gv[10].AsCharacter() != null && gv[10].AsCharacter()[0].ToString() != "-2146826288")
                                var.Decimals = Int32.Parse(gv[10].AsCharacter()[0].ToString());

                            if (gv[11].AsCharacter() != null && gv[11].AsCharacter()[0].ToString() != "-2146826288")
                                var.Columns = UInt32.Parse(gv[11].AsCharacter()[0].ToString());
                        }

                        try
                        {
                            ////////// Alignment  ////////////
                            //logService.WriteToLogLevel("Get-Set Alignment start : " + s.ToString(), LogLevelEnum.Info);
                            string align = gv[6].AsCharacter()[0].ToString();
                            if (align == "-2146826288") align = "Left";
                            DataColumnAlignmentEnum alignVal = (DataColumnAlignmentEnum)Enum.Parse(typeof(DataColumnAlignmentEnum), align);
                            if (Enum.IsDefined(typeof(DataColumnAlignmentEnum), alignVal))
                                var.Alignment = alignVal;
                            else
                                var.Alignment = DataColumnAlignmentEnum.Left;

                            var.Role = DataColumnRole.Input;// Role is not used, I guess, so 'if' is commented above
                            //logService.WriteToLogLevel("Get-Set Alignment start : " + s.ToString(), LogLevelEnum.Info);
                        }
                        catch (ArgumentException)
                        {
                            logService.WriteToLogLevel("Not a member of enum(Alignment) ", LogLevelEnum.Error);
                        }

                        dataSource.Variables.Add(var);
                        columnindex++;
                        dataSource.RowCount = Math.Max(dataSource.RowCount, dataSource.Variables.Last().RowCount);
                    }

                    result.Datasource = dataSource;
                    result.Success = true;

                    this.DataSources.Add(dataSource);
                }
                else // no need of this 'else' unless you want to put custom error message in result
                {
                }
            }
            return result;
        }
        public UAReturn RefreshDataset_old(ServerDataSource dataSource)//25Mar2013 refresh on new row added by compute
        {
            UAReturn result = new UAReturn() { Success = false };
            if (true)//dispatcher.GetErrorText().Contains(BSky.Statistics.R.RService.RCommandReturn.Success))
            {
                logService.WriteToLogLevel("GetColnames Start:", LogLevelEnum.Info);
                //Get matrix columns
                string subCommand = RCommandStrings.GetDataFrameColumnNames(dataSource);

                object colnames = dispatcher.EvaluateToObject(subCommand, false);
                string[] columnNames = null;//var columnNames = new string[] { "aaa", "bbb" };
                Type retType = colnames.GetType();
                if (retType.Name == "String[]")//for multicols
                {
                    columnNames = (String[])colnames;
                }
                else if (retType.Name == "String")//for single col
                {
                    columnNames = new string[1];
                    columnNames[0] = (String)colnames;
                }
                else
                {
                    return new UAReturn() { Success = false };
                }

                logService.WriteToLogLevel("GetColnames End", LogLevelEnum.Info);

                logService.WriteToLogLevel("Get Max factor start", LogLevelEnum.Info);
                //maximum factors allowed
                object maxf = (getMaxFactors(dataSource));


                int mxf;//sym.AsInteger()[0];
                bool parseSuccess = int.TryParse(maxf.ToString(), out mxf);
                dataSource.MaxFactors = parseSuccess ? mxf : 40; //Hardcoded Default max factor count   //int.Parse(maxf.ToString());
                logService.WriteToLogLevel("Get Max factor end", LogLevelEnum.Info);

                dataSource.Variables.Clear();
                int rowcount = GetRowCount(dataSource);//31Dec2014
                int columnindex = 1;
                foreach (object s in columnNames)
                {
                    logService.WriteToLogLevel("Get Col Prop start : " + s.ToString(), LogLevelEnum.Info);
                    object resobj = GetColProp(dataSource, s.ToString()).SimpleTypeData;
                    object[] cprops = (object[])resobj;
                    logService.WriteToLogLevel("Get Col Prop end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Set Col Prop start : " + s.ToString(), LogLevelEnum.Info);
                    DataSourceVariable var = new DataSourceVariable()
                    {
                        Name = s.ToString(),
                        Label = cprops[2].ToString(),
                        DataType = GetCovertedDataType(cprops[1].ToString()),
                        Measure = DataColumnMeasureEnum.Scale,
                        Width = 4,
                        Decimals = 0,
                        Columns = 8,
                        MissType = cprops[5].ToString(),
                        RowCount = rowcount //GetVectorLength(dataSource, s.ToString())
                        //factormapList = new List<FactorMap>()//17Apr2014
                    };
                    logService.WriteToLogLevel("Set Col Prop end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set Col factors start : " + s.ToString(), LogLevelEnum.Info);
                    //uadatasets$lst$ added by Anil in following two
                    bool isfactors = (bool)dispatcher.EvaluateToObject(string.Format("is.factor({0}[,{1}])", dataSource.Name, columnindex), false);//is.factor(uadatasets$lst${0}[,{1}])
                    if (isfactors)
                    {    //(DataColumnMeasureEnum)Enum.Parse(typeof(DataColumnMeasureEnum), GetMeasure(dataSource, s.ToString()));
                        bool isOrdered = (bool)dispatcher.EvaluateToObject(string.Format("is.ordered({0}[,{1}])", dataSource.Name, columnindex), false);//is.ordered(uadatasets$lst${0}[,{1}])
                        if (isOrdered)
                            var.Measure = DataColumnMeasureEnum.Ordinal;
                        else
                            var.Measure = DataColumnMeasureEnum.Nominal; // default is set in above para which will be overwritten in this line if its factor type
                        //reading all levels/factors
                        object tempO = (object)GetFactorValues(dataSource, s.ToString()).SimpleTypeData;
                        if (tempO != null)
                        {
                            if (tempO.GetType().Name.Equals("String[]"))//tempO.GetType().IsArray)
                            {
                                string[] vals = tempO as string[];
                                var.Values.AddRange(vals);//adding all values to list
                            }
                            else if (tempO.GetType().Name.Equals("String"))
                            {
                                string vals = tempO as string;
                                var.Values.Add(vals);//adding all values to list
                            }
                            else
                            {
                                //some other unexpected type was returned in tempO.
                                //can print an error message here.
                                string[] charfactors = (tempO as SymbolicExpression).AsCharacter().ToArray();
                                var.Values.AddRange(charfactors);//adding all values to list
                            }
                        }
                    }
                    logService.WriteToLogLevel("Get-Set Col factors end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set Col Missing start : " + s.ToString(), LogLevelEnum.Info);
                    if (!(var.MissType == "none"))
                    {
                        object tempObj = (object)GetMissingValues(dataSource, s.ToString()).SimpleTypeData;
                        if (tempObj != null)
                        {
                            double[] misval;
                            if (tempObj.GetType().Name.Equals("Double[]"))// (tempObj.GetType().IsArray)
                            {
                                misval = tempObj as double[];
                                foreach (double mv in misval)
                                    var.Missing.Add(mv.ToString());
                            }
                            else if (tempObj.GetType().Name.Equals("Double"))
                            {
                                double misvalue = (double)tempObj;
                                var.Missing.Add(misvalue.ToString());
                            }
                            else
                            {
                                //some other unexpected type was returned in tempO.
                                //can print an error message here.

                                var.Missing.Add("");//adding blank
                            }
                        }
                    }
                    else
                    {
                        string misval = "none";
                        var.Missing.Add(misval);
                    }
                    logService.WriteToLogLevel("Get-Set Col Missing end : " + s.ToString(), LogLevelEnum.Info);

                    logService.WriteToLogLevel("Get-Set others start : " + s.ToString(), LogLevelEnum.Info);
                    if (dataSource.Extension == "rdata")// if filetype is RDATA.
                    {
                        if (cprops[9].ToString() != "-2146826288")
                            var.Width = Int32.Parse(cprops[9].ToString());

                        if (cprops[10].ToString() != "-2146826288")
                            var.Decimals = Int32.Parse(cprops[10].ToString());

                        if (cprops[11].ToString() != "-2146826288")
                            var.Columns = UInt32.Parse(cprops[11].ToString());
                    }
                    try
                    {
                        ////////// Alignment  ////////////
                        if (cprops[6].ToString() == "-2146826288") cprops[6] = "Left";
                        DataColumnAlignmentEnum alignVal = (DataColumnAlignmentEnum)Enum.Parse(typeof(DataColumnAlignmentEnum), cprops[6].ToString());
                        if (Enum.IsDefined(typeof(DataColumnAlignmentEnum), alignVal))
                            var.Alignment = alignVal;
                        else
                            var.Alignment = DataColumnAlignmentEnum.Left;

                        var.Role = DataColumnRole.Input;// Role is not used, I guess, so 'if' is commented above
                    }
                    catch (ArgumentException)
                    {
                        //Console.WriteLine("Not a member of the enumeration.");
                        logService.WriteToLogLevel("Not a member of enum(Alignment) ", LogLevelEnum.Error);
                    }
                    logService.WriteToLogLevel("Get-Set others end : " + s.ToString(), LogLevelEnum.Info);

                    dataSource.Variables.Add(var);
                    columnindex++;
                    dataSource.RowCount = Math.Max(dataSource.RowCount, dataSource.Variables.Last().RowCount);
                }

                result.Datasource = dataSource;
                result.Success = true;

                this.DataSources.Add(dataSource);
            }
            return result;
        }
        private void removeVarGridVariable()
        {

            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            analyticServ.removeVargridColumn(delcolname, ds.Name);//removing R side
            //renumbering
            renumberRowHeader(variableGrid);
            //remove var in UI side datasets
            DataSourceVariable dsv = new DataSourceVariable();
            dsv = ds.Variables.ElementAt(delvarindex);
            ds.Variables.Remove(dsv);
            //refresh
            refreshDataGrid();
        }
        private void variableGrid_BeginningNewRow(object sender, DataGridBeginningNewRowEventArgs e)
        {
            //int curRowindex = variableGrid.CurrentRow.Index;
            DataSourceVariable var = new DataSourceVariable();
            //string RecCount = (this.Variables.Count + 1).ToString();//add 1 because its 0 based

            string varname = "newvar";
            //getRightClickRowIndex();
            int rowindex = variableGrid.SelectedIndex;

            //checking duplicate var names
            foreach (DataSourceVariable dsv in this.Variables)
            {
                varname = "newvar" + varcount.ToString();
                if (dsv.Name == varname)
                    varcount++;
            }
            var.Name = varname;
            var.Label = varname;

            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            analyticServ.addNewVariable(var.Name, ".", rowindex + 1, ds.Name);

            this.Variables.Insert(rowindex, var);
            DS.Variables.Insert(rowindex, var);//one more refresh needed. I guess

            renumberRowHeader(variableGrid);
            ds.Changed = true;
            refreshDataGrid(); 
        }
        private void _deleteVar_Click(object sender, RoutedEventArgs e)
        {

            MessageBoxResult result = MessageBox.Show("Do you want to delete variable?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                DataSourceVariable var = new DataSourceVariable();
                //getRightClickRowIndex();
                int rowindex = variableGrid.SelectedIndex;
                //var.Name = "accid";
                //this.Variables.Remove(var);
                variableGrid.RemoveRow(rowindex);//two things .grid remove UI dataset side remove. third is R side remove
                variableGrid.Refresh();
                // renumberRowHeader(); //not required. I guess automatically handeled by RemoveRow() above.
                ds.Changed = true;

                //this.Variables.Remove(rowindex);
                //refreshDataGrid();
            }
        }
        private void _insertNewVarAtEnd_Click(object sender, RoutedEventArgs e)
        {
            DataSourceVariable var = new DataSourceVariable();
            //string RecCount = (this.Variables.Count + 1).ToString();//add 1 because its 0 based

            string varname = "newvar";
            //getRightClickRowIndex();
            int rowindex = Variables.Count;// variableGrid.SelectedIndex;


            //checking duplicate var names
            do
            {
                varname = "newvar" + varcount.ToString();
                varcount++;
            } while (this.Variables.Contains(varname));
            var.Name = varname;
            var.Label = varname;

            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            analyticServ.addNewVariable(var.Name, ".", rowindex + 1, ds.Name);

            this.Variables.Insert(rowindex, var);
            DS.Variables.Insert(rowindex, var);//one more refresh needed. I guess

            renumberRowHeader(variableGrid);
            ds.Changed = true;
            refreshDataGrid();
        }
        //bool committedVarCell = false;
        private void variableGrid_CommittingEdit(object sender, DataGridEndingEditEventArgs e)
        {
            //if (committedVarCell)
            //{
            //    e.Cancel = true;
            //    return;
            //}
            //committedVarCell = true;
            // //on cell Edit and clicking elsewhere gives the info about edited cell
            List<string> colLevels = null;
            string cellVal = variableGrid.CurrentCell.Text;//eg..Male or Female
            string cellValue = cellVal != null ? cellVal.Replace("'", @"\'").Replace("\"", @"\'") : string.Empty;
            //string cellValue = cellVal != null ? cellVal.Replace("'", @"\'") : string.Empty;
            if (cellValue == null || cellValue.Trim().Length < 1) //Do not create new variable row if variable name is not provided
            {
                //method1 variableGrid.RemoveRow(variableGrid.CurrentRow.Index);

                //variableGrid.RaiseEvent();
                return;
            }
            //rowid = variableGrid.CurrentCell.Row.DataItem.ToString();//eg..gender // should be captured when we click on cell
            string colid = variableGrid.CurrentCell.Column.Header.ToString();//eg..Label
            switch (e.Column.Name)
            {
                case "Name":
                    break;
                case "DataType":
                    if (colid.Equals("DataType")) colid = "Type"; // colid must match with R side property name. Else it will not work
                    //MessageBox.Show(selectedData);
                    if (cellValue.Equals("String")) cellValue = "character";
                    if (cellValue.Equals("Numeric") || cellValue.Equals("Int") || cellValue.Equals("Float") || cellValue.Equals("Double")) cellValue = "numeric";
                    if (cellValue.Equals("Bool")) cellValue = "logical";
                    break;
                case "Width":
                    break;
                case "Decimals":
                    break;
                case "Label":
                    break;
                case "Values": 
                    colid = "Levels"; // "Levels"  new property name in R code
                    break;

                case "Missing":
                    break;
                case "Columns":
                    break;
                case "Alignment": 
                    colid = "Align"; // "Align" new property name in R code
                    C1.WPF.DataGrid.DataGridComboBoxColumn col = e.Column as C1.WPF.DataGrid.DataGridComboBoxColumn;
                    C1.WPF.C1ComboBox combo = e.EditingElement as C1.WPF.C1ComboBox;
                    string value = combo.Text;
                    break;
                case "Measure":
                    colLevels = getLevels();

                    break;
                case "Role":
                    break;
                default:
                    break;

            }

            ///// Modifying R side Dataset ////////
            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            if (rowid == null)//new row
            {
                int rowindex = 0;//variableGrid.CurrentRow.Index;
                string datagridcolval = ".";//default value for new col in datagrid view.
                // add new row cellValue is new colname
                analyticServ.addNewVariable(cellValue, datagridcolval, rowindex, ds.Name);


                //// Insert on UI side dataset ///
                DataSourceVariable var = new DataSourceVariable();
                // string RecCount = (this.Variables.Count + 1).ToString();//add 1 because its 0 based
                // int insertrowindex = variableGrid.SelectedIndex;
                 var.Name = cellValue; //////// Check Problem for manually appending new Var at the end
                 DS.Variables.Add(var);
                //this.Variables.Insert(rowindex, var);
                //DS.Variables.Insert(rowindex, var);//one more refresh needed. I guess
                //renumberRowHeader(variableGrid);
            }
            else
            {//edit existing row
                UAReturn retval = analyticServ.EditVarGrid(ds.Name, rowid, colid, cellValue, colLevels);
                retval.Success = true;
                ///08Jul2013 Show Error/Warning in output window if any.
                //if (retval != null && retval.Data != null)
                //    SendErrorWarningToOutput(retval);
            }
            //variableGrid. = cellValue;
            //MessageBox.Show("[R:"+rowid + "] [C:" + colid + "] [V:" + cellValue + "] [DS:" + ds.Name+"]");
            ds.Changed = true;
            if (e.Column.Name.Equals("Name"))
            refreshDataGrid();
            //arrangeVarGridCols();//rearrange the var-grid cols

        }