// takes list of participants sorted by place in age division, returns top 3..ish
        List<AgeChampion> CalcAgeChampions(List<AgeChampion> champions, List<Participant> participants, int place = 1)
        {
            Participant p = participants.First();
            participants.Remove(p);

            // no points scored, cannot be a champion
            if (ParticipantPoints(p) == 0)
                return champions;

            champions.Add(new AgeChampion(p, place, ParticipantPoints(p)));

            // no more possible champions
            if (participants.Count == 0)
                return champions;

            // if the same number of points, equal age champion w/ same place
            if (champions.Last().Points == ParticipantPoints(participants.First()))
                CalcAgeChampions(champions, participants, place);

            // room for more champions
            else if (champions.Count < 3)
                CalcAgeChampions(champions, participants, place + 1);

            return champions;
        }
Beispiel #2
0
 public MainWindow()
 {
     InitializeComponent();
     _rules_them_all = OperationsManager.OperationsManager.GetInstance();
     this.DataContext = this._rules_them_all;
     string version_string = Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString();
     string program_title = "ASML-McCallister Home Security ";
     this.Title = program_title + version_string;
     lblNumMissiles.Content = _rules_them_all.NumberMissiles.ToString();
     _rules_them_all.ChangedTargets += on_targets_changed;
     _rules_them_all.sdCompleted += Search_Destroy_Complete;
     _rules_them_all._timer.TimeCaptured += new EventHandler<TimerEventArgs>(_timer_TimeCaptured);
     _video_plugins = new List<IVideoPlugin>();
     // add video plugins to list here
     _video_plugins.Add(new DefaultVideo());
     // set current plugin here.
     _eye_of_sauron = _video_plugins.First();
     // setup resoultion information and event handler, start plugin.
     _eye_of_sauron.Width = (int)imgVideo.Width;
     _eye_of_sauron.Height = (int)imgVideo.Height;
     _eye_of_sauron.NewImage += new EventHandler(on_image_changed);
     _eye_of_sauron.Start();
     // Mode List initialization
     cmbModes.ItemsSource = _rules_them_all.Modes;
     _rules_them_all.OutOfAmmo += on_out_of_ammo;
     _rules_them_all.AmmoReduced += On_Ammo_Reduced;
     this.Closing += MainWindow_Closing;
 }
        public AddProfileDialog(Window owner)
        {
            InitializeComponent();

            this.Owner = owner;

            OkCommand = new DelegateCommand(ExecuteOk, CanExecuteOk);
            _MainLayout.DataContext = this;

            Loaded += (sender, e) => MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

            IPHostEntry ips = Dns.GetHostEntry(Dns.GetHostName());

            HostList = new List<string>();
            HostList.Add(string.Empty);
            HostList.Add(LOCALHOST_NAME);

            if (ips != null)
            {
                foreach (IPAddress ipAddress in ips.AddressList)
                {
                    HostList.Add(ipAddress.ToString());
                }
            }

            Host = HostList.First();
        }
        public MainWindow()
        {
            InitializeComponent();
            // 以下を追加
            this.btnDownload.Click += (sender, e) =>
            {
                var client = new System.Net.WebClient();
                byte[] buffer = client.DownloadData("http://k-db.com/?p=all&download=csv");
                string str = Encoding.Default.GetString(buffer);
                string[] rows = str.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                // 1行目をラベルに表示
                this.lblTitle.Content = rows[0];
                // 2行目以下はカンマ区切りから文字列の配列に変換しておく
                List<string[]> list = new List<string[]>();
                rows.ToList().ForEach(row => list.Add(row.Split(new char[] { ',' })));
                // ヘッダの作成(データバインド用の設計)
                GridView view = new GridView();
                list.First().Select((item, cnt) => new { Count = cnt, Item = item }).ToList().ForEach(header =>
                {
                    view.Columns.Add(
                        new GridViewColumn()
                        {
                            Header = header.Item,
                            DisplayMemberBinding = new Binding(string.Format("[{0}]", header.Count))
                        });
                });
                // これらをリストビューに設定
                lvStockList.View = view;
                lvStockList.ItemsSource = list.Skip(1);
            };
        }
 private void fillComboSchueler()
 {
     //TODO
     //Get Schueler where isGuide = false
     List<Schueler> content = new List<Schueler>();
     content.Add(new Schueler(1, "Hansi", "Jaeger", "5BHIFS", false));
     content.Add(new Schueler(1, "Markus", "Weber", "5BHIFS", false));
     content.Add(new Schueler(1, "Michael", "Delfser", "5BHIFS", false));
     cmbSchueler.SelectedItem = content.First();
     cmbSchueler.ItemsSource = content;
 }
Beispiel #6
0
        public LaunchWindow()
        {
            string gameConfigurationFolder = "GameConfiguration";
            string gameConfigurationsPath = Path.Combine(gameConfigurationFolder, "gameConfigs.json");

            InitializeComponent();

            if (!Directory.Exists(gameConfigurationFolder))
                Directory.CreateDirectory(gameConfigurationFolder);

            //Loading the last used configurations for hammer
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Hammer\General");

            var configs = new List<GameConfiguration>();

            //try loading json
            if (File.Exists(gameConfigurationsPath))
            {
                string jsonLoadText = File.ReadAllText(gameConfigurationsPath);
                configs.AddRange(JsonConvert.DeserializeObject<List<GameConfiguration>>(jsonLoadText));
            }

            //try loading from registry
            if (rk != null)
            {
                string BinFolder = (string)rk.GetValue("Directory");

                string gameData = Path.Combine(BinFolder, "GameConfig.txt");

                configs.AddRange(GameConfigurationParser.Parse(gameData));
            }

            //finalise config loading
            if (configs.Any())
            {
                //remove duplicates
                configs = configs.GroupBy(g => g.Name).Select(grp => grp.First()).ToList();

                //save
                string jsonSaveText = JsonConvert.SerializeObject(configs, Formatting.Indented);
                File.WriteAllText(gameConfigurationsPath, jsonSaveText);

                if (configs.Count == 1)
                    Launch(configs.First());

                GameGrid.ItemsSource = configs;
            }
            else//oh noes
            {
                LaunchButton.IsEnabled = false;
                WarningLabel.Content = "No Hammer configurations found. Cannot launch.";
            }
        }
 public ProcessSelectionWindow( IEnumerable<EnvDTE.Process> processes )
     : base()
 {
     Processes = new List<ProcessItem> ();
     if ( processes.Count() == 0 ) {
         throw new ArgumentException ( "processes must contain items to show this dialog." );
     }
     foreach ( var p in processes ) {
         Processes.Add ( new ProcessItem ( p ) );
     }
     InitializeComponent ( );
     DataContext = this;
     this.Title = "{0} - {1}".With ( this.Title, Processes.First ( ).ShortName );
 }
