private void RangeChanged(object sender, DateTime DateStart, DateTime DateEnd)
 {
     DataTable Controlos = SGCEBL.PGGET.GetCONTROLOSinputCODCOPERACAOandDATAINIandDATAFIM("01", DateStart, DateEnd);
     List<ProductOrder> Cntrls = new List<ProductOrder>();
     foreach (Machine item in oCal.Machines) {
         item.Ordens.Clear();
     }
     foreach (DataRow iRow in Controlos.Rows) {
         DateTime Ini = iRow.Field<DateTime>("Data Início");
         DateTime Fim = iRow.Field<DateTime>("Data Fim");
         String Maq = iRow.Field<string>("Equipamento");
         String txt = iRow.Field<object>("OPP").ToString() + ":" + iRow.Field<string>("CODARTIGO");
         ProductOrder po = Cntrls.Find(x => x.Equipamento == Maq && x.DateStart == Ini);
         if (po == null)Cntrls.Add(new ProductOrder(Maq + "_" + Cntrls.Count, txt, 0, Ini, Fim, 0, Maq));
         else po.Text += "+" + txt;
     }
     foreach (ProductOrder po in Cntrls) {
         Machine CurMac = oCal.Machines.Find(x => x.Name == po.Equipamento);
         if (CurMac == null) {
             CurMac = new Machine(po.Equipamento);
             oCal.Machines.Add(CurMac);
         }
         po.ItemID = CurMac.Name + "_" + CurMac.Ordens.Count;
         CurMac.Ordens.Add(po);
     }
     oCal.oRefresh();
 }
 public String findConfferention(List<int> list_id)
 {
     bool flag;
     foreach (KeyValuePair<String, List<int>> pair in conferention)
     {
         if (list_id.Count == pair.Value.Count)
         {
             flag = true;
             for (int i = 0; i < pair.Value.Count; i++)
             {
                 int find = list_id.Find(item => item==pair.Value[i] );
                 if (find == 0)
                 {
                     flag = false;
                 }
             }
             if (flag == true)
             {
                 return pair.Key;
             }
         }
         else
         {
             flag = false;
         }
     }
     return "";
 }
 static ColorPicker()
 {
     colorsList = new List<ColorNamePair>();
     Type t = typeof(Colors);
     PropertyInfo[] properties = t.GetProperties();
     foreach (PropertyInfo property in properties)
     {
         ColorNamePair c = new ColorNamePair(property.Name, (Color)property.GetValue(null, null));
         colorsList.Add(c);
     }
     ColorNamePair transparent = colorsList.Find(c => c.Name == "Transparent");
     colorsList.Remove(transparent);
 }
Beispiel #4
0
        public SubsystemAssembly GetAssembly(GetAssemblyParameterMessage message)
        {
            try
            {
                string assemblyDirLocation = AppDomain.CurrentDomain.BaseDirectory;
                List<string> dirList = new List<string>(Directory.GetDirectories(assemblyDirLocation));

                Stream stream = new MemoryStream();

                string name = dirList.Find(
                    delegate(string dirName)
                    {
                        return (dirName.Contains(message.SystemMode.ToString()));
                    });

                //if specified assembly doesn't exist then 
                //find one below the specified assembly level
                //e.g. if specified assembly is Engineer then look for
                // Maintenance, if not found then Supervisor, if not found
                // then Operator
                List<EnumSystemOperationMode> SearchCriteria = new List<EnumSystemOperationMode>();

                if (String.IsNullOrWhiteSpace(name))
                {
                    if (message.SystemMode == EnumSystemOperationMode.Engineer)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Maintenance);
                    }

                    if (message.SystemMode == EnumSystemOperationMode.Maintenance ||
                        message.SystemMode == EnumSystemOperationMode.Engineer)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Supervisor);
                    }

                    if (message.SystemMode == EnumSystemOperationMode.Supervisor ||
                        message.SystemMode == EnumSystemOperationMode.Engineer ||
                        message.SystemMode == EnumSystemOperationMode.Maintenance)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Operator);
                    }

                    foreach (EnumSystemOperationMode criteria in SearchCriteria)
                    {
                        name = dirList.Find(
                        delegate(string dirName)
                        {
                            return (dirName.Contains(criteria.ToString()));
                        });

                        if (!String.IsNullOrWhiteSpace(name))
                        {
                            break;
                        }
                    }
                }

                if (!String.IsNullOrWhiteSpace(name))
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        string[] files = Directory.GetFiles(name);

                        // changing this defalte threshold avoids corrupted files in the zipfile.
                        zip.ParallelDeflateThreshold = -1; 

                        zip.AddFiles(files, "");

                        // zip up resource directories as well
                        string[] directories = Directory.GetDirectories(name);
                        foreach (string subDir in directories)
                        {
                            try
                            {
                                // only add resource files for this local project. Exclude the L3.Cargo.Common.Dashboard.resources.dll
                                string[] resFiles = Directory.GetFiles(subDir);
                                zip.AddDirectoryByName(Path.GetFileName(subDir));
                                foreach (string resFile in resFiles)
                                {
                                    // Avoid adding the resource file for the Dashboard.
                                    // TODO: this string should come from somewhere
                                    if (!resFile.Contains("L3.Cargo.Common.Dashboard.resources.dll"))
                                    {
                                        zip.AddFile(resFile, Path.GetFileName(subDir));
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                string ex = e.Message;
                            }
                        }

                        zip.Save(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                    }

                    OperationContext clientContext = OperationContext.Current;
                    clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs e)
                    {
                        if (stream != null)
                            stream.Dispose();
                    });

                    return new SubsystemAssembly(stream, m_aliasTag + "_" + m_assemblyTag + ".zip");
                }
                else
                    throw new FaultException(new FaultReason("File does not exist"));
            }
            catch (Exception exp)
            {
                throw new FaultException(new FaultReason(exp.Message));
            }
        }
Beispiel #5
0
        private void SetupProfiles()
        {
            cmbProfile.ItemsSource = null;
            _profiles = Config.GetGlobal<List<ConnectionProfile>>("connection.profiles", new List<ConnectionProfile>());
            String lastProfile = Config.GetGlobal<string>("connection.lastprofile", null);
            if (!Config.GetGlobal<bool>("connection.skiplegacyimport", false)) {

                LegacySettings.TraverseSubKeys("Client", "UserProfiles", (key) => {
                    ConnectionProfile profile = new ConnectionProfile();
                    string name = key.Name;
                    profile.Name = key.Name.Substring(name.LastIndexOf('\\') + 1);
                    profile.Server = key.GetValue("DatabaseServer") as string;
                    profile.Database = key.GetValue("DatabaseName") as string;
                    profile.LastUser = key.GetValue("LastUser") as string;
                    profile.Timeout = key.GetValue("CommandTimeout") as Nullable<Int32>;
                    _profiles.Add(profile);
                });

                if (lastProfile == null) {
                    lastProfile = LegacySettings.GetRegSetting("Client", "UserProfiles", "LastUsedProfile", "");
                }

                // Save the new list
                Config.SetGlobal("connection.profiles", _profiles);
                // and we don'note need to do this again!
                Config.SetGlobal("connection.skiplegacyimport", true);
            }

            cmbProfile.ItemsSource = _profiles;

            if (!String.IsNullOrEmpty(lastProfile)) {
                // Look in the list for the profile with the same name.
                ConnectionProfile lastUserProfile = _profiles.Find((item) => { return item.Name.Equals(lastProfile); });
                if (lastUserProfile != null) {
                    cmbProfile.SelectedItem = lastUserProfile;
                }
            }
        }
        public PopUpAirlinerSeatsConfiguration(AirlinerType type, List<AirlinerClass> classes)
        {
            this.FreeClassTypes = new ObservableCollection<AirlinerClass.ClassType>();
            this.Classes = new ObservableCollection<AirlinerClassMVVM>();
            this.Type = type;

            AirlinerClass economyClass = classes.Find(c => c.Type == AirlinerClass.ClassType.Economy_Class);

            foreach (AirlinerClass aClass in classes)
            {

                int maxseats = aClass.Type == AirlinerClass.ClassType.Economy_Class ? aClass.SeatingCapacity : economyClass.RegularSeatingCapacity - 1;
                AirlinerClassMVVM nClass = new AirlinerClassMVVM(aClass.Type, aClass.SeatingCapacity,maxseats, aClass.Type != AirlinerClass.ClassType.Economy_Class);
                this.Classes.Add(nClass);

                foreach (AirlinerFacility facility in aClass.getFacilities())
                    nClass.Facilities.Where(f=>f.Type == facility.Type).First().SelectedFacility = facility;

            }

            this.CanAddNewClass = this.Classes.Count < ((AirlinerPassengerType)this.Type).MaxAirlinerClasses;

            if (this.Classes.Count < 3)
            {
                this.FreeClassTypes.Clear();
                this.FreeClassTypes.Add(AirlinerClass.ClassType.Business_Class);
                this.FreeClassTypes.Add(AirlinerClass.ClassType.First_Class);

            }

            InitializeComponent();
        }
