private bool checkMaxFactorsAndLoadFMap()
        {
            bool success = true;
            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();

            string fromTo = "from " + changeFrom + " to " + changeTo;
            object numfactors = null;
            string[] factors;
            if (changeFrom.Equals("Scale") && ( changeTo.Equals("Nominal") || changeTo.Equals("Ordinal") )) // S to N/O
            {
                //get the list of factors(numeric)
                numfactors = analyticServ.GetColNumFactors(colName, datasetName);

                if (numfactors != null && (numfactors as UAReturn).SimpleTypeData.GetType().Name == "String[]")
                {
                    factors = (string[])(numfactors as UAReturn).SimpleTypeData;
                    if (factors.Length > maxfactors)
                    {
                        string msg = "Conversion " + fromTo + " cannot be done, as number of factors are greater than " + maxfactors + ".";
                        if (changeMeasureCombo.SelectedIndex != 2)
                            MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        changeMeasureCombo.SelectedIndex = 2;
                        success = false;
                    }
                    else
                    {
                        _factormapList = new List<FactorMap>();
                        FactorMap fm = null;
                        foreach (string str in factors)
                        {
                            if (!str.Trim().Equals("."))//exclude '.'
                            {
                                fm = new FactorMap();
                                fm.labels = str;
                                fm.textbox = str;
                                _factormapList.Add(fm);
                            }
                        }
                    }
                }
                else//if empty levels/factors
                {
                    string msg = "Conversion " + fromTo + " cannot be done, as number of values are less than 1. Please enter some values in data grid." ;
                    if (changeMeasureCombo.SelectedIndex != 2)
                        MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    changeMeasureCombo.SelectedIndex = 2;
                    success = false;
                }
            }
            else if (changeTo.Equals("Scale") && (changeFrom.Equals("Nominal") || changeFrom.Equals("Ordinal")))// N/O to S
            {
                //get list of level names. 
                _factormapList = analyticServ.GetColumnFactormap(colName, datasetName);

            }
            //else
            //{
            //    success = false;
            //}
            //MessageBox.Show("Selection changed"+s);
            return (success);
        }
        private void valueLabelDialog()
        {

            string selectedData = "";
            string cellValue = variableGrid.CurrentCell.Text;
            string rowid = variableGrid.CurrentCell.Row.DataItem.ToString();
            // check this string colid = variableGrid.CurrentCell.Column.Header.ToString();

            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();

            bool hasmap = false;
            bool varfound = false;//variable found in ds.Variables or not
            int varidx = 0; // for index of vaiable in ds.Variables. Which is under Scale 2 Nominal (or vice versa ) change.
            /////testing Value Lable popup /////22Sep2011
            ValueLablesDialog fm = new ValueLablesDialog();
            fm.colName = rowid;
            fm.datasetName = ds.Name;
            fm.maxfactors = ds.maxfactor;//setting maximum factor limit.
            string[] dsvals = null;//=new string[ds.Variables.Count];
            DataColumnMeasureEnum measure = DataColumnMeasureEnum.Scale;
            int i = 0;
            ValueLabelDialogMatrix vlmatrix = new ValueLabelDialogMatrix();
            foreach (var v in ds.Variables)//search for col name
            {
                if (v.Name.Equals(rowid))
                {
                    varfound = true;
                    if (v.Values != null && v.Values.Count > 0)//if colname is found
                    {
                        //find if '.' exists. Following can be temp fix. We can refine.
                        bool isdot = false;
                        bool isblank = false; //18Mar2014
                        int unwanteditems = 0;
                        foreach (var lb in v.Values)
                        {
                            if (lb.ToString().Equals("."))
                            { unwanteditems++; }
                            if (lb.ToString().Trim().Equals(""))
                            { unwanteditems++; }
                        }
                        //if(isdot)
                        dsvals = new string[v.Values.Count - unwanteditems];// '.' & '' is excluded
                        //else
                        //    dsvals = new string[v.Values.Count];// '.' does not exists. no need to exclude


                        //dsvals = new string[v.Values.Count-1];// '.' is excluded
                        foreach (var lbls in v.Values)//get value lables for a column
                        {
                            if (!lbls.ToString().Equals(".") && !lbls.ToString().Trim().Equals("")) // dot should be shown in value lable dialog
                            {
                                dsvals[i] = lbls.ToString();
                                vlmatrix.addLevel(lbls.ToString(), i, true);

                                //right now we only support converting first Scale to N/O and then from that N/O to S
                                //Using following 'if' and may be couple fixes we may be able to convert first N/O to scale and then backwards
                                //02feb2014. When converting from Nominal/Ordinal to scale very first time.
                                //Originally variable was Nominal/Ordinal and first time we want to change it to scale.
                                //if (v.factormapList.Count < v.Values.Count)
                                //{
                                //    v.factormapList = new List<FactorMap>();
                                //    FactorMap fmp = null;
                                //    fmp = new FactorMap();
                                //    fmp.labels = lbls.ToString();
                                //    fmp.textbox = lbls.ToString();
                                //    v.factormapList.Add(fmp);
                                //}
                            }
                            i++;
                        }
                        measure = v.Measure;

                        fm.ValueLableListBoxValues = dsvals;//setting in popup
                        fm.oldfactcount = dsvals.Length;

                        //17Apr2014 // for retrieveing stored factor map
                        if (v.factormapList.Count > 0)
                            hasmap = true;
                        //break;
                    }
                    break;
                }
                if (!varfound)
                    varidx++;
            }


            fm.colMeasure = measure;
            fm.changeFrom = measure.ToString();//this 'changeFrom' should not change till dialog is closed(OK/CANCEL)
            fm.OKclicked = false;
            fm.modified = false; // modification done or not
            fm.vlmatrix = vlmatrix; // sending refrence of matrix.
            fm.ShowDialog();


            bool isOkclick = fm.OKclicked;
            bool ismodified = fm.modified;


            if (hasmap && fm.changeTo=="Scale")//17Apr2014 retrieveing stored factor map 
            {
                foreach (FactorMap fcm in ds.Variables[varidx].factormapList)
                {
                    FactorMap cpyfm = new FactorMap();
                    cpyfm.labels = fcm.textbox; //reversing textbox and labels
                    cpyfm.textbox = fcm.labels;
                    fm.factormapList.Add(cpyfm);
                }
            }
            List<FactorMap> fctmaplst = fm.factormapList;
            measure = fm.colMeasure;//retrieve new Measure from Value Lable Dialog
            bool OK_subdialog=false;
            if (isOkclick)
            {
                if (fctmaplst != null && fctmaplst.Count <= DS.maxfactor)//OK from main dailog. Sub dialog will appear now.
                {
                    fm.Close();//release resources held by this popup
                    //show sub dialog
                    ValueLabelsSubDialog vlsd=null;
                    if(fm.changeFrom == "Scale")
                        vlsd = new ValueLabelsSubDialog(fctmaplst, "Existing Values", "New Labels");
                    else
                        vlsd = new ValueLabelsSubDialog(fctmaplst, "Existing Values", "New Labels");// reverse text and labels

                    vlsd.ShowDialog();
                    OK_subdialog = vlsd.OKclicked;
                    fctmaplst = vlsd.factormap;
                    vlsd.Close(); //release resources held by this popup
                    if (OK_subdialog)//ok from sub-dialog
                    {
                        //ds.Variables[varidx].factormapList.Clear();
                        if (fm.changeFrom == "Scale")
                        {
                            //// read changes from UI and set UI vars to take changes //// Update UI side datasource
                            List<string> vlst = new List<string>();
                            foreach (FactorMap newlvl in fctmaplst)//get value lables for a column
                            {
                                if (!newlvl.textbox.Trim().Equals(""))//blanks are ignored from sub-dialog
                                    vlst.Add(newlvl.textbox);
                            }
                            updateVargridValuesCol(rowid, measure, vlst); // update Values Col using common function


                            //17Apr2014 Saving factormap along with other col porps of DataSourceVariable
                            int varcount = ds.Variables.Count;
                            //for (int idx = 0; idx < varcount; idx++)// v in ds.Variables)//no need of 'for' when varidx can do the job
                            //{
                            if (ds.Variables[varidx].Name.Equals(rowid) && ds.Variables[varidx].Values!=null && ds.Variables[varidx].Values.Count > 0)//if colname is found
                                {
                                    ds.Variables[varidx].factormapList.Clear();
                                    foreach (FactorMap fcm in fctmaplst)
                                    {
                                        FactorMap copyfm = new   FactorMap();
                                        copyfm.labels = fcm.labels;
                                        copyfm.textbox = fcm.textbox;

                                        ds.Variables[varidx].factormapList.Add(copyfm);
                                    }
                                    //break; //no need of break, when 'for' is commented out.
                                }
                            //}
                        }
                        else
                            updateVargridValuesCol(rowid, measure, null); // update Values Col using common function
                        if (fm.changeFrom == "Scale" && (fm.changeTo == "Nominal" || fm.changeTo == "Ordinal"))
                        {
                            if (OK_subdialog)//ok from sub-dialog
                            {
                                analyticServ.ChangeScaleToNominalOrOrdinal(rowid, fctmaplst, fm.changeTo, ds.Name);
                            }
                        }
                        else if ((fm.changeFrom == "Nominal" || fm.changeFrom == "Ordinal") && fm.changeTo == "Scale")// Nom, Ord to Scale
                        {
                            //MessageBox.Show("Nom Ord to Scale ");
                            if (OK_subdialog)//ok from sub-dialog
                            {
                                analyticServ.ChangeNominalOrOrdinalToScale(rowid, fctmaplst, fm.changeTo, ds.Name);
                            }
                        }
                    }//OK from sub-dialog
                }

                else // Nominal -> Ordinal  /  Ordinal -> Nominal. No sub dialog, as if now.
                {
                    //check if values are changed and then set ds.Changed = true;
                    if (ismodified)//values changed
                    {
                        ////setting UI side vars and datasets////
                        //measure = fm.colMeasure;//retrieve new Measure from Value Lable Dialog. shifted above for common access
                        List<string> vlst = new List<string>();

                        foreach (string newlvl in fm.ValueLableListBoxValues)//get value lables for a column
                        {
                            vlst.Add(newlvl);
                        }
                        List<ValLvlListItem> finalList = vlmatrix.getFinalList(vlst); 
                         updateVargridValuesCol(rowid, measure, vlst); // update Values Col using common function
                        //set this new list of levels to R for update.
                         analyticServ.ChangeColumnLevels(rowid, finalList, ds.Name);
                    }//if modified
                }//else .. n2s n2o o2n o2s
            }//if OK on main dialog

            fm.Close();//release resources held by this popup

            ////refreshing datagrid. if Main dialog modified or if ok is clicked from sub-dialog
            if (ismodified || OK_subdialog)
            {
                //sortcolnames = null; //10May2014 removesort icon from the already sorted col if its measure is changed.
                refreshDataGrid();
                variableGrid.Refresh();
            }
        }
        private List<FactorMap> getColumnFmap(string colName, ServerDataSource dataSource)
        {
            Object num = ((object)dispatcher.EvaluateToObject(RCommandStrings.GetColFactorMap(colName, true, dataSource), false));//num vals
            Object str = ((object)dispatcher.EvaluateToObject(RCommandStrings.GetColFactorMap(colName, false, dataSource), false));//level names

            List<FactorMap> factormapList = new List<FactorMap>();
            if (num.GetType().Name == "Double[]" && str.GetType().Name == "String[]")
            {
                double[] numval = (double[])num;
                string[] strlvl = (string[])str;

                FactorMap fm;
                for (int i = 0; i < numval.Length; i++)
                {
                    fm = new FactorMap();
                    fm.labels = strlvl[i];
                    fm.textbox = numval[i].ToString();
                    factormapList.Add(fm);
                }
            }
            return factormapList;

        }
        private void ChangeLabels(int rowindex)
        {
            if (rowindex < 0)
            {
                //Wrong row index
                return;
            }
            //int rowindex = variableGrid.SelectedIndex;
            string colname = (this.Variables[rowindex] as DataSourceVariable).RName;
            DataColumnMeasureEnum measure = (this.Variables[rowindex] as DataSourceVariable).Measure;

            if (measure == DataColumnMeasureEnum.Scale)//dont let user run "change  levels" on scale col.
            {
                MessageBox.Show("This operation is not valid for variable of type Measure = Scale(Numeric)", "Change Level Warning:", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            IAnalyticsService analyticServ = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
            List<FactorMap> fctmaplst = new List<FactorMap>();
            foreach (var v in ds.Variables[rowindex].Values)
            {
                FactorMap cpyfm = new FactorMap();
                cpyfm.labels = v;
                cpyfm.textbox = v;
                fctmaplst.Add(cpyfm);
            }
            ValueLabelsSubDialog vlsd = new ValueLabelsSubDialog(fctmaplst, "Existing Label", "New Label");
            vlsd.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            vlsd.ShowDialog();
            if (!vlsd.OKclicked)
            {
                return;
            }
            List<ValLvlListItem> finalList = new List<ValLvlListItem>();
            ValLvlListItem vlit;
            foreach (FactorMap fm in fctmaplst)
            {
                if (fm.labels != "<NA>" || fm.textbox != "<NA>")
                {
                    vlit = new ValLvlListItem();
                    vlit.OriginalLevel = fm.labels;
                    vlit.NewLevel = fm.textbox;
                    finalList.Add(vlit);
                }
            }
            analyticServ.ChangeColumnLevels(colname, finalList, ds.Name);
            refreshDataGrid();
        }