Beispiel #8
0
        private void HorarioProximo(List<string> saidasDiretas, TextBlock tb)
        {
            string proxSaida;
            try
            {
                proxSaida = saidasDiretas.Where(x => String.Compare(x, DateTime.Now.ToShortTimeString()) > 0).First();
            }
            catch (Exception)
            {
                proxSaida = saidasDiretas.First();
            }

            tb.Text = proxSaida;
        }
Beispiel #9
0
        private void expandPath(TreeViewItem item, List<String> path){
            if (path.Count == 0) return;
            for(int i=0; i< item.Items.Count; i++){
                TreeViewItem t = item.Items[i] as TreeViewItem;
                if (t.Header.ToString().Equals(path.First()))
                {
                    t.IsExpanded = true;
                    path.RemoveAt(0);
                    if (path.Count == 0)
                        t.IsSelected = true;
                    else
                        expandPath(t, path);
                    break;
                }
            }

        }
		public IEnumerable<Edge> GroupToEdges(List<Point> points)
		{
			List<Edge> edges = new List<Edge>();

			while (points.Any())
			{
				creatingTime.Start();
				var point = points.First();
				points.Remove(point);

				var edge = new Edge(point);
				creatingTime.Stop();

				edges.Add(GrowEdge(edge, points));
			}

			return edges;
		}
 void ListOrganisationCompleted(List<Organisation> orgList)
 {
     Globals.IsBusy = false;
     _originalItemSource.Clear();
     foreach (Organisation item in orgList)
     {
         item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(OrganisationItem_PropertyChanged);
         _originalItemSource.Add(item);
     }
     gvwOrganisations.ItemsSource = orgList;
     if (_seletedOrgId > 0 && orgList.Count(i => i.OrganisationId == _seletedOrgId) > 0)
     {
         gvwOrganisations.SelectedItem = orgList.First(i => i.OrganisationId == _seletedOrgId);
     }
     else if (orgList.Count > 0)
     {
         gvwOrganisations.SelectedItem = orgList[0];
     }
 }
        private void GenerateColumns(DataGrid dataGrid, List<RowViewModel> rows)
        {
            if (dataGrid == null || rows.Count == 0)
                return;

            var nameColumn = dataGrid.Columns.First();
            dataGrid.Columns.Clear();
            dataGrid.Columns.Add(nameColumn);

            var ruleCount = rows.First().States.Count;
            for (int i = 0; i < ruleCount; i++)
            {
                dataGrid.Columns.Add(new DataGridTemplateColumn
                {
                    Header = i + 1,
                    CellTemplateSelector = DTCellTemplateSelector.Instance,
                    MinWidth = 70
                });
            }
        }
        public Bannissement()
        {
            CultureManager.UICultureChanged += CultureManager_UICultureChanged;

            InitializeComponent();

            // Header de la fenetre
            App.Current.MainWindow.Title = Nutritia.UI.Ressources.Localisation.FenetreBannissement.Titre;

            LstMembre = new ObservableCollection<Membre>();
            LstBanni = new ObservableCollection<Membre>();
            TousLesMembres = new List<Membre>(ServiceFactory.Instance.GetService<IMembreService>().RetrieveAll());

            TousLesMembres.Remove(TousLesMembres.First(membre => membre.IdMembre == App.MembreCourant.IdMembre));

            RemplirListe();

            //SearchBox
            dgRecherche.DataGridCollection = CollectionViewSource.GetDefaultView(LstMembre);
            dgRecherche.DataGridCollection.Filter = new Predicate<object>(Filter);
        }
Beispiel #14
0
        public MainWindow()
        {
            InitializeComponent();
            _rules_them_all = OperationsManager.OperationsManager.GetInstance();
            this.DataContext = this._rules_them_all;
            string version_string = Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString();
            string program_title = "ASML-McCallister Home Security ";
            this.Title = program_title + version_string;
            lblNumMissiles.Content = _rules_them_all.NumberMissiles.ToString();
            _rules_them_all.ChangedTargets += on_targets_changed;
            _rules_them_all.sdCompleted += Search_Destroy_Complete;
            _rules_them_all._timer.TimeCaptured += new EventHandler<TimerEventArgs>(_timer_TimeCaptured);
            _video_plugins = new List<IVideoPlugin>();
            bool PluginFunctioning = true;
            _detection_counter = 0;
            try
            {
                // add video plugins to list here
                _video_plugins.Add(new DefaultVideo());

            }
            catch (Exception)
            {
                PluginFunctioning = false;

            }
            // fail silently if video is not present or does not work.
            if (PluginFunctioning == true)
            {
                // set current plugin here.
                _eye_of_sauron = _video_plugins.First();
                _eye_of_sauron.NewImage += new EventHandler(on_image_changed);
                _eye_of_sauron.Start();
            }
            // Mode List initialization
            cmbModes.ItemsSource = _rules_them_all.Modes;
            _rules_them_all.AmmoReduced += On_Ammo_Reduced;
            this.Closing += MainWindow_Closing;
        }
        /// <summary>
        /// Populates the layout radio buttons from disk.
        /// </summary>
        private void PopulateLayoutRadioButtonsFromDisk()
        {
            List<RadioButton> radioButtonList = new List<RadioButton>();
            var rockConfig = RockConfig.Load();
            List<string> filenameList = Directory.GetFiles( ".", "*.dplx" ).ToList();
            foreach ( var fileName in filenameList )
            {
                DplxFile dplxFile = new DplxFile( fileName );
                DocumentLayout documentLayout = new DocumentLayout( dplxFile );
                RadioButton radLayout = new RadioButton();
                if ( !string.IsNullOrWhiteSpace( documentLayout.Title ) )
                {
                    radLayout.Content = documentLayout.Title.Trim();
                }
                else
                {
                    radLayout.Content = fileName;
                }

                radLayout.Tag = fileName;
                radLayout.IsChecked = rockConfig.LayoutFile == fileName;
                radioButtonList.Add( radLayout );
            }

            if ( !radioButtonList.Any( a => a.IsChecked ?? false ) )
            {
                if ( radioButtonList.FirstOrDefault() != null )
                {
                    radioButtonList.First().IsChecked = true;
                }
            }

            lstLayouts.Items.Clear();
            foreach ( var item in radioButtonList.OrderBy( a => a.Content ) )
            {
                lstLayouts.Items.Add( item );
            }
        }