Beispiel #7
0
        /// <summary>
        /// DataGridの異なる行異なる列を選択したコピーの禁止処理
        /// </summary>
        /// <returns></returns>
        bool CheckCopyDataGridContents()
        {
            List<System.Windows.Point> rowAndColList = new List<System.Windows.Point>();
            List<int> copyRowList = new List<int>();
            List<int> copyColumnList = new List<int>();

            var cells = upperdatagrid.SelectedCells;
            foreach (DataGridCellInfo cell in cells)
            {
                rowAndColList.Add(
                    new System.Windows.Point(upperdatagrid.Items.IndexOf(cell.Item), cell.Column.DisplayIndex));
                int b = copyColumnList.Find(s => s == cell.Column.DisplayIndex);
                if (copyColumnList.Count == 0 || !copyColumnList.Contains(cell.Column.DisplayIndex))
                {
                    copyColumnList.Add(cell.Column.DisplayIndex);
                }
                if (copyRowList.Count == 0 || !copyRowList.Contains(upperdatagrid.Items.IndexOf(cell.Item)))
                {
                    copyRowList.Add(upperdatagrid.Items.IndexOf(cell.Item));
                }
            }
            int copyRangeColumn = copyColumnList.Count;
            int copyRangeRow = copyRowList.Count;
            bool validCopyFlag = true;

            //複数コピーの禁止
            //全てのXがコピーした列数分だけ存在するか、すべてのYがコピーした行数分だけ存在する
            foreach (var y in copyColumnList)
            {
                validCopyFlag = true;
                if (rowAndColList.FindAll(s => s.Y == y).Count != copyRangeRow)
                {
                    validCopyFlag = false;
                    break;
                }
            }
            foreach (var x in copyRowList)
            {
                validCopyFlag = true;
                if (rowAndColList.FindAll(s => s.X == x).Count != copyRangeColumn)
                {
                    validCopyFlag = false;
                    break;
                }
            }
            if (!validCopyFlag)
            {
                System.Windows.Forms.MessageBox.Show(AnimeCheckerByXaml.Properties.Settings.Default.E0004,
                                            "エラー", System.Windows.Forms.MessageBoxButtons.OK,
                                            System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
            return true;
        }
        public void DisplayWeek(WeekData Week)
        {
            CurrentWeek = Week;
            TopGrid.Children.Clear();
            MainGrid.Children.Clear();
            MainGrid.RowDefinitions.Clear();

            //MouseCoordBlock = AddToCell(TopGrid, 0, 1, new TextBlock { Text = "----" });

            if (CurrentWeek == null) return;

            var maxRows = EnumerateFullColumnHeights(Week).Max() + 4;
            var approvedLeaveRows = EnumerateLeaveColumnHeights(Week).Max() + 2;

            MainGrid.Height = 20 * maxRows;

            for (var i = 0; i < maxRows; ++i)
                MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(20) });

            AddCell(TopGrid, "Substitutes", 0, 0, "All available substitutes");
            AddCell(TopGrid, "", 0, 1, null);
            for (var i = 0; i < maxRows; ++i)
            {
                if (i > Week.Substitutes.Count)
                    AddCell(MainGrid, "", 0, i, "", null);
                else if (i == Week.Substitutes.Count)
                    AddCell(MainGrid, "+ new substitute", 0, i, "Click to add new substitute", () =>
                        {
                            var creator = CreateSub.Show();
                            if (creator.FinishedInput)
                                ApplyAction(String.Format("S\"{0}\" ", creator.Name));
                        });
                else if (i < Week.Substitutes.Count)
                {
                    var lambdaSub = Week.Substitutes[i];
                    AddCell(MainGrid, Week.Substitutes[i].ToString(), 0, i, "Click to modify matrix assignments", () =>
                        {
                            var matrixEditor = ModifyMatrix.Show(lambdaSub);
                            if (matrixEditor.FinishedInput)
                                ApplyAction(String.Format("S\"{0}\"M{1} {2} {3} ", lambdaSub.Name, matrixEditor.Choices[0], matrixEditor.Choices[1], matrixEditor.Choices[2]));
                        });

                    AddToCell(MainGrid, 0, i, new TextBlock
                    {
                        Text = "[del] ",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
                        ToolTip = "Click to delete substitute"
                    }).MouseDown += (sender, args) => ApplyAction(String.Format("DS\"{0}\" ", lambdaSub.Name));
                }
            }

            AddCell(TopGrid, "D", 1, 0, "Days Scheduled", null);
            AddCell(TopGrid, "S", 1, 1, "Days Scheduled", null);

            for (var i = 0; i < Week.Substitutes.Count; ++i)
                AddCell(MainGrid, CountSubstituteScheduledDays(Week, Week.Substitutes[i].Name).ToString(), 1, i, "", null);

            for (var i = Week.Substitutes.Count; i < maxRows; ++i)
                AddCell(MainGrid, "", 1, i, "", null);

                AddCell(TopGrid, "Routes", 2, 0, "All routes");
            AddCell(TopGrid, "", 2, 1, null);
            for (var i = 0; i < maxRows; ++i)
            {
                if (i > Week.Regulars.Count)
                    AddCell(MainGrid, "", 2, i, "", null);
                else if (i >= Week.Regulars.Count)
                    AddCell(MainGrid, "+ new regular/route", 2, i, "Click to add regular", () =>
                    {
                        var creator = CreateRegular.Show();
                        if (creator.FinishedInput)
                            ApplyAction(String.Format("R\"{0}\"{1} ", creator.Name, creator.Route));
                    });
                else
                {
                    var lambdaR = Week.Regulars[i];
                    AddCell(MainGrid, lambdaR.ToString(), 2, i, null);

                    AddToCell(MainGrid, 2, i, new TextBlock
                    {
                        Text = "[del] ",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
                        ToolTip = "Click to delete regular / route"
                    }).MouseDown += (sender, args) => ApplyAction(String.Format("DR\"{0}\" ", lambdaR.Name));
                }
            }

            for (var x = 3; x < 10; ++x)
            {
                var currentDay = Week.DailySchedules[x - 3];
                var dayIndex = x - 3;
                AddCell(TopGrid, ((DayOfWeek)dayIndex).ToString() + " - " + OffsetDateString(dayIndex) + (currentDay.IsHoliday ? " - HOLIDAY" : ""), x, 0, null);

                var localReliefDays = new List<LeaveEntry>(Week.DailySchedules[dayIndex].ReliefDays);

                if (localReliefDays.Count >= Week.Substitutes.Count)
                    AddCell(TopGrid, "FULL", x, 1, null);
                else
                    AddCell(TopGrid, String.Format("SUBS:{0}", Week.Substitutes.Count - localReliefDays.Count), x, 1, null);

                AddToCell(TopGrid, x, 1, new TextBlock
                {
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
                    Text = (currentDay.IsHoliday ? "[clear holiday]" : "[make holiday]"),
                }).MouseDown += (sender, args) =>
                    {
                        if (currentDay.IsHoliday) ApplyAction(String.Format("DH{0} ", Constants.DayNames[dayIndex]));
                        else ApplyAction(String.Format("H{0} ", Constants.DayNames[dayIndex]));
                    };

                var rowIndex = 0;

                if (dayIndex == 1 || currentDay.IsHoliday)
                {
                    var sundayRoutes = new List<LeaveEntry>(localReliefDays.Where(rd => rd.LeaveType == "SUNDAY"));
                    foreach (var sundayRoute in sundayRoutes)
                    {
                        localReliefDays.Remove(sundayRoute);
                        AddLeaveEntryCell(sundayRoute, LeaveCellType.Sunday, x, rowIndex);
                        rowIndex += 1;
                    }

                    while (rowIndex < CurrentWeek.Regulars.Count)
                    {
                        AddCell(MainGrid, "", x, rowIndex, null);
                        rowIndex += 1;
                    }

                    foreach (var regular in Week.Regulars)
                    {
                        var reliefDay = localReliefDays.Find(r => r.Carrier == regular.Name);
                        if (reliefDay != null)
                            localReliefDays.Remove(reliefDay);
                    }
                }
                else
                {
                    foreach (var regular in Week.Regulars)
                    {
                        var reliefDay = localReliefDays.Find(r => r.Carrier == regular.Name);
                        if (reliefDay == null)
                            AddCell(MainGrid, "", x, rowIndex, "Click to add leave", () =>
                                {
                                    var leaveSelector = SimpleSelector.Show("Select leave type", Constants.AllLeaveTypes.Select(c => (object)c));
                                    if (leaveSelector.SelectionMade)
                                        ApplyAction(String.Format("L\"{0}\"{1}{2} ",
                                            regular.Name, Constants.DayNames[dayIndex], leaveSelector.SelectedItem));
                                });
                        else
                        {
                            AddLeaveEntryCell(reliefDay, LeaveCellType.Regular, x, rowIndex);
                            localReliefDays.Remove(reliefDay);
                        }

                        rowIndex += 1;
                    }
                }

                foreach (var rDay in localReliefDays)
                {
                    AddLeaveEntryCell(rDay, LeaveCellType.Sub, x, rowIndex);
                    rowIndex += 1;
                }

                AddCell(MainGrid, "+ substitute leave", x, rowIndex, "Add leave for a substitute", () =>
                    {
                        var leaveSelector = SimpleSelector.Show("Select leave type", Constants.AllLeaveTypes.Select(c => (object)c));
                        if (leaveSelector.SelectionMade)
                        {
                            var carrierSelector = SimpleSelector.Show("Select carrier", EnumerateAllCarriers().Select(c => (object)c));
                            if (carrierSelector.SelectionMade)
                                ApplyAction(String.Format("L\"{0}\"{1}{2} ",
                                    carrierSelector.SelectedItem, Constants.DayNames[dayIndex], leaveSelector.SelectedItem));
                        }
                    });
                rowIndex += 1;

                while (rowIndex < approvedLeaveRows)
                {
                    AddCell(MainGrid, "", x, rowIndex, null);
                    rowIndex += 1;
                }

                AddCell(MainGrid, "DENIED LEAVE", x, rowIndex, null);
                rowIndex += 1;

                foreach (var rDay in CurrentWeek.DailySchedules[dayIndex].DeniedLeave)
                {
                    AddLeaveEntryCell(rDay, LeaveCellType.Denied, x, rowIndex);
                    rowIndex += 1;
                }

                AddCell(MainGrid, "+ denied leave", x, rowIndex, "Add denied leave", () =>
                    {
                        var leaveSelector = SimpleSelector.Show("Select leave type", Constants.AllLeaveTypes.Select(c => (object)c));
                        if (leaveSelector.SelectionMade)
                        {
                            var carrierSelector = SimpleSelector.Show("Select carrier", EnumerateAllCarriers().Select(c => (object)c));
                            if (carrierSelector.SelectionMade)
                                ApplyAction(String.Format("LD\"{0}\"{1}{2} ",
                                    carrierSelector.SelectedItem, Constants.DayNames[dayIndex], leaveSelector.SelectedItem));
                        }
                    });

                rowIndex += 1;

                while (rowIndex < maxRows)
                {
                    AddCell(MainGrid, "", x, rowIndex, null);
                    rowIndex += 1;
                }

            }

            UpdateMouseHilite();
            this.InvalidateVisual();
        }
