ValueLabelsSubDialog
Inheritance: System.Windows.Window, System.Windows.Markup.IComponentConnector, System.Windows.Markup.IStyleConnector
        private void ok_button_Click(object sender, RoutedEventArgs e)
        {
            if (!isTextChanged) // if text is not changed
            {
                ValueLabelsSubDialog.GetWindow(this).Close();
            }
            else
            {
                if (factormap != null && factormap.Count < 1)//if list is empty. just close the dialog
                {
                    ValueLabelsSubDialog.GetWindow(this).Close();
                    return;
                }
                bool isEmpty            = false;
                bool isDuplicateLvlName = false;
                ////bool isDuplicateLvlNum = false;
                int i   = 0;
                int len = factormap.Count;

                #region if user enters more than one levels separated by comma
                //The last item in the list is the one that has the new level(s)
                FactorMap lastitem = factormap.Last();
                if (lastitem.textbox.Contains(','))
                {
                    char[]   sepa        = { ',' };
                    string[] newlevels   = lastitem.textbox.Split(sepa);
                    bool     isfirstItem = true;

                    //add new levels but remember to modify the 'lastitem' that was having all the new levels.
                    //First new level can be fed to 'lasitem'. Second onwards create new item per new level.
                    for (int newi = 0; newi < newlevels.Length; newi++)
                    {
                        //ignore blanks
                        if (newlevels[newi].Trim() == null || newlevels[newi].Trim().Length < 1)
                        {
                            continue;
                        }

                        //ignore duplicates
                        {
                            isDuplicateLvlName = false;
                            for (int j = 0; j < len; j++)
                            {
                                //duplicate level names
                                if ((newlevels[newi].Trim().Length > 0) && (newlevels[newi].Trim().Equals(factormap.ElementAt(j).textbox.Trim())))//blank fields should not be checked
                                {
                                    isDuplicateLvlName = true;
                                    break;
                                }
                            }
                            if (isDuplicateLvlName)//ignore duplicates. When multiple new levels are entered by user with duplicates
                            {
                                continue;
                            }
                        }

                        if (isfirstItem)//first item goes to 'lastitem' object
                        {
                            lastitem.textbox = newlevels[newi].Trim();
                            isfirstItem      = false;
                        }
                        else
                        {
                            FactorMap newitemNewlevel = new FactorMap();
                            newitemNewlevel.textbox = newlevels[newi].Trim();
                            newitemNewlevel.labels  = "";
                            factormap.Add(newitemNewlevel);
                        }
                    }
                }
                #endregion
                foreach (FactorMap m in factormap)
                {
                    string s = m.labels + ":" + m.textbox;
                    //MessageBox.Show(s);

                    ////checking duplicates ////
                    i++;
                    for (int j = i; j < len; j++)
                    {
                        //duplicate level names
                        if ((m.textbox.Trim().Length > 0) && (m.textbox == factormap.ElementAt(j).textbox.Trim()))//blank fields should not be checked
                        {
                            isDuplicateLvlName = true;
                            break;
                        }

                        //////Duplicate level number
                        ////if ((m.numlevel.ToString().Trim().Length > 0) && (m.numlevel.ToString() == factormap.ElementAt(j).textbox.Trim()))//blank fields should not be checked
                        ////{
                        ////    isDuplicateLvlNum = true;
                        ////    break;
                        ////}
                    }

                    ////checking empty for all except the blank field(which is for new level)///
                    if (m.textbox.Trim().Length == 0 &&
                        !m.labels.Trim().Equals(BSky.GlobalResources.Properties.UICtrlResources.AddFactorLevelMsg.Trim()))
                    {
                        isEmpty = true;
                    }
                }
                OKclicked = true;
                if (isDuplicateLvlName)  //// || isDuplicateLvlNum)
                {
                    ////MessageBox.Show("Duplicate Level Names(or level numbers) are not allowed.", "Error! Duplicate not allowed.", MessageBoxButton.OK, MessageBoxImage.Error);
                    MessageBox.Show("Duplicate Level Names are not allowed.", "Error! Duplicate not allowed.", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (isEmpty)
                {
                    if (MessageBox.Show("Empty values not allowed.", "Warning.", MessageBoxButton.OK, MessageBoxImage.Warning) == MessageBoxResult.OK)
                    {
                        //restore cells with blank values
                        foreach (FactorMap m in factormap)
                        {
                            if (m.textbox == null || m.textbox.Trim().Length == 0)
                            {
                                m.textbox = m.labels;
                            }
                        }
                        Listbox.ItemsSource = null;
                        Listbox.ItemsSource = factormap;
                        return;
                    }
                    else if (MessageBox.Show("Empty factors will be converted to NAs.", "Warning.", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        ValueLabelsSubDialog.GetWindow(this).Close();
                    }
                    else
                    {
                        //try to put back original value that was replaced with space.
                        //If there are multiple levels(fields) made as blank, it will be trickier to get all of them back in UI dialog.
                        foreach (FactorMap m in factormap)
                        {
                            if (m.textbox == null || m.textbox.Trim().Length == 0)
                            {
                                m.textbox = m.labels;
                            }
                        }
                        Listbox.ItemsSource = null;
                        Listbox.ItemsSource = factormap;
                    }
                }
                else
                {
                    ValueLabelsSubDialog.GetWindow(this).Close();
                }
            }
        }
 private void cancel_button_Click(object sender, RoutedEventArgs e)
 {
     ValueLabelsSubDialog.GetWindow(this).Close();
 }
        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();
        }
        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 void ok_button_Click(object sender, RoutedEventArgs e)
        {
            if (!isTextChanged) // if text is not changed
            {
                ValueLabelsSubDialog.GetWindow(this).Close();
            }
            else
            {
                if (factormap != null && factormap.Count < 1)//if list is empty. just close the dialog
                {
                    ValueLabelsSubDialog.GetWindow(this).Close();
                    return;
                }
                bool isEmpty     = false;
                bool isDuplicate = false;
                int  i           = 0;
                int  len         = factormap.Count;

                foreach (FactorMap m in factormap)
                {
                    string s = m.labels + ":" + m.textbox;
                    //MessageBox.Show(s);

                    ////checking duplicates ////
                    i++;
                    for (int j = i; j < len; j++)
                    {
                        if ((m.textbox.Trim().Length > 0) && (m.textbox == factormap.ElementAt(j).textbox.Trim()))//blank fields should not be checked
                        {
                            isDuplicate = true;
                            break;
                        }
                    }

                    ////checking empty ///
                    if (m.textbox.Trim().Length == 0)
                    {
                        isEmpty = true;
                    }
                }
                OKclicked = true;
                if (isDuplicate)
                {
                    MessageBox.Show("Duplicate Level Names are not allowed.", "Error! Duplicate not allowed.", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (isEmpty)
                {
                    if (MessageBox.Show("Empty values not allowed.", "Warning.", MessageBoxButton.OK, MessageBoxImage.Warning) == MessageBoxResult.OK)
                    {
                        //restore cells with blank values
                        foreach (FactorMap m in factormap)
                        {
                            if (m.textbox == null || m.textbox.Trim().Length == 0)
                            {
                                m.textbox = m.labels;
                            }
                        }
                        Listbox.ItemsSource = null;
                        Listbox.ItemsSource = factormap;
                        return;
                    }
                    else if (MessageBox.Show("Empty factors will be converted to NAs.", "Warning.", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        ValueLabelsSubDialog.GetWindow(this).Close();
                    }
                    else
                    {
                        //try to put back original value that was replaced with space.
                        //If there are multiple levels(fields) made as blank, it will be trickier to get all of them back in UI dialog.
                        foreach (FactorMap m in factormap)
                        {
                            if (m.textbox == null || m.textbox.Trim().Length == 0)
                            {
                                m.textbox = m.labels;
                            }
                        }
                        Listbox.ItemsSource = null;
                        Listbox.ItemsSource = factormap;
                    }
                }
                else
                {
                    ValueLabelsSubDialog.GetWindow(this).Close();
                }
            }
        }