Beispiel #16
0
        public MainWindow()
        {
            InitializeComponent();
            _rules_them_all = OperationsManager.OperationsManager.GetInstance();
            this.DataContext = this._rules_them_all;
            string version_string = Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString();
            string program_title = "ASML-McCallister Home Security ";
            this.Title = program_title + version_string;
            lblNumMissiles.Content = _rules_them_all.NumberMissiles.ToString();
            _rules_them_all.ChangedTargets += on_targets_changed;
            _video_plugins = new List<IVideoPlugin>();
            // add plugins to list here
            _video_plugins.Add(new DefaultVideo());
            // set current plugin here.
            _eye_of_sauron = _video_plugins.First();
            _eye_of_sauron.Width = (int)imgVideo.Width;
            _eye_of_sauron.Height = (int)imgVideo.Height;
            _eye_of_sauron.NewImage += new EventHandler(on_image_changed);
            _eye_of_sauron.Start();

            // Mode List initialization
               // lstModes.DataContext = _rules_them_all.SearchModeList
        }
        private void callWebService(compiledAssembly compiledAsm, string astrMethod, List<Parameter> alsParameters, Microsoft.Office.Interop.Excel.Worksheet awsData, int aiStartRow)
        {
            CompilerResults compilerResult = compiledAsm.compilerResults as CompilerResults;

            int iErrorCount = 0;
            DateTime dtStart = DateTime.Now;
            DateTime dtEnd;

            if (null != compilerResult && false == string.IsNullOrEmpty(astrMethod))
            {
                var allTypes = compilerResult.CompiledAssembly.GetTypes();

                MethodInfo methodInfo = null; //compilerResult.GetType().GetMethod(astrMethod);

                foreach (var currentMethod in allTypes)
                {
                    if (null != currentMethod && null != currentMethod.BaseType)
                    {
                        if(null != (methodInfo = currentMethod.GetMethod(astrMethod)))
                        {
                            break;
                        }
                    }
                }

                var headerInfo = allTypes.Where(t => t.Name == "lws" || t.Name == "mws").First();

                object objHeader = System.Activator.CreateInstance(headerInfo);

                // this is the type of the final type in our heirachy where we plug in the spreadsheet values
                Type tpTypeToPopulate = null;

                // argumentType = getArgumentClassType(allTypes, astrMethod);

                List<Type> lsTypeHierarchy = getArgumentClassType(allTypes, astrMethod);

                List<object> lsCallObjects = new List<object>();
                // create the object hierachy, the first object in the list should be the one
                // supplied to the webservice call.  The last should be the one that we populate
                // with data from the spreadsheet
                createObjectHierachy(lsTypeHierarchy, lsCallObjects, 0);

                if(lsCallObjects.Count > 0)
                {
                    tpTypeToPopulate = lsTypeHierarchy.Last();
                    // object objObjectToSet = lsCallObjects.Last();
                    object objObjectToPassToCall = lsCallObjects.First();

                    foreach(object objObjectToSet in lsCallObjects)
                    {
                        tpTypeToPopulate = objObjectToSet.GetType();

                        for (int i = aiStartRow; i < giMaxRowPosition; i++)
                        {
                            bool bBlank = true;

                            foreach (Parameter currentParameter in alsParameters)
                            {
                                if (null != currentParameter)
                                {
                                    var spreadSheetValue = awsData.get_Range(currentParameter.Value + i).Value2;
                                    if (null != spreadSheetValue)
                                    {
                                        // retrieve the value from the spreadsheet
                                        string strValue = awsData.get_Range(currentParameter.Value + i).Value2.ToString();

                                        PropertyInfo currentProperty = tpTypeToPopulate.GetProperty(currentParameter.Name);

                                        if (null != currentProperty)
                                        {
                                            if (false == string.IsNullOrWhiteSpace(strValue))
                                            {
                                                bBlank = false;
                                            }

                                            object objValue = strValue;

                                            if (typeof(int) == currentProperty.PropertyType)
                                            {
                                                int iValue = 0;
                                                int.TryParse(strValue, out iValue);

                                                objValue = iValue;
                                            }
                                            else if (typeof(decimal) == currentProperty.PropertyType)
                                            {
                                                decimal decValue = 0;
                                                decimal.TryParse(strValue, out decValue);

                                                objValue = decValue;
                                            }
                                            else if (typeof(double) == currentProperty.PropertyType)
                                            {
                                                double dblValue = 0;
                                                double.TryParse(strValue, out dblValue);

                                                objValue = dblValue;
                                            }
                                            else if (typeof(DateTime) == currentProperty.PropertyType)
                                            {
                                                DateTime dtValue = DateTime.MinValue;

                                                DateTime.TryParse(strValue, out dtValue);

                                                objValue = dtValue;
                                            }

                                            // save the parameter
                                            tpTypeToPopulate.InvokeMember(currentParameter.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, objObjectToSet, new object[] { objValue });
                                        }
                                        else
                                        {
                                            // property doesn't exist
                                        }

                                    }
                                }
                            }
                            // if we have a blank line we should stop
                            if (true == bBlank)
                            {
                                break;
                            }
                            else
                            {
                                // call to the webservice here
                                try
                                {
                                    methodInfo.Invoke(compiledAsm.instantiatedObject, new object[] { objHeader, objObjectToPassToCall });
                                    awsData.get_Range(gstrResultColumn + i).Value2 = "OK";
                                }
                                catch (Exception ex)
                                {
                                    awsData.get_Range(gstrResultColumn + i).Value2 = ex;
                                    iErrorCount++;
                                }
                            }
                        }
                    }

                    dtEnd = DateTime.Now;

                    awsData.get_Range(gstrErrorCountCell).Value2 = iErrorCount;
                    awsData.get_Range(gstrStartTimeCell).Value2 = dtStart.ToString("yyyy-MM-dd HH:mm:ss");
                    awsData.get_Range(gstrEndTimeCell).Value2 = dtEnd.ToString("yyyy-MM-dd HH:mm:ss");
                    awsData.get_Range(gstrDurationCell).Value2 = (dtEnd - dtStart).TotalSeconds;
                }

            }
        }
        public void BindBookingList(List<Booking> itemSource)
        {
            Globals.IsBusy = false;
            _originalItemSource.Clear();
            foreach (Booking item in itemSource)
            {
                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(item_PropertyChanged);
                _originalItemSource.Add(item);
            }
            FillEmptyCustomerName();

            gvwBooking.ItemsSource = itemSource;

            if (_selectedBookingId > 0 && itemSource.Count(i => i.BookingId == _selectedBookingId) > 0)
            {
                gvwBooking.SelectedItem = itemSource.First(i => i.BookingId == _selectedBookingId);
            }
            else if (itemSource.Count > 0)
            {
                gvwBooking.SelectedItem = itemSource[0];
            }
        }