Beispiel #9
0
 private void nextButton_Click(object sender, RoutedEventArgs e)
 {
     bool error = false;
     currentPageIndex++;
     if (contentFrame.Content is UniverstyChoicePage)
     {
         selectedUniversities = (contentFrame.Content as UniverstyChoicePage).SelectedUniversitiesList;
         if (selectedUniversities.Count < 2)
         {
             error = true;
             Xceed.Wpf.Toolkit.MessageBox.Show("test błędu");
         }
     }
     else if (contentFrame.Content is CryteriaChoicePage)
     {
         selectedCryteria = (contentFrame.Content as CryteriaChoicePage).SelectedCryteriaList;
         Cryteria cryt = selectedCryteria.Find(c => c.ID == Cryteria.FREE_UNIVERSITY_CRYTERIA);
         skipWrongUniversities = cryt == null;
         if (!skipWrongUniversities)
         {
             wrongUniversities = new List<University>();
             foreach (University u in selectedUniversities)
             {
                 string value = DBConnection.GetCryteriaValueForUniversity(u.ID, cryt.ID);
                 double val = Convert.ToDouble(value);
                 if (val == 1)
                     wrongUniversities.Add(u);
             }
             skipWrongUniversities = wrongUniversities.Count == 0;
             if (skipWrongUniversities)
                 currentPageIndex++;
         }
         else
             currentPageIndex++;
         if (skipWrongUniversities)
         {
             cryt = selectedCryteria.Find(c => c.ID == Cryteria.CITY_DISTANCE_CRYTERIA);
             skipDistances = cryt == null;
             if (skipDistances)
                 currentPageIndex++;
         }
     }
     else if (contentFrame.Content is NotFreeUniversitiesPage)
     {
         if ((contentFrame.Content as NotFreeUniversitiesPage).GetNoWrong())
             selectedUniversities.RemoveAll(u => wrongUniversities.Contains(u));
         else
             lowerRatingForWrong = true;
         Cryteria cryt = selectedCryteria.Find(c => c.ID == Cryteria.CITY_DISTANCE_CRYTERIA);
         skipDistances = cryt == null;
         if (skipDistances)
             currentPageIndex++;
     }
     else if (contentFrame.Content is GeoLocalizationPage)
     {
         (contentFrame.Content as GeoLocalizationPage).SetDistanceFromAddressInUniversities();
         reverseDistance = (contentFrame.Content as GeoLocalizationPage).GetReverseDistance();
     }
     else if (contentFrame.Content is CryteriaEvaluationPage)
     {
         cryteriaEvaluationMatrix = (contentFrame.Content as CryteriaEvaluationPage).GetCryteriaEvaluationMatrix();
         Xceed.Wpf.Toolkit.MessageBox.Show(cryteriaEvaluationMatrix.CheckConsistency().ToString());
     }
     if (currentPageIndex < pageList.Count && !error)
     {
         Page page = pageList.ElementAt(currentPageIndex);
         if (page is CryteriaEvaluationPage)
             (page as CryteriaEvaluationPage).Init(selectedCryteria);
         else if (page is NotFreeUniversitiesPage && wrongUniversities.Count > 0)
             (page as NotFreeUniversitiesPage).Init(selectedUniversities, wrongUniversities);
         else if (page is GeoLocalizationPage)
             (page as GeoLocalizationPage).Init(selectedUniversities);
         contentFrame.Content = page;
         Title = (pageList.ElementAt(currentPageIndex) as Page).Title;
     }
     else if (error)
     {
         currentPageIndex--;
     }
     backButton.IsEnabled = currentPageIndex > 0;
     nextButton.IsEnabled = currentPageIndex < pageList.Count;
 }