Beispiel #19
0
        private void UpdatePage(DateTime date)
        {
            try
            {
                var ValuesList = new List<DateValues>();

                VentsTools.currentActionString = "Подключаюсь к Базе данных";
                _fndHwnd = GetCurrentThreadId();
                //запустим таймер с задержкой в 1с для отображения прогрессбара (бесячий кругалек, когда все зависло)
                ProgressBarPerform = new KeyValuePair<bool, int>(true, 1000);

                string ventName = (string)Dispatcher.Invoke(new Func<string>(() => (VentsListBox.SelectedItem as Vents).name)); // возвращает название выбранного вентилятора
                bool RDVres = _vt.ReadDayValuesFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref ValuesList);
                if (!RDVres)
                    throw new Exception(String.Format("Не удалось получить ежедневные данные для {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));

                //разобьем список на несколько по VentsConst._VALUE_ROWS_HOURTABLE итемов в каждом
                var parts = ValuesList.DivideByLenght(VentsConst._VALUE_ROWS_DAYTABLE);
                double cellWidth = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Width / VentsConst._MAXIMUM_COLUMNS_DAYTABLE));
                double cellHeight = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Height / VentsConst._MAXIMUM_ROWS_DAYTABLE));

                Dispatcher.Invoke(new Action(delegate { BuildDayTable(parts, cellWidth, cellHeight); }));  //построим таблицу

                #region autogenerated datagrid
                //Dispatcher.Invoke(new Action(delegate
                //{
                //    workGrid.Children.Clear();
                //    for (int i = 0; i < 3;i++ )
                //    {
                //        List<DateValues> listDV = parts[i];
                //        DataGrid dataGrid = new DataGrid();
                //        dataGrid.AutoGenerateColumns = true;
                //        dataGrid.MaxHeight = 380;
                //        //dataGrid.MaxWidth = 140;
                //        dataGrid.Width = 156;
                //        dataGrid.MaxWidth = 156;
                //        dataGrid.Margin = new Thickness(200 + dataGrid.Width * i, 59, 0, 0);
                //        dataGrid.RowHeight = 30;
                //        dataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //        dataGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                //        dataGrid.CanUserAddRows = false;
                //        dataGrid.CanUserDeleteRows = false;
                //        dataGrid.CanUserReorderColumns = false;
                //        dataGrid.CanUserResizeColumns = false;
                //        dataGrid.CanUserResizeRows = false;
                //        dataGrid.CanUserSortColumns = false;
                //        dataGrid.IsReadOnly = true;
                //        dataGrid.IsHitTestVisible = false;
                //        dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                //        dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                //       // dataGrid.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromRgb(255,255,255));
                //        dataGrid.ItemsSource = listDV;
                //        dataGrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn);
                //        // var trtr = dataGrid.ColumnWidth;
                //        workGrid.Children.Add(dataGrid);
                //    }

                //}));
                #endregion

                //calculate monthly electric power expense
                int monthlyExpense = 0;
                if (date != _firstMonth)
                {
                    bool daylyRes = _vt.ReadMonthlyExpenseFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref monthlyExpense);
                    if (!daylyRes)
                    {
                        throw new Exception(String.Format("Не удалось получить  данные для месячного расхода {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); }))));
                    }
                }
                else
                {
                    monthlyExpense = ValuesList.Last<DateValues>().value - ValuesList.First<DateValues>().value;
                }
                monthlyExpense = monthlyExpense * 100;
                Dispatcher.Invoke(new Action(delegate { totaltb.Text = String.Format("Расход {0} за {1} равен {2} кВтч", (VentsListBox.SelectedItem as Vents).descr, date.GetDateTimeFormats('O')[0].Substring(0, 8), monthlyExpense.ToString()); }));

                //generate current action string and update content of main window textbox
                string descr = (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; }));

                VentsTools.currentActionString = String.Format("Показания за  {0} {1}", date.Date.GetDateTimeFormats('D', CultureInfo.CreateSpecificCulture("ru-ru"))[0], descr);

                ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
                _fndHwnd = IntPtr.Zero;

            }
            catch (Exception ex)
            {
                VentsTools.currentActionString = "Не удалось подключиться к базе данных";
                _log.Error(ex.Message);
                ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000);
                _fndHwnd = IntPtr.Zero;
            }
        }
Beispiel #20
0
        /// <summary>
        /// 导入借款单
        /// Creator:安凯航
        /// 日期:2011年5月30日
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnImportBorrowData_Click(object sender, RoutedEventArgs e)
        {
            //导入时间
            DateTime createTime = DateTime.Now;
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Multiselect = false,
                Filter = "Excel 2007-2010 File(*.xlsx)|*.xlsx"
            };
            bool? userClickedOK = dialog.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK != true)
            {
                return;
            }
            try
            {

                //待保存数据列表
                List<OrderEntity> orders = new List<OrderEntity>();
                #region 读取Excel文件

                XLSXReader reader = new XLSXReader(dialog.File);
                List<string> subItems = reader.GetListSubItems();
                var maseters = reader.GetData(subItems[0]);
                var listm = maseters.ToDataSource();
                var details = reader.GetData(subItems[1]);
                var listd = details.ToDataSource();
                List<dynamic> masterList = new List<dynamic>();
                foreach (var item in listm)
                {
                    dynamic d = item;
                    masterList.Add(d);
                }
                //排除第一行信息
                masterList.Remove(masterList.First());

                List<dynamic> detailList = new List<dynamic>();
                foreach (var item in listd)
                {
                    dynamic d = item;
                    detailList.Add(d);
                }
                //排除第一行信息
                detailList.Remove(detailList.First());

                #endregion

                #region 添加主表
                List<T_FB_BORROWAPPLYMASTER> import = new List<T_FB_BORROWAPPLYMASTER>();
                foreach (var item in masterList)
                {
                    //构造OrderEntity数据
                    OrderEntity oe = new OrderEntity(typeof(T_FB_BORROWAPPLYMASTER));
                    orders.Add(oe);

                    T_FB_BORROWAPPLYMASTER t = oe.FBEntity.Entity as T_FB_BORROWAPPLYMASTER;
                    t.BORROWAPPLYMASTERID = Guid.NewGuid().ToString();
                    t.BORROWAPPLYMASTERCODE = item.单据号;
                    if (item.借款类型 == "普通借款")
                    {
                        t.REPAYTYPE = 1;
                    }
                    else if (item.借款类型 == "备用金借款")
                    {
                        t.REPAYTYPE = 2;
                    }
                    else if (item.借款类型 == "专项借款")
                    {
                        t.REPAYTYPE = 3;
                    }
                    else
                    {
                        continue;
                    }
                    t.REMARK = item.备注;
                    import.Add(t);
                }

                #endregion

                #region 添加子表

                foreach (var item in detailList)
                {
                    OrderEntity oe = orders.FirstOrDefault(oen =>
                    {
                        T_FB_BORROWAPPLYMASTER bm = oen.FBEntity.Entity as T_FB_BORROWAPPLYMASTER;
                        if (bm.BORROWAPPLYMASTERCODE == item.单据号)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    });
                    if (oe == null)
                    {
                        string message = "导入的借款单明细借款单号为\"" + item.单据号 + "\"的明细,没有相应的借款单对应.请检查借款Excel中是否有此借款单的数据";
                        throw new InvalidOperationException(message);
                    }
                    FBEntity fbdetail = oe.CreateFBEntity<T_FB_BORROWAPPLYDETAIL>();
                    T_FB_BORROWAPPLYDETAIL d = fbdetail.Entity as T_FB_BORROWAPPLYDETAIL;
                    d.BORROWAPPLYDETAILID = Guid.NewGuid().ToString();
                    d.REMARK = item.摘要;
                    d.BORROWMONEY = Convert.ToDecimal(item.借款金额);
                    d.UNREPAYMONEY = Convert.ToDecimal(item.未还款金额);
                    d.T_FB_SUBJECT = d.T_FB_SUBJECT ?? new T_FB_SUBJECT();
                    d.T_FB_SUBJECT.SUBJECTID = item.借款科目;
                    d.CREATEDATE = createTime;
                    d.CREATEUSERID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID;
                    d.UPDATEDATE = createTime;
                    d.UPDATEUSERID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID;
                }

                #endregion

                //服务
                OrderEntityService service = new OrderEntityService();

                #region 得到科目信息

                QueryExpression reExp = QueryExpressionHelper.Equal("OWNERID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID);
                QueryExpression exp = QueryExpressionHelper.Equal("OWNERPOSTID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].PostID);
                exp.QueryType = "T_FB_BORROWAPPLYDETAIL";
                exp.RelatedExpression = reExp;
                exp.IsUnCheckRight = true;

                #endregion

                #region 获取申请人信息

                ObservableCollection<string> numbers = new ObservableCollection<string>();
                masterList.ForEach(item => numbers.Add(item.申请人身份证号));//拿到所有身份证号
                SMT.Saas.Tools.PersonnelWS.PersonnelServiceClient client = new Saas.Tools.PersonnelWS.PersonnelServiceClient();
                client.GetEmployeesByIdnumberAsync(numbers);

                #endregion

                #region 先获取申请人信息,待申请人信息填充完毕之后进行下一步操作

                client.GetEmployeesByIdnumberCompleted += new EventHandler<Saas.Tools.PersonnelWS.GetEmployeesByIdnumberCompletedEventArgs>((oo, ee) =>
                {
                    if (ee.Error == null)
                    {
                        string message = null;
                        try
                        {
                            masterList.ForEach(m =>
                            {
                                //添加owner和creator
                                SMT.Saas.Tools.PersonnelWS.V_EMPLOYEEVIEW userview = null;
                                try
                                {
                                    userview = ee.Result.First(t => t.IDNUMBER == m.申请人身份证号);
                                }
                                catch (InvalidOperationException ex)
                                {
                                    message = ex.Message + "\n" + "在系统中找不到身份证号为\"" + m.申请人身份证号 + "\"的,员工信息.也可能是您没有相应的权限.";
                                    throw new InvalidOperationException(message);
                                }
                                T_FB_BORROWAPPLYMASTER master = null;
                                try
                                {
                                    master = import.First(t => t.BORROWAPPLYMASTERCODE == m.单据号);
                                }
                                catch (InvalidOperationException ex)
                                {
                                    message = ex.Message + "\n" + "导入的借款单明细借款单号为\"" + m.单据号 + "\"的明细,没有相应的借款单对应.请检查借款Excel中是否有此借款单的数据";
                                    throw new InvalidOperationException(message);
                                }
                                master.OWNERCOMPANYID = userview.OWNERCOMPANYID;
                                master.OWNERCOMPANYNAME = userview.OWNERCOMPANYID;
                                master.OWNERDEPARTMENTID = userview.OWNERDEPARTMENTID;
                                master.OWNERID = userview.EMPLOYEEID;
                                master.OWNERPOSTID = userview.OWNERPOSTID;
                                master.CREATECOMPANYID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].CompanyID;
                                master.CREATECOMPANYNAME = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].CompanyName;
                                master.CREATEDEPARTMENTID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].DepartmentID;
                                master.CREATEDEPARTMENTNAME = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].DepartmentName;
                                master.CREATEPOSTID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].PostID;
                                master.CREATEPOSTNAME = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].PostName;
                                master.CREATEUSERID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID;
                                master.CREATEUSERNAME = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeName;
                                master.CREATEDATE = createTime;
                                master.UPDATEUSERID = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID;
                                master.UPDATEUSERNAME = SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeName;
                                master.UPDATEDATE = createTime;
                            });
                            //填充完申请人信息之后开始填充科目信息
                            service.QueryFBEntities(exp);
                        }
                        catch (Exception ex)
                        {
                            SMT.SaaS.FrameworkUI.ChildWidow.ComfirmWindow.ConfirmationBoxs("导入出错", ex.Message, "确定", MessageIcon.Exclamation);
                        }
                    }
                });

                #endregion

                #region 填充完申请人信息之后开始填充科目信息

                service.QueryFBEntitiesCompleted += new EventHandler<QueryFBEntitiesCompletedEventArgs>((o, args) =>
                {
                    if (args.Error == null)
                    {
                        //构造明细科目及账务信息
                        string message = null;
                        try
                        {
                            import.ForEach(m =>
                            {
                                OrderEntity oe = orders.FirstOrDefault(oen =>
                                {
                                    T_FB_BORROWAPPLYMASTER bm = oen.FBEntity.Entity as T_FB_BORROWAPPLYMASTER;
                                    if (bm.BORROWAPPLYMASTERCODE == m.BORROWAPPLYMASTERCODE)
                                    {
                                        return true;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                });
                                var dlist = oe.GetRelationFBEntities("T_FB_BORROWAPPLYDETAIL");
                                List<T_FB_BORROWAPPLYDETAIL> detailslist = new List<T_FB_BORROWAPPLYDETAIL>();
                                dlist.ForEach(ddd =>
                                {
                                    detailslist.Add(ddd.Entity as T_FB_BORROWAPPLYDETAIL);
                                });
                                detailslist.ForEach(d =>
                                {
                                    FBEntity en = null;
                                    try
                                    {
                                        en = args.Result.First(a => ((T_FB_BORROWAPPLYDETAIL)a.Entity).T_FB_SUBJECT.SUBJECTCODE == d.T_FB_SUBJECT.SUBJECTID);
                                    }
                                    catch (InvalidOperationException ex)
                                    {
                                        message = ex.Message + "\n" + "导入的借款单明细中,在系统中找不到ID为\"" + d.T_FB_SUBJECT.SUBJECTID + "\"的科目,也可能是您没有相应的权限";
                                        throw new InvalidOperationException(message);
                                    }
                                    T_FB_BORROWAPPLYDETAIL t = en.Entity as T_FB_BORROWAPPLYDETAIL;
                                    if (t != null)
                                    {
                                        t.T_FB_SUBJECT.T_FB_BORROWAPPLYDETAIL.Clear();
                                        d.T_FB_SUBJECT = t.T_FB_SUBJECT;
                                        d.CHARGETYPE = t.CHARGETYPE;
                                        d.USABLEMONEY = t.USABLEMONEY;
                                        #region 清理科目信息中的无用数据

                                        t.T_FB_SUBJECT.T_FB_BORROWAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_BUDGETACCOUNT.Clear();
                                        t.T_FB_SUBJECT.T_FB_BUDGETCHECK.Clear();
                                        t.T_FB_SUBJECT.T_FB_CHARGEAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_COMPANYBUDGETAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_COMPANYBUDGETMODDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_COMPANYBUDGETMODDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_COMPANYTRANSFERDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_DEPTBUDGETADDDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_DEPTBUDGETAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_DEPTTRANSFERDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_EXTENSIONORDERDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_PERSONBUDGETADDDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_PERSONBUDGETAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_PERSONMONEYASSIGNDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_REPAYAPPLYDETAIL.Clear();
                                        t.T_FB_SUBJECT.T_FB_SUBJECTCOMPANY.Clear();
                                        t.T_FB_SUBJECT.T_FB_SUBJECTDEPTMENT.Clear();
                                        t.T_FB_SUBJECT.T_FB_SUBJECTPOST.Clear();
                                        t.T_FB_SUBJECT.T_FB_TRAVELEXPAPPLYDETAIL.Clear();

                                        #endregion
                                    }
                                });
                            });

                            //保存
                            service.SaveList(orders);
                        }
                        catch (Exception ex)
                        {
                            SMT.SaaS.FrameworkUI.ChildWidow.ComfirmWindow.ConfirmationBoxs("导入出错", ex.Message, "确定", MessageIcon.Exclamation);
                        }
                    }
                });

                #endregion

                #region 所有信息构造完成之后保存数据

                service.SaveListCompleted += new EventHandler<ActionCompletedEventArgs<bool>>((s, evgs) =>
                {
                    if (evgs.Result)
                    {
                        SMT.SaaS.FrameworkUI.ChildWidow.ComfirmWindow.ConfirmationBox("导入成功", "导入成功", "确定");
                    }
                    else
                    {
                        SMT.SaaS.FrameworkUI.ChildWidow.ComfirmWindow.ConfirmationBox("导入失败", "导入失败", "确定");
                    }
                });

                #endregion

            }
            catch (Exception ex)
            {
                SMT.SaaS.FrameworkUI.ChildWidow.ComfirmWindow.ConfirmationBoxs("导入出错", ex.Message, "确定", MessageIcon.Exclamation);
            }
        }