Beispiel #10
0
 CUSInfo FindUSInfo(List<CUSInfo> usinfolist, int pipeId)
 {
     CUSInfo info = null;
     info = usinfolist.Find(us => us.PipeID == pipeId);
     return info;
 }
Beispiel #11
0
        private void Generatebtn_Click(object sender, RoutedEventArgs e)
        {
            this.listView2.UpdateLayout();
            //##################################################################################
            //Inatialize Result tab
            //##################################################################################

            //Get Parameter
            List<Microsoft.Test.VariationGeneration.Parameter> listP = new List<Microsoft.Test.VariationGeneration.Parameter>();
            foreach (VariationDataSource.Variation v in Variations)
            {
                string[] values = v.Value.Replace(",", ",").Split(',');

                var P = new Microsoft.Test.VariationGeneration.Parameter(v.Parameter.Trim()) { };
                foreach (string value in values)
                {
                    Double isnumber;
                    if (value.Contains("(") && value.Contains(")") && Double.TryParse(substring(value,"(",")"),out isnumber))
                    {
                        P.Add(new ParameterValue(value.Substring(0, value.IndexOf("("))) { Weight = Convert.ToDouble(substring(value,"(",")")) });
                    }
                    else
                    {
                        P.Add(value.Trim());
                    }

                }
                listP.Add(P);
            }

            //Get Model
            Model model = null;
            int count = this.listBox3.Items.Count;
            if (count == 0)
            {
                model = new Model(listP);
            }
            else
            {
                //Get constraints
                var constraints = new List<Microsoft.Test.VariationGeneration.Constraint> { };
                for (int i = 0; i < count; i++)
                {
                    string constain = this.listBox3.Items[i].ToString();
                    string if_constrain = substring(constain, "If","Then").Trim();
                    string ifparametername = substring(if_constrain, "[", "]");
                    string ifvaluename = substring(if_constrain, "\"", "\"");
                    string if_express = substring(if_constrain, "]", "\"");
                    Microsoft.Test.VariationGeneration.Parameter if_p = listP.Find(p => p.Name.Equals(ifparametername));
                    string then_constrain = constain.Substring(constain.IndexOf("Then"));
                    string thenparametername = substring(then_constrain, "[", "]");
                    string thenvaluename = substring(then_constrain, "\"", "\"");
                    string then_express = substring(then_constrain, "]", "\"");
                    Microsoft.Test.VariationGeneration.Parameter then_p = listP.Find(p => p.Name.Equals(thenparametername));

                    //Judge if Parameters in listview1 contain ifparametername and thenparametername, if not , the constaint is not valid
                    StringBuilder builder = new StringBuilder();
                    foreach (VariationDataSource.Variation v in Variations)
                    {
                        builder.Append(v.Parameter + " ");
                    }
                    if (builder.ToString().Contains(ifparametername) && builder.ToString().Contains(thenparametername))
                    {
                        IfThenConstraint ifthen = new IfThenConstraint(){};
                        //############################################################################
                        //if_constrain
                        //############################################################################
                        if (if_constrain.Contains("And") || if_constrain.Contains("Or"))
                        {
                            string[] if_constrains = if_constrain.Replace("And", "_And").Replace("Or","_Or").Split('_');
                            List<string> if_constrainslist = if_constrains.ToList<string>();

                            ConditionConstraint _if;

                            string ifparname_Fir = substring(if_constrainslist[0], "[", "]");
                            string ifvalname_Fir = substring(if_constrainslist[0], "\"", "\"");
                            string if_exp_Fir = substring(if_constrainslist[0], "]", "\"");
                            Microsoft.Test.VariationGeneration.Parameter if_par_Fir = listP.Find(p => p.Name.Equals(ifparname_Fir));

                            if (if_exp_Fir == "is")
                            {
                                _if = if_par_Fir.Equal(ifvalname_Fir);

                            }
                            else
                            {
                                _if = if_par_Fir.NotEqual(ifvalname_Fir);
                            }
                            if_constrainslist.RemoveAt(0);
                            foreach (string if_constraint in if_constrainslist)
                            {
                               string ifparname = substring(if_constraint, "[", "]");
                               string ifvalname = substring(if_constraint, "\"", "\"");
                               string if_exp = substring(if_constraint, "]", "\"");
                               Microsoft.Test.VariationGeneration.Parameter if_par = listP.Find(p => p.Name.Equals(ifparname));
                               if(if_constraint.Trim().StartsWith("And"))
                               {

                                    if (if_exp == "is")
                                    {
                                        _if = _if.And(if_par.Equal(ifvalname));

                                    }
                                    else
                                    {
                                          _if = _if.And(if_par.NotEqual(ifvalname));
                                    }

                               }
                               if(if_constraint.Trim().StartsWith("Or"))
                               {

                                    if (if_exp == "is")
                                    {
                                        _if = _if.Or(if_par.Equal(ifvalname));

                                    }
                                    else
                                    {
                                        _if = _if.Or(if_par.NotEqual(ifvalname));
                                    }

                               }

                            }

                            ifthen.If = _if;

                        }
                        else
                        {
                            if (if_express == "is")
                            {
                                ifthen.If = if_p.Equal(ifvaluename);

                            }
                            else
                            {
                                ifthen.If = if_p.NotEqual(ifvaluename);
                            }

                        }
                        //############################################################################
                        //############################################################################

                        //############################################################################
                        //Then_constrain
                        //############################################################################
                        if (then_constrain.Contains("And") || then_constrain.Contains("Or"))
                        {
                            string[] then_constrains = then_constrain.Replace("And", "_And").Replace("Or", "_Or").Split('_');
                            List<string> then_constrainslist = then_constrains.ToList<string>();

                            ConditionConstraint _then;

                            string thenparname_Fir = substring(then_constrainslist[0], "[", "]");
                            string thenvalname_Fir = substring(then_constrainslist[0], "\"", "\"");
                            string then_exp_Fir = substring(then_constrainslist[0], "]", "\"");
                            Microsoft.Test.VariationGeneration.Parameter then_par_Fir = listP.Find(p => p.Name.Equals(thenparname_Fir));

                            if (then_exp_Fir == "is")
                            {
                                _then = then_par_Fir.Equal(thenvalname_Fir);

                            }
                            else
                            {
                                _then = then_par_Fir.NotEqual(thenvalname_Fir);
                            }
                            then_constrainslist.RemoveAt(0);
                            foreach (string then_constraint in then_constrainslist)
                            {
                                string thenparname = substring(then_constraint, "[", "]");
                                string thenvalname = substring(then_constraint, "\"", "\"");
                                string then_exp = substring(then_constraint, "]", "\"");
                                Microsoft.Test.VariationGeneration.Parameter then_par = listP.Find(p => p.Name.Equals(thenparname));
                                if (then_constraint.Trim().StartsWith("And"))
                                {

                                    if (then_exp == "is")
                                    {
                                        _then = _then.And(then_par.Equal(thenvalname));

                                    }
                                    else
                                    {
                                        _then = _then.And(then_par.NotEqual(thenvalname));
                                    }

                                }
                                if (then_constraint.Trim().StartsWith("Or"))
                                {

                                    if (then_exp == "is")
                                    {
                                        _then = _then.Or(then_par.Equal(thenvalname));

                                    }
                                    else
                                    {
                                        _then = _then.Or(then_par.NotEqual(thenvalname));
                                    }
                                }
                            }
                            ifthen.Then = _then;
                        }
                        else
                        {
                            if (then_express == "is")
                            {
                                ifthen.Then = then_p.Equal(thenvaluename);
                            }
                            else
                            {
                                ifthen.Then = then_p.NotEqual(thenvaluename);
                            }
                        }
                        //############################################################################
                        //############################################################################

                        constraints.Add(ifthen);
                    }

                }
                model = new Model(listP, constraints);
            }

            System.Collections.ArrayList objects = new System.Collections.ArrayList();
            var variations = model.GenerateVariations(Convert.ToInt32(this.ComboBox1.SelectedValue), 12345);

            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("ID"));
            int t = 1;
            foreach (var v in variations)
            {
                //Add columns
                foreach (var value in v)
                {

                    if (!table.Columns.Contains(value.Key))
                    {
                        table.Columns.Add(new DataColumn(value.Key));
                    }

                }

                //Add the numbet of ID
                objects.Add(t);
                t++;

                //Add Rows
                foreach (var value in v)
                {
                    objects.Add(value.Value);

                }
                table.Rows.Add(objects.ToArray());
                objects.Clear();

            }

            viewmodel.QueryResult = table;

            this.listView2.UpdateLayout();
            this.Exportbutton.IsEnabled = this.listView2.HasItems;
        }