Beispiel #21
0
 private async void UpdateWeather()
 {
     try
     {
         _weatherList = await OpenWeather.HelperClass.Weather.GetWeather(Properties.Settings.Default.WeatherLocation);
         _currentWeather = _weatherList.First();
         _weatherForecast = _weatherList.Skip(1).ToList();
         tbCurrentLocation.Text = Properties.Settings.Default.WeatherLocation;
         //gridWeather.DataContext = _currentWeather;
         itemsControlForecase.DataContext = _weatherForecast;
         borderWeatherRight.DataContext = _currentWeather;
         borderWeatherStrip.DataContext = _currentWeather;
     }
     catch (System.Exception)
     {
     }
 }
        // this section is used to populate all other textboxes according to the selected record in searchbar
        public void populateAllOtherTextbox(ComboBox cmbBox, TextBox factoryNameTxt, TextBox itemNameTxt, DatePicker dateX, TextBox descriptionTxt, TextBox noOfPiecesTxt, TextBox costPerPieceTxt, System.Windows.Controls.Image imgX)
        {
            if (cmbBox.SelectedItem != null)
            {

                try
                {
                    using (adoraDBContext a = new adoraDBContext())
                    {
                        //getting data from the selected record in the search bar
                        String fullString = cmbBox.SelectedValue.ToString();
                        String[] facNameAndItemNameArray = Regex.Split(fullString, "  ->  ");
                        String factoryName = facNameAndItemNameArray[0];
                        String itemName = facNameAndItemNameArray[1];

                        factoryNameTxt.Text = factoryName;
                        itemNameTxt.Text = itemName;
                       
                        // retriving descrption data from the database and populating the description text box
                        var DescriptionDetails = (from e in a.StockInHands
                                                  where (e.FactoryName == factoryName && e.ItemName == itemName)
                                                  select e.descript
                                                 ).ToList();

                        descriptionTxt.Text = DescriptionDetails.First().ToString();

                        // retriving date details from the database and populating the date field
                        var dateDetails = (from e in a.StockInHands
                                                  where (e.FactoryName == factoryName && e.ItemName == itemName)
                                                  select e.Date
                       ).ToList();

                        dateX.Text = dateDetails.First().ToString();

                        // retriving no of pieces details from the database and populating the no of pieces details text box
                        var noOfPiecesDetails = (from e in a.StockInHands
                                           where (e.FactoryName == factoryName && e.ItemName == itemName)
                                           select e.NoOfItems
                       ).ToList();

                        noOfPiecesTxt.Text = noOfPiecesDetails.First().ToString();

                        try
                        {
                            // retriving cost per piece details from the database and populating the cost per piece details text box
                            var CostPerPieceDetails = (from e in a.StockInHands
                                                       join b in a.ActualCosts on e.ACostID equals b.ACostID
                                                       where (e.FactoryName == factoryName && e.ItemName == itemName)
                                                       select b.TotalCost
                           ).ToList();

                            costPerPieceTxt.Text = CostPerPieceDetails.First().ToString();
                        }
                        catch(Exception)
                        {
                            costPerPieceTxt.Text = "<< Cost per piece for this item not available >>";
                        }

                        // retriving the image stock id from the database using factory name and item number of selected record
                        var imageStockId = (from e in a.StockInHands
                                            where (e.FactoryName == factoryName && e.ItemName == itemName)
                                            select e.StockID
                       ).ToList();

                        // setting the current record stock id public variable 
                        setCurrentRecordStockID(imageStockId.Last().ToString());

                        if (imageStockId.Any())
                        {
                            String imgStockId = imageStockId.Last().ToString();

                            //retriving the image name list from the database using the image stock id
                            var imageNameList = (from e in a.Images
                                             where (e.StockID == imgStockId)
                                             select e.Link
                                       ).ToList();

                            // Setting the imageNameList to global variable currentRecordImageList
                             currentRecordImageNameList = imageNameList;

                            // Setting the first image in the image viewer
                             if (currentRecordImageNameList.Count > 0)
                             {
                                 String firstImageName = currentRecordImageNameList.First().ToString();

                                 // calling image set function to set the corresponding image in the image viewer
                                 imageSet(firstImageName, imgX);
                             } 
                             else
                             {
                                 imgX.Source = null;
                             }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
        }
        private void llamarSegundaPantalla(List<Detalle> detalles)
        {
            txbFactura.Document.Blocks.Clear();
            DataClasses1DataContext dc = new DataClasses1DataContext();
            int factura = dc.SIGEEA_FacAsociados.First(c => c.PK_Id_FacAsociado == (dc.SIGEEA_DetFacAsociados.First(d => d.PK_Id_DetFacAsociado == detalles.First().getLlave()).FK_Id_FacAsociado)).PK_Id_FacAsociado;
            SIGEEA_spGenerarFacturaEntregaResult encabezado = dc.SIGEEA_spGenerarFacturaEntrega(factura).First();
            List<SIGEEA_spObtenerDetallesFacturaCompletaAsocResult> listaDetalles = dc.SIGEEA_spObtenerDetallesFacturaCompletaAsoc(factura).ToList();
            Run run;

            Paragraph parrafoEncabezado = new Paragraph();
            parrafoEncabezado.TextAlignment = TextAlignment.Center;
            parrafoEncabezado.FontFamily = new FontFamily("Agency FB");
            parrafoEncabezado.FontSize = 18;

            parrafoEncabezado.Inlines.Add(new Run(encabezado.Nombre_Empresa));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.CedJuridica));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.Direccion_Empresa));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.Telefono));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.Correo));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.Fecha));
            parrafoEncabezado.Inlines.Add(new Run("  " + encabezado.Hora));
            parrafoEncabezado.Inlines.Add(new Run(Environment.NewLine));
            parrafoEncabezado.Inlines.Add(new Run(encabezado.NumFactura));

            txbFactura.Document.Blocks.Add(parrafoEncabezado);//FINAL

            Paragraph parrafoAsociado = new Paragraph();
            parrafoAsociado.TextAlignment = TextAlignment.Left;
            parrafoAsociado.FontFamily = new FontFamily("Agency FB");
            parrafoAsociado.FontSize = 16;

            parrafoAsociado.Inlines.Add(new Run(encabezado.NombreAsociado));
            parrafoAsociado.Inlines.Add(new Run(Environment.NewLine));
            parrafoAsociado.Inlines.Add(new Run(encabezado.CedPersona));
            parrafoAsociado.Inlines.Add(new Run(Environment.NewLine));
            parrafoAsociado.Inlines.Add(new Run(encabezado.CodigoAsociado));
            txbFactura.Document.Blocks.Add(parrafoAsociado);



            /*Paragraph parrafoFactura = new Paragraph();
            parrafoFactura.TextAlignment = TextAlignment.Left;
            parrafoFactura.FontFamily = new FontFamily("Agency FB");
            parrafoFactura.FontSize = 16;
            parrafoFactura.Inlines.Add(new Run("______________________________________________________________________________________________"));
            parrafoFactura.Inlines.Add(new Run(Environment.NewLine));
            parrafoFactura.Inlines.Add(new Run("Cantidad total entregada: " + infoFactura.CantidadTotal));
            parrafoFactura.Inlines.Add(new Run(Environment.NewLine));
            parrafoFactura.Inlines.Add(new Run("Cantidad neta: " + infoFactura.CantidadNeta));
            parrafoFactura.Inlines.Add(new Run(Environment.NewLine));
            parrafoFactura.Inlines.Add(new Run("Merma: " + infoFactura.MERMA));
            parrafoFactura.Inlines.Add(new Run(Environment.NewLine));
            parrafoFactura.Inlines.Add(new Run("______________________________________________________________________________________________"));
            parrafoFactura.Inlines.Add(new Run(Environment.NewLine));
            txbFactura.Document.Blocks.Add(parrafoFactura);*/


            Paragraph parrafoProductos = new Paragraph();
            parrafoProductos.TextAlignment = TextAlignment.Left;
            parrafoProductos.FontFamily = new FontFamily("Agency FB");
            parrafoProductos.FontSize = 16;

            run = new Run();
            run.FontWeight = FontWeights.Bold;
            run.FontSize = 16;
            run.Text = "Producto          Cantidad total        Cantidad neta          A pagar       Merma              Precio";
            parrafoProductos.Inlines.Add(run);
            parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
            parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
            double total = 0;


            foreach (Detalle i in detalles)
            {
                foreach (SIGEEA_spObtenerDetallesFacturaCompletaAsocResult d in listaDetalles)
                {
                    if (d.PK_Id_DetFacAsociado == i.getLlave())
                    {
                        parrafoProductos.Inlines.Add(new Run(d.Nombre_TipProducto + "              "));
                        parrafoProductos.Inlines.Add(new Run(d.CantidadTotalString + "                      "));
                        parrafoProductos.Inlines.Add(new Run(d.CantidadNetaString + "               "));
                        parrafoProductos.Inlines.Add(new Run((((double)d.CanNeta_DetFacAsociado * i.getMonto()) / ((double)d.CanNeta_DetFacAsociado * Convert.ToDouble(d.Precio.Substring(1)))).ToString("0.00") + "           "));
                        parrafoProductos.Inlines.Add(new Run(d.MERMA + "                    "));
                        parrafoProductos.Inlines.Add(new Run(d.Precio.ToString()));
                        moneda = d.Precio[0].ToString();
                        double totalDetalle = Convert.ToDouble(d.Precio.ToString().Remove(0, 1)) * (double)d.CanNeta_DetFacAsociado;
                        total += i.getMonto() == totalDetalle ? totalDetalle : i.getMonto();
                        parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
                    }
                }
            }
            parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
            run = new Run();
            run.FontWeight = FontWeights.Bold;
            run.FontSize = 20;
            run.Text = "Total                  " + moneda + total.ToString() + "           ";
            parrafoProductos.Inlines.Add(run);
            parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
            parrafoProductos.Inlines.Add(new Run(Environment.NewLine));
            parrafoProductos.Inlines.Add(new Run("Este recibo es un comprobante legal en el que se respalda que el asociado realizó la entrega de producto. Recomendamos conservarlo."));
            txbFactura.Document.Blocks.Add(parrafoProductos);
        }