Beispiel #12
0
        private void Calculate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<priceList> list = new List<priceList>();

                for (int i = 0; i < row; i++)
                {
                    var textbox = (TextBox)OrderItemGrid.Children.Cast<UIElement>().First(e1 => Grid.GetRow(e1) == i && Grid.GetColumn(e1) == 1);
                    var quantity = (TextBox)OrderItemGrid.Children.Cast<UIElement>().First(e1 => Grid.GetRow(e1) == i && Grid.GetColumn(e1) == 3);

                    int item;
                    int intquantity;

                    Int32.TryParse(textbox.Text.ToString(), out item);
                    Int32.TryParse(quantity.Text.ToString(), out intquantity);

                    if (item != 0 && intquantity != 0)
                    {
                        var t = list.Find(item1 => item1.id.Equals(item));
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals(item.ToString()));

                        if (t == null)
                        {
                            priceList pc = new priceList();
                            pc.id = item;
                            pc.quantity = intquantity;
                            pc.price = pc.quantity * Double.Parse(priceTem.Price);

                            list.Add(pc);
                        }
                        else
                        {
                            t.quantity += intquantity;
                            t.price = t.quantity * Double.Parse(priceTem.Price);
                        }
                    }
                }

                double fivePercent;
                double tenPercent;
                double fifteenPercent;
                double twentyPercent;

                double largest = 0;
                string reason = "";

                if (row == 0 || list.Count() == 0)
                    return;

                if (DiscountSchema.Content.Equals("Single Highest Schema"))
                {
                    //5% off if you buy 2 iphone 6 –“Iphone 6 Discount”
                    var temp = list.Find(item1 => item1.id.Equals(1));

                    if (temp.quantity == 2)
                    {
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals("1"));

                        fivePercent = (5 * temp.quantity * Int32.Parse(priceTem.Price)) / 100;
                        largest = fivePercent;
                        reason = "Iphone 6 Discount";
                    }

                    //10% off if its customers birthday on the day of ordering any product. – “Birthday Discount”

                    DateTime today = DateTime.Today;

                    int monthdiff = currentUser.Birthday.Month - today.Month;

                    int daydiff = currentUser.Birthday.Day - today.Day;

                    int yearDiff = currentUser.Birthday.Year - today.Year;

                    double sum = list.Sum(item => item.price);

                    if (monthdiff == 0 && daydiff == 0 && yearDiff != 0)
                    {
                        tenPercent = (10 * sum) / 100;

                        if (tenPercent > largest)
                        {
                            largest = tenPercent;
                            reason = "Birthday Discount";
                        }
                    }

                    //15% off if customer is more than 50 years old  - “Senior Citizen Discount”

                    if (yearDiff > 50)
                    {
                        fifteenPercent = (15 * sum) / 100;

                        if (fifteenPercent > largest)
                        {
                            largest = fifteenPercent;
                            reason = "Senior Citizen Discount";
                        }
                    }

                    //20% off if order total is more than £3000 – “High Value Order Discount”

                    if (sum > 3000)
                    {
                        twentyPercent = (20 * sum) / 100;

                        if (twentyPercent > largest)
                        {
                            largest = twentyPercent;
                            reason = "High Value Order Discount";
                        }
                    }

                    DisList.Text = reason + "\n " + "Single Highest Schema";
                    DisPrice.Text = (sum - largest).ToString();
                }
                else
                {
                    fifteenPercent = 0;
                    tenPercent = 0;
                    fivePercent = 0;
                    twentyPercent = 0;

                    //5% off if you buy 2 iphone 6 –“Iphone 6 Discount”
                    var temp = list.Find(item1 => item1.id.Equals(1));

                    if (temp.quantity == 2)
                    {
                        var priceTem = DataStore.Store.AllProduct.Find(item1 => item1.ID.Equals("1"));

                        fivePercent = (5 * temp.quantity * Int32.Parse(priceTem.Price)) / 100;
                        //largest = fivePercent;
                        reason = "Iphone 6 Discount";
                    }

                    //10% off if its customers birthday on the day of ordering any product. – “Birthday Discount”

                    DateTime today = DateTime.Today;

                    int monthdiff = currentUser.Birthday.Month - today.Month;

                    int daydiff = currentUser.Birthday.Day - today.Day;

                    int yearDiff = currentUser.Birthday.Year - today.Year;

                    double sum = list.Sum(item => item.price);

                    if (monthdiff == 0 && daydiff == 0 && yearDiff != 0)
                    {
                        tenPercent = (10 * sum) / 100;

                        reason += " \n Birthday Discount";
                    }

                    //15% off if customer is more than 50 years old  - “Senior Citizen Discount”

                    if (yearDiff > 50)
                    {
                        fifteenPercent = (15 * sum) / 100;

                        reason += " \n Senior Citizen Discount";
                    }

                    //20% off if order total is more than £3000 – “High Value Order Discount”

                    if (sum > 3000)
                    {
                        twentyPercent = (20 * sum) / 100;

                        reason += " \n High Value Order Discount";
                    }

                    DisList.Text = reason + "\n " + "Multiple Discount Schema";
                    DisPrice.Text = (sum - (fivePercent + tenPercent + fifteenPercent + twentyPercent)).ToString();
                }

                string originalPrice = "";

                foreach (priceList pl in list)
                {
                    originalPrice += "Item no " + pl.id + " cost is " + pl.price;
                }

                OriPrice.Text = originalPrice;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Try Again");
            }
        }
        /// <summary>
        /// Constructeur par défaut de la classe.
        /// </summary>
        public FenetreGenerateurMenus()
        {
            CultureManager.UICultureChanged += CultureManager_UICultureChanged;

            InitializeComponent();

            Rand = new Random();

            App.Current.MainWindow.ResizeMode = ResizeMode.CanResize;

            AlimentService = ServiceFactory.Instance.GetService<IAlimentService>();
            PlatService = ServiceFactory.Instance.GetService<IPlatService>();
            SuiviPlatService = ServiceFactory.Instance.GetService<ISuiviPlatService>();
            MenuService = ServiceFactory.Instance.GetService<IMenuService>();

            // Chargement des plats.
            Mouse.OverrideCursor = Cursors.Wait;
            ListeDejeuners = new List<Plat>(PlatService.RetrieveSome(new RetrievePlatArgs { Categorie = "Déjeuner" }));
            ListeEntrees = new List<Plat>(PlatService.RetrieveSome(new RetrievePlatArgs { Categorie = "Entrée" }));
            ListePlatPrincipaux = new List<Plat>(PlatService.RetrieveSome(new RetrievePlatArgs { Categorie = "Plat principal" }));
            ListeBreuvages = new List<Plat>(PlatService.RetrieveSome(new RetrievePlatArgs { Categorie = "Breuvage" }));
            ListeDesserts = new List<Plat>(PlatService.RetrieveSome(new RetrievePlatArgs { Categorie = "Déssert" }));
            ListePlatsRetires = new List<Plat>();
            Mouse.OverrideCursor = null;

            // Header de la fenêtre.
            App.Current.MainWindow.Title = Nutritia.UI.Ressources.Localisation.FenetreGenerateurMenus.Titre;

            if (!String.IsNullOrEmpty(App.MembreCourant.NomUtilisateur))
            {
                btnSuiviPlatsNonAdmissibles.IsEnabled = true;
                btnOuvrirMenu.IsEnabled = true;
                RestreindrePossibilites();
                List<Plat> ListePlatsSuivis = new List<Plat>(SuiviPlatService.RetrieveSome(new RetrieveSuiviPlatArgs { IdMembre = (int)App.MembreCourant.IdMembre }));

                if (ListePlatsSuivis.Count == 0)
                {
                    SuiviPlatService.Insert(ListePlatsRetires, App.MembreCourant);
                }
                else
                {
                    foreach (Plat platCourant in ListePlatsRetires)
                    {
                        if (ListePlatsSuivis.Find(plat => plat.Nom == platCourant.Nom) != null)
                        {
                            platCourant.EstTricherie = ListePlatsSuivis.Find(plat => plat.Nom == platCourant.Nom).EstTricherie;

                            if (platCourant.EstTricherie)
                            {
                                switch (platCourant.TypePlat)
                                {
                                    case "Déjeuner":
                                        ListeDejeuners.Add(platCourant);
                                        break;
                                    case "Entrée":
                                        ListeEntrees.Add(platCourant);
                                        break;
                                    case "Plat principal":
                                        ListePlatPrincipaux.Add(platCourant);
                                        break;
                                    case "Breuvage":
                                        ListeBreuvages.Add(platCourant);
                                        break;
                                    case "Déssert":
                                        ListeDesserts.Add(platCourant);
                                        break;
                                }
                            }
                        }
                    }

                    SuiviPlatService.Update(ListePlatsRetires, App.MembreCourant);

                }
            }

            EstNouveauMenu = true;
            NbColonnes = NB_COLONNES_AVEC_IMAGES;
        }
Beispiel #14
0
        private void FillGridWithInfo()//Fetching info for each cell of Info grid and placing it there
        {
            int rows = WeekGrid.Rows;//we will need row and column number to properly placing info into the grid;
            int columns = WeekGrid.Columns;
            List<Group> searchresult = new List<Group>();

            foreach (ListView listView in WeekGrid.Children)
            {

                int index = WeekGrid.Children.IndexOf(listView);
                int row = index / columns;
                int column = index % columns;

                searchresult = groups.FindAll(delegate(Group group)//Looking up if there are ny group for at this date;
                {
                    DateTime weekday = GetStartOfCurrentWeek().AddDays(column);
                    return group.Date == weekday;
                });

                if (!searchresult.Any())//If there are none - setting empty labels.
                {
                    for (int i = 0; i < listView.Items.Count; i++)
                    {
                        ((Label)listView.Items[i]).Content = " ";
                        ((Label)listView.Items[i]).Tag = null;
                        ((Label)listView.Items[i]).Background = Brushes.White;
                    }
                }
                else if (searchresult.Any())//If there are any - we narrow search further to timeperiod.
                {
                    searchresult = searchresult.FindAll(delegate(Group gp)
                    {
                        timeperiod time = (timeperiod)row;
                        return gp.Time == time;
                    });

                    if (!searchresult.Any())//If there are none, we again set all to empty;
                    {
                        for (int i = 0; i < listView.Items.Count; i++)
                        {
                            ((Label)listView.Items[i]).Content = " ";
                            ((Label)listView.Items[i]).Tag = null;
                            ((Label)listView.Items[i]).Background = Brushes.White;
                        }
                    }
                    else if (searchresult.Any())//And if there are any we set them to appropriate posistions in list;
                    {
                        for (int i = 0; i < listView.Items.Count; i++)//we go through all labels on Listview
                        {
                            Group target = searchresult.Find(delegate(Group gp)//And see if there is group for this label
                            {//to be displayed
                                return gp.Room.Id == i + 1;//We check it by room id, because each label corresponds to unique room;
                            });
                            if (target != null)//If we get some result 
                            {
                                ((Label)listView.Items[target.Room.Id - 1]).Tag = target;//We place this group there
                                ((Label)listView.Items[target.Room.Id - 1]).Content = target.Room.Type + ": " +target.Name;
                                ((Label)listView.Items[i]).Background = Brushes.LightSeaGreen;//And display with text and color;
                            }
                            else
                            {
                                ((Label)listView.Items[i]).Content = " ";//Again if there is nothing - setting all to empty;
                                ((Label)listView.Items[i]).Tag = null;
                                ((Label)listView.Items[i]).Background = Brushes.White;
                            }

                        }


                    }
                }
            }
        }
        private void Generar(object sender, RoutedEventArgs e)
        {
            ventas = new List<Venta>();
            DateTime inicio = Convert.ToDateTime(FechaDesde.Text);
            DateTime fin =Convert.ToDateTime(FechaHasta.Text);

            List<Venta> ventaAux1 = new List<Venta>();
            List<Venta> ventaAux2 = new List<Venta>();
            List<Venta> ventaAux3 = new List<Venta>();
            List<Venta> ventaAux4 = new List<Venta>();
            List<string> tiendas = new List<string>();
            List<string> clientes = new List<string>();
            List<string> productos = new List<string>();
            List<int> lista = new List<int>();

            for (int i = 0; i < ListBoxSede2.Items.Count; i++)
            {
                tiendas.Add(ListBoxSede2.Items[i].ToString());
                ventaAux1 = DataObjects.Reportes.ReporteVentasSQL.BuscarVentaxTienda(tiendas[i]);
                for (int j = 0; j < ventaAux1.Count; j++)
                {
                    ventas.Add(ventaAux1[j]);
                }
            }

            for (int i = 0; i < ListBoxCliente2.Items.Count; i++)
            {
                clientes.Add(ListBoxCliente2.Items[i].ToString());
                ventaAux2 = DataObjects.Reportes.ReporteVentasSQL.BuscarVentaxCliente(clientes[i]);
                for (int j = 0; j < ventaAux2.Count; j++)
                {
                    ventas.Add(ventaAux2[j]);
                }
            }

            for (int i = 0; i < ListBoxProducto2.Items.Count; i++)
            {
                productos.Add(ListBoxProducto2.Items[i].ToString());
                ventaAux3 = DataObjects.Reportes.ReporteVentasSQL.BuscarVentaxProducto(productos[i]);
                for (int j = 0; j < ventaAux3.Count; j++)
                {
                    ventas.Add(ventaAux3[j]);
                }
            }

            Venta vAux;
            Venta vAux2;
            for (int i = 0; i < ventas.Count; i++)
            {
                vAux = ventas[i];
                if (i != ventas.Count) ventas.RemoveAt(i);
                if ((vAux = ventas.Find(x => x.IdVenta == vAux.IdVenta)) != null)
                {
                    vAux2 = vAux;
                    if ((vAux2 = ventaAux4.Find(x => x.IdVenta == vAux2.IdVenta)) == null)
                        ventaAux4.Add(vAux);
                }
            }

            for (int i = 0; i < ventaAux4.Count; i++)
            {
                if (ventaAux4[i].FechaReg < inicio || ventaAux4[i].FechaReg > fin)
                {
                    ventaAux4.RemoveAt(i);
                    i = -1;
                }
            }
            for (int i = 0; i < ventaAux4.Count; i++)
            {

                for (int j = 0; j < lstCliente.Count; j++)
                {
                    if (lstCliente[j].Id == ventaAux4[i].IdCliente) ventaAux4[i].NombreCliente = lstCliente[j].Nombre;
                }
            }

            List<VentaAux> final = new List<VentaAux>();

            for (int i = 0; i < ventaAux4.Count; i++)
            {
                final.Add(new VentaAux());
                final[i].CodTarjeta = ventaAux4[i].CodTarjeta;
                final[i].Descuento = ventaAux4[i].Descuento;
                final[i].Estado  = ventaAux4[i].Estado;
                final[i].EstadoS = ventaAux4[i].EstadoS;
                final[i].FechaDespacho = ventaAux4[i].FechaDespacho;
                final[i].FechaMod = ventaAux4[i].FechaMod;
                final[i].FechaReg = ventaAux4[i].FechaReg;
                final[i].FechaRegS = ventaAux4[i].FechaRegS;
                final[i].IdCliente = ventaAux4[i].IdCliente;
                final[i].IdUsuario = ventaAux4[i].IdUsuario;
                final[i].IdVenta = ventaAux4[i].IdVenta;
                final[i].Igv = ventaAux4[i].Igv;
                final[i].Monto = ventaAux4[i].Monto;
                final[i].NombreCliente = ventaAux4[i].NombreCliente;
                final[i].NumDocPago = ventaAux4[i].NumDocPago;
                final[i].NumDocPagoServicio = ventaAux4[i].NumDocPagoServicio;
                final[i].PtosGanados = ventaAux4[i].PtosGanados;
                final[i].TipoDocPago = ventaAux4[i].TipoDocPago;
                final[i].TipoVenta = ventaAux4[i].TipoVenta;

            }
                Reportes.reportViewerVentas neva = new reportViewerVentas(final);
                neva.Show();
        }
 // Get ratings from Master IPDB
 private void Button_Click_23(object sender, RoutedEventArgs e)
 {
     foreach (var item in tables_grid.SelectedItems)
     {
         if (item != null)
         {
             var t = item as Table;
             List<Table> m_tables = new List<Table>(master_tables);
             var value = m_tables.Find(itemFind => itemFind.Description.ToUpper() == t.Description.ToUpper());
             if (value != null)
                 t.Rating = value.Rating;
         }
     }
 }
		void BindData(List<Profile> plst, ProfileToken tok) {
			plst.ForEach(x =>
				profCollection.Add(x)
				);

			//profilesList.ItemsSource = profCollection;
			//profilesList.DisplayMemberPath = "Name";
			
			profilesList.SelectionChanged += (object sender, SelectionChangedEventArgs e) => {
                if (profilesList.SelectedItem != null)
                {
                    if (profilesList.SelectedItem == currentProf || ((Profile)profilesList.SelectedItem).@fixed)
                        deleteSelected.IsEnabled = false;
                    else
                        deleteSelected.IsEnabled = true;
                }
                else
                {
                    deleteSelected.IsEnabled = false;
                }
			};
			
			try {
				currentProf = plst.Find(x => x.token == tok);
				selectedProf = currentProf;
				profilesList.SelectedItem = currentProf;
			} catch (Exception err) {
				dbg.Error(err);
			}
		}
        private void lv_dropdetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {

                if (e.AddedItems.Count > 0)
                {
                    GetUndeclaredVaultDrops vd_select = e.AddedItems[0] as GetUndeclaredVaultDrops;
                    if (vd_select != null)
                    {

                        if (vd_select.Cassettes != null && vd_select.Cassettes.Count > 0)
                        {
                            lst_cassettes = vd_select.Cassettes;
                            if (Settings.AutoFillDeclaredAmount)
                            {
                                foreach (CassetteDropsResult casette in vd_select.Cassettes)
                                {
                                    casette.DeclaredBalance = casette.VaultBalance.Value;
                                    if (casette.EnableControls)
                                    {
                                        casette.Quantity = Convert.ToInt32(Math.Truncate(casette.DeclaredBalance / Convert.ToDecimal(casette.Denom.Value)));
                                    }

                                }
                            }

                            p_cassette = lst_cassettes.Find(obj => obj.CassetteType_ID == (int)CassetteTypes.Cassette && !obj.EnableControls);
                            p_hopper = lst_cassettes.Find(obj => obj.CassetteType_ID == (int)CassetteTypes.Hopper && !obj.EnableControls);

                            if (lst_cassettes.FindAll(obj => obj.CassetteType_ID == (int)CassetteTypes.Cassette).Count == 0)
                            {
                                btnStart.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                btnStart.Visibility = Visibility.Visible;

                            }

                            lv_CassetteDetails.ItemsSource = lst_cassettes;
                            if (!vd_select.IsEmptyCassette)
                            {
                                vd_select.IsEmptyCassette = false;
                            }
                            vd_select.Declared_Balance = (p_cassette != null ? p_cassette.DeclaredBalance : 0) + (p_hopper != null ? p_hopper.DeclaredBalance : 0);
                        }
                        else
                        {
                            LoadEmptyCassette(vd_select);
                            if (lst_cassettes.FindAll(obj => obj.CassetteType_ID == (int)CassetteTypes.Cassette).Count == 0)
                            {
                                btnStart.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                btnStart.Visibility = Visibility.Visible;

                            }
                            vd_select.Declared_Balance = 0;
                            vd_select.IsEmptyCassette = true;
                        }
                        if (!vd_select.ToDeclared)
                        {
                            lblcounterWarning.Text = Application.Current.FindResource("Vault_MessageID16") as string;
                        }
                        else
                        {
                            lblcounterWarning.Text = "";
                        }
                        if (e.RemovedItems.Count > 0)
                        {
                            GetUndeclaredVaultDrops vd_removeselect = e.RemovedItems[0] as GetUndeclaredVaultDrops;
                            if (vd_removeselect != null)
                            {
                                if (vd_removeselect.Declared_Balance > 0 && vd_removeselect.ToDeclared)
                                {
                                    if ((Settings.ShowVaultConfirmMessage) && MessageBox.ShowBox("Vault_MessageID15", BMC_Icon.Information, BMC_Button.YesNo) == System.Windows.Forms.DialogResult.Yes)
                                    {
                                        lv_dropdetails.SelectionChanged -= lv_dropdetails_SelectionChanged;
                                        lv_dropdetails.SelectedItem = vd_removeselect;
                                        bool IsValidAmount = false;
                                        SaveVaultDeclaration(ref IsValidAmount);
                                        lv_dropdetails.SelectionChanged += lv_dropdetails_SelectionChanged;

                                        return;
                                    }
                                    else
                                    {
                                        foreach (CassetteDropsResult casette in vd_removeselect.Cassettes)
                                        {
                                            casette.Quantity = 0;
                                            casette.DeclaredBalance = 0;
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (CassetteDropsResult casette in vd_removeselect.Cassettes)
                                    {
                                        casette.Quantity = 0;
                                        casette.DeclaredBalance = 0;
                                    }

                                }

                            }

                            vd_removeselect.Declared_Balance = 0;

                        }

                        vd_select.BillsTotal = 0;
                        vd_select.TotalCoinsValueAsCurrency = 0;

                    }
                }
            }
            catch (Exception Ex)
            {
                ExceptionManager.Publish(Ex);
            }

        }
        private void LoopPhase2(List<FunctionBlock> blocks, List<Loop> loops)
        {
            /* Take loops in reverse order (inner loops are processed before outer loops */
            loops.Sort(LoopSortDesc);

            foreach (Loop loop in loops)
            {
                FunctionBlock lastBlock = loop.Blocks[loop.Blocks.Count - 1];

                CStatement doWhile = new CStatement();
                doWhile.Kind = CStatement.Kinds.DoWhile;

                doWhile.Condition = FindLastCondition(lastBlock.Statements);
                doWhile.SubBlocks = loop.Blocks;
                doWhile.BreakBlock = blocks[lastBlock.Id + 1];
                doWhile.ContinueBlock = lastBlock;

                doWhile.ExpandBlocks();

                if (doWhile.ContinueBlock.Statements.Count != 1)
                    doWhile.ContinueBlock = null;
                else
                {
                    CStatement stat = doWhile.ContinueBlock.Statements[0];
                    if (stat.Kind != CStatement.Kinds.Conditional)
                        doWhile.ContinueBlock = null;
                    else
                    {
                        if (stat.InnerBlock[0].BranchDestinationAddr != loop.Blocks[0].StartAddress)
                            doWhile.ContinueBlock = null;
                    }
                }

                /* Remove all blocks in the loop from the main block list. It is replaced by a single while block */
                int firstIndex = blocks.IndexOf(loop.Blocks[0]);
                FunctionBlock firstBlock = blocks[firstIndex];
                foreach (FunctionBlock b in loop.Blocks)
                    blocks.Remove(b);

                FunctionBlock fake = new FunctionBlock();
                fake.StartAddress = firstBlock.StartAddress;
                fake.InstrCount = 0;
                fake.Statements.Add(doWhile);

                loop.LoopBlock = fake;
                blocks.Insert(firstIndex, fake);

                StructureBreakContinue(doWhile, doWhile.ContinueBlock, doWhile.BreakBlock);
            }

            foreach (Loop loop in loops)
            {
                FunctionBlock precBlock = blocks.Find(delegate(FunctionBlock b) { return b.Id == loop.Blocks[0].Id - 1; });

                uint precedingBlockStart = precBlock.StartAddress;
                uint lastInstruction = precedingBlockStart + (precBlock.InstrCount - 1) * 4;
                uint offset = state.Pe.Rva2Offset(lastInstruction - (uint)state.Pe.optHdr.ImageBase);
                uint instruction = state.Pe.ReadInstruction(offset);
                XenonInstructions.OpCodeInfo info = state.Instructions.GetInfo(instruction);

                if (info.Id == XenonInstructions.Mnemonics.PPC_OP_B)
                {
                    uint bDest = (instruction & 0xFFFFFF) + lastInstruction;
                    if (bDest == loop.Header.StartAddress)
                    {
                        loop.LoopBlock.Statements[0].Kind = CStatement.Kinds.While;
                        precBlock.InstrCount--;
                        precBlock.Statements.RemoveAt(precBlock.Statements.Count - 1);
                    }
                }
            }

            foreach (Loop loop in loops)
            {
                int cnt = loop.LoopBlock.Statements[0].SubBlocks.Count;
                FunctionBlock last = loop.LoopBlock.Statements[0].SubBlocks[cnt - 1];
                loop.LoopBlock.Statements[0].SubBlocks.RemoveAt(cnt - 1);

                last.Statements.RemoveAt(0);
                if (last.Statements.Count != 0)
                {
                    blocks.Add(last);
                    blocks.Sort(Function.FunctionBlockSorter);
                }

                /* This will have removed some statements, reexpand the blocks */
                loop.LoopBlock.Statements[0].ExpandBlocks();
            }
        }
        private void UpdateGraphBosses(string subgraph)
        {
            SetGraphControl(ComparisonGraph);
            List<ComparisonCalculationBase> bossCalculations = new List<ComparisonCalculationBase>();
#if DEBUG
            DateTime start;
#endif
            BossList bosslist = new BossList();
            List<BossHandler> bosses = new List<BossHandler>();

            string filter = "All";

            // Determine which chart we are looking for. All will have the whole list, specific will just have that content in the list
            if (subgraph == "All (This is Slow to Calc)") {
                filter = "All";
            } else {
                filter = subgraph;
            }
            BossHandler[] calledList = bosslist.GenCalledList(BossList.FilterType.Content, filter);
            if (filter == "All") {
                bosses.Add(bosslist.TheEZModeBoss.Clone());
                bosses.Add(bosslist.TheAvgBoss.Clone());
                bosses.Add(bosslist.TheHardestBoss.Clone());
            } else {
                bosses.Add(bosslist.TheEZModeBoss_Called.Clone());
                bosses.Add(bosslist.TheAvgBoss_Called.Clone());
                bosses.Add(bosslist.TheHardestBoss_Called.Clone());
            }
            foreach (BossHandler bh in calledList) { bosses.Add(bh.Clone()); }
            BossHandler easy = bosses.Find(b => b.Name.Contains("Easy"));

            CGL_Legend.LegendItems = Calculations.SubPointNameColors;
            ComparisonGraph.LegendItems = Calculations.SubPointNameColors;
            ComparisonGraph.Mode = ComparisonGraph.DisplayMode.Subpoints;
#if DEBUG
            System.Diagnostics.Debug.WriteLine("Starting Boss Comparison Calculations");
            start = DateTime.Now;
#endif
            foreach (BossHandler bh in bosses)
            {
                bossCalculations.Add(Calculations.GetBossCalculations(bh, easy, Character, Calculations.GetCharacterCalculations(Character)));
            }
            ComparisonGraph.DisplayCalcs(_bossCalculations = bossCalculations.ToArray());
#if DEBUG
            System.Diagnostics.Debug.WriteLine("Finished Boss Comparison Calculations: Total " + DateTime.Now.Subtract(start).TotalMilliseconds.ToString() + "ms");
#endif
        }
 private void CarregarListas()
 {
     produtos = new DLProduto().List();
     if (Consumidor.ListaConsumidorProduto.Count > 0)
     {
         foreach (MLConsumidorProduto cp in Consumidor.ListaConsumidorProduto)
         {
             MLProduto produto = new MLProduto();
             produto = produtos.Find(x => x.CodProduto == cp.CodProduto);
             produtosSelecionados.Add(produto);
         }
     }
     lstProdutos.ItemsSource = produtos;
     lstProdutosSelecionados.ItemsSource = produtosSelecionados;
 }