Beispiel #24
0
        /// <summary>
        /// track every item in the host's list (these are data items)
        /// Generate an appropriate depth for them
        /// </summary>
        /// <param name="host"></param>
        private void UpdateItemsTracker(TwitterPanel host)
        {
            trackedItems = (from trackers in trackedItems
                               where host.Items.Contains(trackers.Item)
                               select trackers).ToList();

            var newtrackers = from item in host.Items
                              where trackedItems.Any(t => t.Item.Equals(item)) == false
                              select MakeTracker(item, null);
            trackedItems.AddRange(newtrackers);

            // order trackedItems to be the right order according to the host

            trackedItems = (from item in host.Items
                            select trackedItems.First(t => t.Item.Equals(item))).ToList();

            // Adjust the depths for all the trackers, to account for new items
            int depth = -300;
            foreach (var track in trackedItems)
            {
                track.Z = depth;
                depth -= 1000;
            }

            // join every item in the hosts data list with all our known tracked items
            // this is a left join so we preserve existing tracker items

            //var newlist = (from child in host.Items
            //              join known in trackedItems on child equals known.Item into joined
            //              from item in joined.DefaultIfEmpty()
            //              select MakeTracker(child, item)).ToList();

            //int cnt = host.Items.Count;
            //var x = (from child in host.Items
            //         join known in trackedItems on child equals known.Item into joined
            //         from item in joined.DefaultIfEmpty()
            //         where item == null
            //         select child).ToList();

            //// Adjust the depths for all the trackers, to account for new items
            //int depth = -300;
            //foreach (var track in newlist)
            //{
            //    track.Z = depth;
            //    depth -= 1000;
            //}
            //trackedItems = newlist;
        }
 private void AddJoints(List<Joint> JointData, JointCollection JointRaw, JointType JointDef)
 {
     IEnumerable<Joint> Results = JointRaw.Where(s => s.JointType == JointDef).Where(s => s.TrackingState == JointTrackingState.Tracked);
     if (Results.Count() > 0)
         JointData.Add(Results.First());
     while (JointData.Count > 10)
     {
         JointData.Remove(JointData.First());
     }
 }
 void ListSiteGroupCompleted(List<SiteGroup> siteGroups)
 {
     _originalItemSource.Clear();
     foreach (SiteGroup sg in siteGroups)
     {
         sg.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(siteGroup_PropertyChanged);
         _originalItemSource.Add(sg);
     }
     gvwSiteGroup.ItemsSource = siteGroups;
     if (!string.IsNullOrEmpty(_selectedSiteGroup)
         && siteGroups.Count(i => i.GroupName == _selectedSiteGroup) > 0)
     {
         gvwSiteGroup.SelectedItem = siteGroups.First(i => i.GroupName == _selectedSiteGroup);
     }
     else if (siteGroups.Count > 0)
     {
         gvwSiteGroup.SelectedItem = siteGroups[0];
     }
     Globals.IsBusy = false;
 }
        private void ReadFromFile(string path = "birth.data")
        {
            try
            {
                var dataset = new List<Data>();
                var info = new StringBuilder();

                foreach (var data in File.ReadAllLines(path))
                {
                    if (data.StartsWith("#"))
                    {
                        info.Append(data + Environment.NewLine);
                        continue;
                    }

                    var values = new List<double>();
                    string[] trainingExample = data.Split(' ');

                    string Id = trainingExample.First();
                    for(int i = 1; i < trainingExample.Length; i++)
                    {
                        values.Add(double.Parse(trainingExample[i], CultureInfo.InvariantCulture));
                    }

                    dataset.Add(new Data {ID = Id, Attributes = values});
                }

                AttrCount = dataset.First().Attributes.Count;
                labelAttrCount.Content = "Attributes Count: " + AttrCount;
                labelExamplesCount.Content = "Examples Count: " + dataset.Count;
                DataSet = dataset;

                FillGrid(dataset);

                for(int i = 0; i < 10; i++)
                {
                    comboBoxClusters.Items.Add(i + 1);
                }
                comboBoxClusters.SelectedIndex = 3;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #28
0
        /// <summary>
        /// Find the nearest DataPoint from each dataSeries from a xValue and yValue
        /// </summary>
        /// <param name="dataSeries"></param>
        /// <param name="internalXValue">internalXValue</param>
        /// <param name="internalYValue">internalYValue</param>
        /// <returns></returns>
        internal static DataPoint GetNearestDataPoint(DataSeries dataSeries, Double xValueAtMousePos, Double yValueAtMousePos)
        {
            DataPoint nearestDataPoint = null;

            // Get all DataPoints order by the XValue distance from the internalXValue.
            List<DataPoint> dataPointsAlongX = (from dp in dataSeries.InternalDataPoints
                                                where
                                                !(RenderHelper.IsFinancialCType(dp.Parent) && dp.InternalYValues == null)
                                                || !(!RenderHelper.IsFinancialCType(dp.Parent) && Double.IsNaN(dp.YValue))
                                                orderby Math.Abs(dp.InternalXValue - xValueAtMousePos)
                                                select dp).ToList();
            
            if (dataPointsAlongX.Count > 0)
            {   
                // Get the internalXValue of the first DataPoint of the ordered list
                Double xValue = dataPointsAlongX[0].InternalXValue;

                // DataPoints along y pixel direction which have same XValue
                List<DataPoint> dataPointsAlongYAxisHavingSameXValue = new List<DataPoint>();

                foreach (DataPoint dp in dataPointsAlongX)
                {
                    if (dp.InternalXValue == xValue)
                        dataPointsAlongYAxisHavingSameXValue.Add(dp);
                }

                if (!Double.IsNaN(yValueAtMousePos))
                {
                    // Sort according to YValue or YValues
                    if (RenderHelper.IsFinancialCType(dataSeries))
                        dataPointsAlongYAxisHavingSameXValue = (from dp in dataPointsAlongYAxisHavingSameXValue
                                                            where (dp.InternalYValues != null)
                                                            orderby Math.Abs(dp.InternalYValues.Max() - yValueAtMousePos)
                                                            select dp).ToList();
                    else
                        dataPointsAlongYAxisHavingSameXValue = (from dp in dataPointsAlongYAxisHavingSameXValue
                                                            where !Double.IsNaN(dp.InternalYValue)
                                                            orderby Math.Abs(dp.InternalYValue - yValueAtMousePos)
                                                            select dp).ToList();
                }

                if (dataPointsAlongYAxisHavingSameXValue.Count > 0)
                    nearestDataPoint = dataPointsAlongYAxisHavingSameXValue.First();
            }

            return nearestDataPoint;
        }
 void ListEquipmentCompleted(List<Equipment> orgList)
 {
     Globals.IsBusy = false;
     _originalItemSource.Clear();
     foreach (Equipment item in orgList)
     {
         item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(EquipmentItem_PropertyChanged);
         _originalItemSource.Add(item);
     }
     gvwEquipments.ItemsSource = orgList;
     if (_selectedEquipmentId > 0 && orgList.Count(i => i.EquipmentId == _selectedEquipmentId) > 0)
     {
         gvwEquipments.SelectedItem = orgList.First(i => i.EquipmentId == _selectedEquipmentId);
     }
     else if (orgList.Count > 0)
     {
         gvwEquipments.SelectedItem = orgList[0];
     }
 }
        void ListSiteCompleted(List<Site> sites)
        {
            Globals.IsBusy = false;
            _originalItemSource.Clear();

            if (this.UserRoleAuths.Count(i => !i.SiteId.HasValue) == 0)
            {
                var abc = (from item in this.UserRoleAuths
                           select item.SiteId).Distinct();
                sites = (from s in sites
                         join a in abc on s.SiteId equals a.Value
                         select s).ToList();
            }

            foreach (Site item in sites)
            {
                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(SiteItem_PropertyChanged);
                _originalItemSource.Add(item);
            }
            gvwSites.ItemsSource = sites;
            if (_seletedSiteId > 0 && sites.Count(i => i.SiteId == _seletedSiteId) > 0)
            {
                gvwSites.SelectedItem = sites.First(i => i.SiteId == _seletedSiteId);
            }
            else if (sites.Count > 0)
            {
                gvwSites.SelectedItem = sites[0];
            }
        }