private void EditPerson_Shown(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных"}; List<Department> departs=new List<Department>(); sp0.WorkingFunction = () => { sp0.StatusText = @"Загрузка данных департаментов"; departs = _dataContexts.IWEntities.Departments.OrderBy(o=>o.Description).ToList(); }; sp0.ShowDialog(this); cbDepartments.DataSource = departs; if (SharedAppData.LoggedUser.DepartmentId != null & _state==FormState.New) { cbDepartments.SelectedValue = SharedAppData.LoggedUser.DepartmentId; } else if (_state == FormState.Edit) { var editPerson = _dataContexts.IWEntities.InstallersWorks_Personalities.SingleOrDefault(p => p.Id == _editId); if (editPerson == null) throw new Exception("Invalid data in database for edit Person!"); cbDepartments.SelectedValue = editPerson.DepartamentId; tbSurname.Text = editPerson.PersonSurname; tbName.Text = editPerson.PersonName; tbPatronymic.Text = editPerson.PersonPatronymic; tbPhone1.Text = editPerson.PersonPhone1; tbPhone2.Text = editPerson.PersonPhone2; tbAddress.Text = editPerson.PersonAddress; } btSave.Enabled = SharedAppData.IsFlagSet(PersonalitiesList.ObjectAccessId, RightsFlags.Change); }
private void RefreshGrid() { MiniSplash_TF sp = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных" }; List<Equipment> equipments = new List<Equipment>(); sp.WorkingFunction = () => { sp.StatusText = @"Загрузка данных"; equipments = _dataContexts.AccEquipmentV2Entities.Equipments.Where(eq => eq.NetworkDescription.Equals(string.Empty) & eq.EquipmentPorts.Any()).OrderBy(o => o.Description).ToList(); }; sp.ShowDialog(this); gvEmptyNetworkName.DataSource = equipments; }
private void EquipmentPortsSelection_Show(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) { Text = @"Загрузка данных", WorkingFunction = () => { _cachedAreas = _dataContext.AccEquipmentV2Entities.Areas.Where(area => area.Equipments.Count > 0).ToList(); } }; sp0.ShowDialog(this); gvAreas.DataSource = _cachedAreas.OrderBy(area=>area.Description).ToList(); }
private void AllEventsReportForm_Shown(object sender, EventArgs e) { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); MiniSplash_TF sp = new MiniSplash_TF(Resources.load4) { Text = @"Загрузка отчета", StatusText = "Подготовка данных" }; sp.WorkingFunction = () => { var data = _dataContexts.AccEquipmentV2Entities.Events .Include(i => i.EquipmentPort.Equipment) .Include(i => i.EquipmentPort.Equipment.Area) .Include(i => i.EquipmentPort) .Include(i => i.EquipmentPort.PortType) .Include(i => i.CustomerSide); _dataContexts.AccEquipmentV2Entities.EntityObjectContext.Refresh(RefreshMode.StoreWins, data); var fullData= data.ToList() .Select(ev => new EventPlainInfo() { Number = ev.Number, CreationDate = ev.CreationDate, Access_Users = ev.Access_Users, CustomerSide = ev.CustomerSide != null ? ev.CustomerSide.Description : ev.EquipmentPort != null ? ev.EquipmentPort.SideLink.EquipmentPort.Equipment.Area.Description : "", EquipmentPort = ev.EquipmentPort, EventIndex = ev.EventIndex.HasValue ? ev.EventIndex.Value : 0, CustomerTitle = (ev.FirmId.HasValue & ev.CustomerId.HasValue) ? _dataContexts.GetCustomerDescription(ev.FirmId.Value, ev.CustomerId.Value) : string.Empty, Tag = ev }) .ToList(); var grouped = fullData.GroupBy(grp => new {grp.Tag.CustomerId, grp.CustomerSide}) .Select(g => new {g.Key.CustomerId, g.Key.CustomerSide, ClosedTrouble = g.Count(i => i.Tag.State == (int)EventState.ClosedEvent & i.Tag.Type == (int)EventType.TroubleEvent), OpenedTrouble = g.Count(i => i.Tag.State == (int)EventState.OpenedEvent & i.Tag.Type == (int)EventType.TroubleEvent), ClosedStandart = g.Count(i => i.Tag.State == (int)EventState.ClosedEvent & i.Tag.Type == (int)EventType.StandartEvent), OpenedStandart = g.Count(i => i.Tag.State == (int)EventState.OpenedEvent & i.Tag.Type == (int)EventType.StandartEvent) }) .OrderByDescending(o => o.CustomerId) .ToList(); RunActionInGUIThread(() => { //dataGridViewCustomed1.AutoGenerateColumns = true; //dataGridViewCustomed1.DataSource = grouped; }); }; sp.ShowDialog(this); }
private void LoadData() { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных", StatusText = @"Загрузка данных" }; sp0.WorkingFunction = () => { _workTypes.Clear(); _workTypes = _dataContexts.IWEntities.InstallersWorks_WorkTypes.OrderBy(o => o.TypeDescription).ToList(); _dataContexts.IWEntities.EntityObjectContext.Refresh(RefreshMode.StoreWins, _workTypes); Extensions.RunActionInGUIThread(() => { gvWorkTypes.DataSource = null; gvWorkTypes.DataSource = _workTypes.ToList(); gvWorkTypes.ClearSelection(); }, _uiScheduler); }; sp0.ShowDialog(this); }
private void DutyForm_Shown(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных", StatusText = @"Загрузка данных" }; sp0.WorkingFunction = () => { var entities = new InstallersWorks_Entities(); Extensions.RunActionInGUIThread(() => { tbReceivers.Text = !string.IsNullOrEmpty(Settings.Default.DutyReceiversList) ? Settings.Default.DutyReceiversList : Settings.Default.DefaultDutyReceiversList; cbPersonalities.DataSource = entities.InstallersWorks_Personalities.OrderBy(o => o.PersonSurname).ToList(); },_uiScheduler); }; sp0.ShowDialog(this); tbReceivers.Enabled = tbSetDefault.Enabled = btSend.Enabled=btAddDuty.Enabled= SharedAppData.IsFlagSet(ObjectAccessId, RightsFlags.Change); }
public void ConnectService() { MiniSplash_TF splash = new MiniSplash_TF(Resources.load1) { Text = @"Запуск приложения", StatusText = @"Поиск сервера уведомлений" }; UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort); udpService.OnReceiveData += (endPoint, data) => { Packet packet = new Packet(data); if (packet.Opcode == Opcodes.ServerFound) { _serverAddress = packet.Data; } }; splash.WorkingFunction = () => { try { List<string> broadcasts = new List<string>(); foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = netif.GetIPProperties(); foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) continue; if (unicast.IPv4Mask == null) continue; byte[] ipAdressBytes = unicast.Address.GetAddressBytes(); byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes(); byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } broadcasts.Add(string.Join(".", broadcastAddress)); } } _serverAddress = string.Empty; udpService.Start(); bool finished = false; int trying = 1; while (!finished && trying <= 5) { splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying; broadcasts.ForEach(ba => { UdpClient client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort); byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack()); client.Send(bytes, bytes.Length, ip); client.Close(); Thread.Sleep(200); }); if (_serverAddress != string.Empty) finished = true; trying++; } } catch (Exception ex) { OnMessageShow(ex.Message); throw; } }; splash.ShowDialog(); #if DEBUG _serverAddress = "10.100.1.47"; #endif if (_serverAddress != string.Empty) { Reconnect(_serverAddress); } else { OnMessageShow("Сервис уведомлений не найден, пытаемся соедениться напрямую!"); Reconnect("10.100.1.21"); } udpService.Stop(); }
//private void ServerHelperInit() // { // _serverHelper = new TcpServerHelper(null,LocalServerPort); // _serverHelper.OnBeforeStop += Unsubscribe; // _serverHelper.OnReceiveData += (info, data) => // { // Packet packet = new Packet(data); // if (packet.Opcode == Opcodes.Invalid) // return; // if (packet.Opcode == Opcodes.ServerShutdown) // { // _serverHelper.Offline(); // MessageBox.Show("server going offline"); // return; // } // if (packet.Opcode == Opcodes.NotifyAll) // { // NotifyData nData = new NotifyData(packet.Data); // MessageBox.Show(nData.Data); // return; // } // }; // _serverHelper.Online(); // } private void button1_Click(object sender, EventArgs e) { MiniSplash_TF splash = new MiniSplash_TF(Resources.load4) { Text = @"Запуск приложения", StatusText = @"Поиск сервера уведомлений" }; UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort); udpService.OnReceiveData += (endPoint, data) => { Packet packet = new Packet(data); if (packet.Opcode == Opcodes.ServerFound) { _serverAddress = packet.Data; } }; splash.WorkingFunction = () => { try { List<string> broadcasts = new List<string>(); foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = netif.GetIPProperties(); foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) continue; if (unicast.IPv4Mask == null) continue; byte[] ipAdressBytes = unicast.Address.GetAddressBytes(); byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes(); byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } broadcasts.Add(string.Join(".", broadcastAddress)); } } _serverAddress = string.Empty; udpService.Start(); bool finished = false; int trying = 1; while (!finished && trying <= 5) { splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying; broadcasts.ForEach(ba => { UdpClient client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort); byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack()); client.Send(bytes, bytes.Length, ip); client.Close(); Thread.Sleep(200); }); if (_serverAddress != string.Empty) finished = true; trying++; } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } }; splash.ShowDialog(this); if (_serverAddress != string.Empty) { if (_clientHelper.Client.Connected) { _clientHelper.SendData(new Packet(Guid.NewGuid(), Opcodes.Unsubscribe, Appid.ToString())); _clientHelper.Stop(); } if (_clientHelper.Connect(_serverAddress, IpDefaultPorts.DefaultTcpServerListenerPort)) { _clientHelper.Start(); } else { MessageBox.Show("not connect to " + _serverAddress); } } else { MessageBox.Show("service not found"); } udpService.Stop(); }
private void TaskEditor_Shown(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных", StatusText = @"Загрузка сотрудников" }; sp0.WorkingFunction = () => { _personsAvailableCache = _dataContexts.IWEntities.InstallersWorks_Personalities.OrderBy(o => o.PersonSurname).ThenBy(o=>o.PersonName).ToList(); List<InstallersWorks_WorkTypes> types = _dataContexts.IWEntities.InstallersWorks_WorkTypes.ToList(); switch (_state) { case FormState.FormEdit: case FormState.FormView: Extensions.RunActionInGUIThread(() => Text = _state == FormState.FormEdit ? @"Редактирование работы" : @"Просмотр работы", _uiScheduler); _loadedWorks = _dataContexts.IWEntities.InstallersWorks_Works .Include(i=>i.InstallersWorks_Personalities) .Include(i=>i.InstallersWorks_WorkTypes) .Where(ws => ws.WorkId == _workId) .AsNoTracking() .ToList(); _defaultWork = _loadedWorks.FirstOrDefault(); if (_defaultWork == default(InstallersWorks_Works)) throw new InvalidDataException(); if (_defaultWork.InstallersWorks_WorkTypes == null) { types.Insert(0, new InstallersWorks_WorkTypes() {Id = Guid.Empty, TypeDescription = "--- Тип работы удален, выберите новый! ---"}); Extensions.RunActionInGUIThread(() => { cbTaskTypes.DataSource = types; cbTaskTypes.SelectedIndex = 0; }, _uiScheduler); } else { Extensions.RunActionInGUIThread(() => { cbTaskTypes.DataSource = types; cbTaskTypes.SelectedValue = _defaultWork.InstallersWorks_WorkTypes.Id; }, _uiScheduler); } _colorMark = _defaultWork.ColorMark; if (_colorMark != null && !string.IsNullOrWhiteSpace(_colorMark)) { string[] fromDb = _colorMark.Split('|'); if (fromDb.Count() == 2) { tbExample.ForeColor = ColorTranslator.FromHtml(fromDb[0]); tbExample.BackColor = ColorTranslator.FromHtml(fromDb[1]); } } _personsActiveCache = _loadedWorks.Select(p => p.InstallersWorks_Personalities ?? new InstallersWorks_Personalities(){Id = Guid.Empty,PersonSurname = "Сотрудник удален"}).ToList(); _personsActiveCache.ForEach(p => { if (p.Id != Guid.Empty && _personsAvailableCache.Any(pa=>pa.Id==p.Id)) _personsAvailableCache.RemoveAll(pa=>pa.Id==p.Id); }); break; case FormState.FormNew: _personsActiveCache = new List<InstallersWorks_Personalities>(); types.Insert(0, new InstallersWorks_WorkTypes() { Id = Guid.Empty, TypeDescription = "--- выберите тип работы ---" }); Extensions.RunActionInGUIThread(() => { cbTaskTypes.DataSource = types; cbTaskTypes.SelectedIndex = 0; }, _uiScheduler); break; default: throw new ArgumentOutOfRangeException(); } Extensions.RunActionInGUIThread(() => { lbAvailablePersons.Tag = _personsAvailableCache; lbActivePersons.Tag = _personsActiveCache; SetPersonListDataSource(lbAvailablePersons, _personsAvailableCache); SetPersonListDataSource(lbActivePersons, _personsActiveCache); if (_state != FormState.FormNew) { _colorMark = _defaultWork.ColorMark; tbEvent.Text = _defaultWork.Event; dpWorkDate.Value = _defaultWork.WorkDate; tbAssignment.Text = _defaultWork.AssNomer; tbAddress.Text = _defaultWork.Address; tbCable.Text = _defaultWork.Cable.HasValue ? _defaultWork.Cable.Value.ToString() : "0"; tbMileage.Text = _defaultWork.Mileage.HasValue ? _defaultWork.Mileage.Value.ToString() : "0"; tbComment.Text = _defaultWork.Comment; btMoveActive.Enabled = btMoveAvail.Enabled = btSave.Enabled = btSelectAddress.Enabled = btSelectAssignment.Enabled = btSelectEvent.Enabled = _state != FormState.FormView; } },_uiScheduler); }; sp0.ShowDialog(this); btSelectAssignment.Enabled = btSelectAddress.Enabled = btSelectEvent.Enabled = SharedAppData.IsFlagsSet(IWMainForm.ObjectAccessId, new[] { RightsFlags.Change, RightsFlags.Add }); }
private void LoadReport() { Guid typeId = Guid.Empty; if (cbWorkTypes.SelectedValue!=null) typeId = (Guid)cbWorkTypes.SelectedValue; MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка отчета", StatusText = @"Загрузка данных отчета" }; sp0.WorkingFunction = () => { InstallersWorks_Entities context = new InstallersWorks_Entities(); var data = context.InstallersWorks_Works .Include(i => i.InstallersWorks_WorkTypes) .Include(i => i.InstallersWorks_Personalities) .Where(w => w.Cable > 0); if (typeId != Guid.Empty) data = data.Where(w => w.WorkTypeId == typeId); if (dpFrom.Enabled) data = data .Where(w => DbFunctions.TruncateTime(w.WorkDate) >= DbFunctions.TruncateTime(dpFrom.Value) & DbFunctions.TruncateTime(w.WorkDate) <= DbFunctions.TruncateTime(dpTo.Value)) .OrderByDescending(o => o.WorkDate); var listData = data.ToList(); var groups = listData.GroupBy(g => g.WorkId); _dataSet.CableData.Clear(); foreach (var grpCable in groups) { var defaultWork = grpCable.FirstOrDefault(); if (defaultWork==default(InstallersWorks_Works)) throw new InvalidDataException(); ReportDataSet.CableDataRow newRow = _dataSet.CableData.NewCableDataRow(); newRow.Id = defaultWork.Id; newRow.Date = defaultWork.WorkDate.Date; newRow.Address = defaultWork.Address; newRow.WorkType = defaultWork.InstallersWorks_WorkTypes.TypeDescription; newRow.Description = !string.IsNullOrEmpty(defaultWork.AssNomer) ? defaultWork.AssNomer : defaultWork.Event; newRow.Length = defaultWork.Cable.HasValue ? defaultWork.Cable.Value : 0; _dataSet.CableData.AddCableDataRow(newRow); } Extensions.RunActionInGUIThread(() => { sp0.StatusText = @"Обновление отчета"; reportViewer.Reset(); reportViewer.LocalReport.DataSources.Clear(); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet", (DataTable)_dataSet.CableData)); reportViewer.LocalReport.ReportEmbeddedResource = "InstallersWork.Reports.Cable.CableSimple.rdlc"; List<ReportParameter> repParams = new List<ReportParameter> { new ReportParameter("CableTotalParam",tbCableTotal.Text), new ReportParameter("ReportHeader1","Отчет о затратах по кабелю за период"), new ReportParameter("ReportHeaderField1", "с " + dpFrom.Value.ToShortDateString() + " по " + dpTo.Value.ToShortDateString()) }; if ((Guid) cbWorkTypes.SelectedValue != Guid.Empty) { var desc = cbWorkTypes.SelectedItem as InstallersWorks_WorkTypes; if (desc==null) throw new InvalidCastException(); repParams.Add(new ReportParameter("ReportHeader2", "по типу " + desc.TypeDescription)); repParams.Add(new ReportParameter("ReportHeaderField2", desc.TypeDescription)); } reportViewer.LocalReport.SetParameters(repParams); reportViewer.RefreshReport(); }, _uiScheduler); }; sp0.ShowDialog(this); }
private void CustomersSidesForm_Shown(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) { Text = @"Загрузка данных абонентов" }; sp0.WorkingFunction = () => { sp0.StatusText= "Загрузка компаний"; _cachedFirms = _dataContexts.NumEquipmentEntities.Firms.Where(item => item.TestFlag.HasValue && !item.TestFlag.Value).OrderBy(firm => firm.FirmName).ToList(); sp0.StatusText= "Загрузка абонентов"; _cachedCustomers = _dataContexts.NumEquipmentEntities.Customers.Where(cust => cust.Visible.HasValue && cust.Visible.Value).ToList(); sp0.StatusText= "Загрузка адресов площадок"; _cachedCustomerSides = _dataContexts.AccEquipmentV2Entities.CustomerSides.ToList(); _defaultOrder = cust => int.Parse(cust.Customer_id.Trim()); Expression<Func<Customer, bool>> currentFirmFilter = cust => cust.FirmId == ((Firm)cbFirms.SelectedItem).FirmId; _compiledCurrentFirmFilter = currentFirmFilter.Compile(); Expression<Func<CustomerSide, Customer, bool>> currentSideFilter = (side, customer) => String.Equals(side.CustomerId.ToString(), customer.Customer_id.Trim()) & side.Firmid == customer.FirmId; _compiledCurrentSideFilter = currentSideFilter.Compile(); }; sp0.ShowDialog(this); Cursor = Cursors.WaitCursor; cbFirms.DataSource = _cachedFirms; cbFirms.SelectedIndex = 3; gvCustomers.DataSource = _cachedCustomers.Where(_compiledCurrentFirmFilter).OrderBy(_defaultOrder).ToList(); Cursor = Cursors.Default; if (FocusedCustomerInfo != null) { Firm custFirm = _cachedFirms.SingleOrDefault(firm => firm.FirmId == FocusedCustomerInfo.FirmId); if (custFirm == null) return; cbFirms.SelectedItem = custFirm; if (FilteredData) { gvCustomers.DataSource = _cachedCustomers.Where(_compiledCurrentFirmFilter) .Where(c => c.FirmId == FocusedCustomerInfo.FirmId & c.Customer_id.Trim() == FocusedCustomerInfo.CustomerId.ToString()) .OrderBy(_defaultOrder) .ToList(); gvCustomers.Rows[0].Selected = true; gvCustomers.BlinkRow(gvCustomers.Rows[0]); gvCustomers_SelectionChanged(gvCustomers, new EventArgs()); } else { var selectedCustomerRow = gvCustomers.Rows.Cast<DataGridViewRow>() .SingleOrDefault( item => { Customer checkCustomer = (Customer)item.DataBoundItem; return (Convert.ToInt32(checkCustomer.Customer_id.Trim()) == FocusedCustomerInfo.CustomerId) & (checkCustomer.FirmId == FocusedCustomerInfo.FirmId); }); if (selectedCustomerRow != null) { gvCustomers.CurrentCell = gvCustomers.Rows[selectedCustomerRow.Index].Cells[0]; selectedCustomerRow.Selected = true; gvCustomers.BlinkRow(selectedCustomerRow); } } if (FocusedSide != null) { var selectedCustomerSideRow = gvSides.Rows.Cast<DataGridViewRow>() .SingleOrDefault( item => { CustomerSide checkSide = (CustomerSide)item.DataBoundItem; return checkSide.Id == FocusedSide.Id; }); if (selectedCustomerSideRow != null) { gvSides.CurrentCell = gvSides.Rows[selectedCustomerSideRow.Index].Cells[0]; selectedCustomerSideRow.Selected = true; gvSides.BlinkRow(selectedCustomerSideRow); } } } }
private void CustomersSidesForm_Shown(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) {Text = @"Загрузка данных абонентов"}; sp0.WorkingFunction = () => { sp0.StatusText = "Загрузка абонентов"; _cachedCustomers = _dataContexts.NumEquipmentEntities.Customers.Where(cust => cust.Visible.HasValue && cust.Visible.Value).ToList(); sp0.StatusText = "Загрузка адресов площадок"; _cachedCustomerSides = _dataContexts.AccEquipmentV2Entities.CustomerSides.ToList(); #region create where for phone numbers ParameterExpression inputType = Expression.Parameter(typeof (Teleph)); var propertyCustomerId = Expression.Property(inputType, "Customer_Id"); var propertyUntilDate = Expression.Property(inputType, "UntilDate"); var propertyTelNum = Expression.Property(inputType, "TelNum"); var currWhere = Expression.Lambda<Func<Teleph, bool>>( Expression.NotEqual( propertyCustomerId, Expression.Constant(null, typeof (string))), inputType); _wherePhoneNumExpression = currWhere; currWhere = Expression.Lambda<Func<Teleph, bool>>( Expression.NotEqual( propertyUntilDate, Expression.Constant(null, typeof (DateTime?))), inputType); _wherePhoneNumExpression = _wherePhoneNumExpression.AndAlso(currWhere); var trimCustomerId = Expression.Call(propertyCustomerId, typeof (string).GetMethod("Trim", Type.EmptyTypes)); var notEmptyCustomerId = Expression.Not(Expression.Call(typeof (string), "IsNullOrEmpty", null, trimCustomerId)); currWhere = Expression.Lambda<Func<Teleph, bool>>(notEmptyCustomerId, inputType); _wherePhoneNumExpression = _wherePhoneNumExpression.AndAlso(currWhere); var trimPhoneNumber = Expression.Call(propertyTelNum, typeof (string).GetMethod("Trim", Type.EmptyTypes)); MethodInfo method = typeof (string).GetMethod("Contains", new[] {typeof (string)}); var constantNumberExpression = Expression.Property(Expression.Constant(this), "NumberTextData"); var containsPhoneNumber = Expression.Call(trimPhoneNumber, method, constantNumberExpression); currWhere = Expression.Lambda<Func<Teleph, bool>>(containsPhoneNumber, inputType); _wherePhoneNumExpression = _wherePhoneNumExpression.AndAlso(currWhere); #endregion _defaultOrder = cust => int.Parse(cust.Customer_id.Trim()); //Expression<Func<CustomerSide, Customer, bool>> // currentSideFilter = (side, customer) => // String.Equals(side.CustomerId.ToString(), customer.Customer_id.Trim()) & // side.Firmid == customer.FirmId; }; sp0.ShowDialog(this); Cursor = Cursors.WaitCursor; //gvCustomers.DataSource = _cachedCustomers.Where(_compiledCurrentFirmFilter).OrderBy(_defaultOrder).ToList(); Cursor = Cursors.Default; //if (FocusedCustomerInfo != null) //{ // Firm custFirm = _cachedFirms.SingleOrDefault(firm => firm.FirmId == FocusedCustomerInfo.FirmId); // if (custFirm == null) // return; // cbFirms.SelectedItem = custFirm; // if (FilteredData) // { // gvCustomers.DataSource = // _cachedCustomers.Where(_compiledCurrentFirmFilter) // .Where(c => c.FirmId == FocusedCustomerInfo.FirmId & c.Customer_id.Trim() == FocusedCustomerInfo.CustomerId.ToString()) // .OrderBy(_defaultOrder) // .ToList(); // gvCustomers.Rows[0].Selected = true; // gvCustomers.BlinkRow(gvCustomers.Rows[0]); // gvCustomers_SelectionChanged(gvCustomers, new EventArgs()); // } // else // { // var selectedCustomerRow = // gvCustomers.Rows.Cast<DataGridViewRow>() // .SingleOrDefault( // item => // { // Customer checkCustomer = (Customer)item.DataBoundItem; // return (Convert.ToInt32(checkCustomer.Customer_id.Trim()) == FocusedCustomerInfo.CustomerId) & (checkCustomer.FirmId == FocusedCustomerInfo.FirmId); // }); // if (selectedCustomerRow != null) // { // gvCustomers.CurrentCell = gvCustomers.Rows[selectedCustomerRow.Index].Cells[0]; // selectedCustomerRow.Selected = true; // gvCustomers.BlinkRow(selectedCustomerRow); // } // } // if (FocusedSide != null) // { // var selectedCustomerSideRow = // gvSides.Rows.Cast<DataGridViewRow>() // .SingleOrDefault( // item => // { // CustomerSide checkSide = (CustomerSide)item.DataBoundItem; // return checkSide.Id == FocusedSide.Id; // }); // if (selectedCustomerSideRow != null) // { // gvSides.CurrentCell = gvSides.Rows[selectedCustomerSideRow.Index].Cells[0]; // selectedCustomerSideRow.Selected = true; // gvSides.BlinkRow(selectedCustomerSideRow); // } // } //} }
private void EventEditor_Shown(object sender, EventArgs e) { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Top = 1; if (Screen.FromControl(Owner).Bounds.Height <= 768) { tlMain.RowStyles[3].Height = tlMain.RowStyles[3].Height - 40; } #region load data MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) {Text = @"Загрузка данных редактора"}; sp0.WorkingFunction = () => { sp0.StatusText = "Загрузка данных"; _contacts = _dataContexts.AccEquipmentV2Entities.Events .Where(c => !c.CustomerInfo.Equals(string.Empty) & c.CustomerInfo != null) .GroupBy(g => g.CustomerInfo) .Select(g => g.Key.Trim()).ToList(); _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = false; _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = false; _receiversLists = _dataContexts.AccEquipmentV2Entities.NotifyReceiversLists .Include(i=>i.NotifyReceivers) .OrderBy(o => o.Description) .AsNoTracking() .ToList(); _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = true; _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = true; switch (_requestAction) { case RequestAction.New: { int number = _dataContexts.AccEquipmentV2Entities.Events.Count() + 5000; _clonedEvent = new Event() { CreationDate = DateTime.Now, CreationUserId = SharedAppData.LoggedUser.Id, Access_Users = SharedAppData.LoggedUser, Id = Guid.NewGuid(), State = (int) EventState.OpenedEvent, Type = (int) EventType.StandartEvent, Number = number, EventIndex = 0 }; _clonedEvent.EventStatusHistories.Add(new EventStatusHistory() { ChangedDate = DateTime.Now, ChangedInfo = @"Создание заявки", ChangedUserId = SharedAppData.LoggedUser.Id, Access_Users = SharedAppData.LoggedUser, Id = Guid.NewGuid(), NewState = (int) EventState.OpenedEvent, NewType = (int) EventType.StandartEvent, OldState = -1, OldType = -1, Event = _clonedEvent }); break; } case RequestAction.Edit: _clonedEvent = LoadEventFromDb(_managedEvent); break; case RequestAction.Close: _clonedEvent = LoadEventFromDb(_managedEvent); //_clonedEvent.CheckUserId = SharedAppData.LoggedUser.Id; _clonedEvent.CheckUserId = _managedEvent.CreationUserId; _clonedEvent.EventStatusHistories.Add(new EventStatusHistory() { ChangedDate = DateTime.Now, ChangedInfo = @"Закрытие заявки", ChangedUserId = SharedAppData.LoggedUser.Id, Access_Users = SharedAppData.LoggedUser, Id = Guid.NewGuid(), OldState = _clonedEvent.State, NewState = (int) EventState.ClosedEvent, OldType = _clonedEvent.Type, NewType = _clonedEvent.Type, Event = _clonedEvent, }); break; case RequestAction.Renew: { int number = _dataContexts.AccEquipmentV2Entities.Events.Count() + 5000; _clonedEvent = new Event() { CreationDate = DateTime.Now, CreationUserId = SharedAppData.LoggedUser.Id, Access_Users = SharedAppData.LoggedUser, Id = Guid.NewGuid(), State = (int) EventState.OpenedEvent, Type = _managedEvent.Type == (int) EventType.RemedyEvent ? (int) EventType.TroubleEvent : _managedEvent.Type, Number = number, CustomerId = _managedEvent.CustomerId, FirmId = _managedEvent.FirmId, CustomerInfo = _managedEvent.CustomerInfo, Description = _managedEvent.Description, CustomerSideId = _managedEvent.CustomerSideId, EquipmentPortId = _managedEvent.EquipmentPortId, EventIndex = _managedEvent.EventIndex }; _clonedEvent.EventStatusHistories.Add(new EventStatusHistory() { ChangedDate = DateTime.Now, ChangedInfo = @"Повторение заявки №" + _managedEvent.Number, ChangedUserId = SharedAppData.LoggedUser.Id, Access_Users = SharedAppData.LoggedUser, Id = Guid.NewGuid(), NewState = (int) EventState.OpenedEvent, NewType = _managedEvent.Type, OldState = _managedEvent.State, OldType = _managedEvent.Type, EventId = _clonedEvent.Id, Event = _clonedEvent, }); foreach (var eventComment in _managedEvent.EventComments) { _clonedEvent.EventComments.Add(new EventComment() { Access_Users = eventComment.Access_Users, UserId = eventComment.Access_Users.Id, CreationDate = eventComment.CreationDate, Description = eventComment.Description, Id = Guid.NewGuid(), Event = _clonedEvent, EventId = _clonedEvent.Id }); } _dataContexts.AccEquipmentV2Entities.Events.Attach(_clonedEvent); _dataContexts.AccEquipmentV2Entities.Entry(_clonedEvent).Reference(ee => ee.CustomerSide).Load(); _dataContexts.AccEquipmentV2Entities.Entry(_clonedEvent).Reference(ee => ee.EquipmentPort).Load(); _dataContexts.AccEquipmentV2Entities.EventIndexValues.Where(index => index.OvnerEventid == _managedEvent.Id) .ToList() .ForEach(index => _indexValues.Add(new IndexValues() { Description = index.Description, Value = index.Value, SortIndex = index.SortIndex })); break; } default: throw new ArgumentOutOfRangeException(); } if (!_indexValues.Any()) _dataContexts.AccEquipmentV2Entities.EventIndexValues.Where(index => index.OvnerEventid == _clonedEvent.Id) .ToList() .ForEach(index => _indexValues.Add(new IndexValues() {SortIndex = index.SortIndex, Description = index.Description, Value = index.Value})); }; sp0.ShowDialog(this); #endregion #region Init visual elements //TODO:Apply right cbReceiversLists.DataSource = _receiversLists; cbReceiversLists.SelectedValue = Properties.Settings.Default.LastReceiversListId != Guid.Empty ? Properties.Settings.Default.LastReceiversListId : ENotifyReceivers.StandartGuid; tbNumber.Text = _clonedEvent.Number.ToString(); nbCustomerIndex.Text = _clonedEvent.EventIndex.HasValue ? _clonedEvent.EventIndex.Value.ToString() : "0"; tbCreationUser.Text = _clonedEvent.Access_Users.Description + @" [" + (_clonedEvent.Access_Users.Department != null ? _clonedEvent.Access_Users.Department.Description : "Неизвестное подразделение") + @"]"; tbCreationDate.Text = _clonedEvent.CreationDate.ToString("MM/dd/yyyy H:mm"); tbCustomer.Text = _clonedEvent.FirmId.HasValue & _clonedEvent.CustomerId.HasValue ? _dataContexts.GetCustomerDescription(_clonedEvent.FirmId.Value, _clonedEvent.CustomerId.Value) : string.Empty; if (_clonedEvent.CustomerSide != null) { tbCustomerSide.Text = _clonedEvent.CustomerSide.Description; } else { if (_clonedEvent.EquipmentPort != null) { tbCustomerSide.Text = _clonedEvent.EquipmentPort.Equipment.Area.Description; } } tbInfo.Text = _clonedEvent.Description; tbCustomerInfo.Text = _clonedEvent.CustomerInfo; var port = _clonedEvent.EquipmentPort; if (port != null) { if (port.SideLink!=null && port.SideLink.LinkType == (int)SideLinkType.toEquipmentPort) tbCustomerPort.Text = GetPortFullDescription(port.SideLink.EquipmentPort); else tbCustomerPort.Text = GetPortFullDescription(port); } else tbCustomerPort.Text = string.Empty; cbType.SelectedIndexChanged -= cbType_SelectedIndexChanged; cbType.DataSource = Enum.GetValues(typeof (EventType)) .Cast<EventType>() .Select(c => new KeyValuePair<string, EventType>(c.GetAttributeValue<DescriptionAttribute, string>(x => x.Description), c)) .Where(k => k.Value < EventType.ComplexRemedyTrouble) .ToList(); cbType.SelectedValue = (EventType) _clonedEvent.Type; cbType.SelectedIndexChanged += cbType_SelectedIndexChanged; _firstType = (EventType) _clonedEvent.Type; cbState.DataSource = Enum.GetValues(typeof (EventState)) .Cast<EventState>() .Select(c => new KeyValuePair<string, EventState>(c.GetAttributeValue<DescriptionAttribute, string>(x => x.Description), c)) .Where(k => !string.IsNullOrEmpty(k.Key)) .ToList(); cbState.SelectedValue = (EventState) _clonedEvent.State; cbSendENotify.Checked = (EventType) cbType.SelectedValue != EventType.StandartEvent & (EventType) cbType.SelectedValue != EventType.RemedyEvent; switch (_requestAction) { case RequestAction.New: Text = @"Добавление новой заявки"; cbType.SelectedValue = EventType.TroubleEvent; break; case RequestAction.Edit: { Text = @"Просмотр заявки"; bool isOwner = SharedAppData.LoggedUser.Id == _clonedEvent.CreationUserId; tbInfo.Enabled = isOwner; if (_clonedEvent.State == (int) EventState.ClosedEvent) { if (_clonedEvent.Access_Users1 == null) throw new Exception("Invalid data in closed event!!!"); if (!_clonedEvent.CloseDate.HasValue & !_clonedEvent.CheckDate.HasValue) throw new Exception("Invalid data in closed event!!!"); btSelectCustomerSide.Enabled = btSelectCustomer.Enabled = btSelectCustomerPort.Enabled = false; gbEventCloseInfo.Visible = true; dpClosedDate.Value = _clonedEvent.CloseDate ?? DateTime.Now; dpCheckedDate.Value = _clonedEvent.CheckDate ?? DateTime.Now; tbClosePerson.Text = _clonedEvent.ClosePerson; tbClosePerson.Enabled = false; //tbCheckedUser.Text = _clonedEvent.Access_Users1.Description + @" [" + // (_clonedEvent.Access_Users1.Department != null ? _clonedEvent.Access_Users1.Department.Description : "Неизвестное подразделение") + @"]"; tbCheckedUser.SelectedIndexChanged -= tbCheckedUser_SelectedIndexChanged; tbCheckedUser.DataSource = _dataContexts.AccEquipmentV2Entities.Access_Users.OrderBy(o => o.Description).ToList(); tbCheckedUser.SelectedIndexChanged += tbCheckedUser_SelectedIndexChanged; tbCheckedUser.SelectedValue = _clonedEvent.Access_Users1.Id; tbCheckedUser.Enabled = false; tbClosedInfo.Text = _clonedEvent.CloseInfo; this.FilterControls(f => f is TextBox).ForEach(c => { TextBox box = (c as TextBox); if (box != null) box.ReadOnly = true; }); btAddComment.Enabled = btSave.Enabled = cbType.Enabled = dpClosedDate.Enabled = dpCheckedDate.Enabled = nbCustomerIndex.Enabled = cbSendENotify.Enabled = false; } else { btSelectCustomerSide.Enabled = _clonedEvent.CustomerSide != null; btSelectCustomer.Enabled = _clonedEvent.FirmId.HasValue & _clonedEvent.CustomerId.HasValue; btSelectCustomerPort.Enabled = _clonedEvent.EquipmentPort != null; } break; } case RequestAction.Close: { Text = @"Закрытие заявки"; tbClosePerson.DataSource = _dataContexts.AccEquipmentV2Entities.Events.Where(ev => ev.ClosePerson != string.Empty & ev.ClosePerson != null).GroupBy(grp => grp.ClosePerson).Select(grp => grp.Key).ToList(); tbClosePerson.SelectedIndex = -1; gbEventCloseInfo.Visible = true; btSelectCustomerSide.Enabled = btSelectCustomer.Enabled = btSelectCustomerPort.Enabled = false; cbState.SelectedValue = EventState.ClosedEvent; cbType.Enabled = false; nbCustomerIndex.ReadOnly = true; //tbCustomerInfo.ReadOnly = true; //tbCheckedUser.Text = _clonedEvent.Access_Users1.Description + @" [" + // (_clonedEvent.Access_Users1.Department != null ? _clonedEvent.Access_Users1.Department.Description : "Неизвестное подразделение") + @"]"; tbCheckedUser.SelectedIndexChanged -= tbCheckedUser_SelectedIndexChanged; tbCheckedUser.DataSource = _dataContexts.AccEquipmentV2Entities.Access_Users.OrderBy(o => o.Description).ToList(); tbCheckedUser.SelectedIndexChanged += tbCheckedUser_SelectedIndexChanged; tbCheckedUser.SelectedValue = SharedAppData.LoggedUser.Id; tbInfo.ReadOnly = true; break; } case RequestAction.Renew: Text = @"Возобновление заявки"; break; default: throw new ArgumentOutOfRangeException(); } gvEventHistory.DataSource = _clonedEvent.EventStatusHistories.OrderBy(o => o.ChangedDate).ToList(); gvEventComments.DataSource = _clonedEvent.EventComments.OrderBy(o => o.CreationDate).ToList(); ListBox boxl = new ListBox(); boxl.Items.AddRange(_contacts.ToArray<object>()); tbCustomerInfo.DropDownControl = boxl; #endregion }
public void RefreshData(object sender, EventArgs e) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) {Text = @"Загрузка отчета"}; sp0.WorkingFunction = () => { sp0.StatusText= @"Загрузка данных"; LoadData(); }; sp0.ShowDialog(this); SetDataSources(); }
private void LoadData() { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных", StatusText = @"Загрузка данных о нарядах" }; sp0.WorkingFunction = () => { _assInfos = new List<AssInfo>(); NumEquipmentsDataContext context = new NumEquipmentsDataContext(); var data = context.NumEquipmentEntities.AssignmentStates .Where(state => state.Created >= DbFunctions.AddDays(dpFrom.Value, -1) & state.Created <= DbFunctions.AddDays(dpTo.Value, 1)) .Join( context.NumEquipmentEntities.Assignments, state => state.Nomer, assignment => assignment.Nomer, (state, assignment) => new { assignment.FirmId, assignment.Customer_Id, assignment.Nomer, assignment.Address, assignment.Kur_desc, assignment.Printed, assignment.Closed, state.Created }); if (cbAssAddData.Checked) { _assInfos = (from ass in data from cust in context.NumEquipmentEntities.Customers .Where(c => c.FirmId == ass.FirmId) .Where(c => c.Customer_id == ass.Customer_Id) .DefaultIfEmpty() select new AssInfo() { Nomer = ass.Nomer, Address = ass.Address, Kur_Desc = ass.Kur_desc, Customer = cust.Title, Created = ass.Created, Closed = ass.Closed.Value, Printed = ass.Printed.Value }).OrderByDescending(o => o.Created).ToList(); } else { _assInfos = data.Select(d => new AssInfo() { Nomer = d.Nomer, Address = d.Address, Kur_Desc = "", Customer ="", Created = d.Created, Closed = d.Closed.Value, Printed = d.Printed.Value }).OrderByDescending(o => o.Created).ToList(); } Extensions.RunActionInGUIThread(() => { SetGridVisualStyle(); gvAssignments.DataSource = _assInfos; }, _uiScheduler); }; sp0.ShowDialog(this); }
private void LoadReport() { _dataLoading = true; List<CustomerInfo> customers = new List<CustomerInfo>(); MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка отчета", StatusText = @"Загрузка данных отчета" }; _watch = null; sp0.WorkingFunction = () => { NumEquipmentsDataContext numEquContext = new NumEquipmentsDataContext(); if (_cachedCustomers==null) _cachedCustomers = numEquContext.NumEquipmentEntities.Customers.Where(cust => cust.Visible.HasValue && cust.Visible.Value).ToList(); InstallersWorks_Entities context = new InstallersWorks_Entities(); var data = context.InstallersWorks_Works .Include(i => i.InstallersWorks_WorkTypes); if (dpFrom.Enabled) data = data .Where(w => DbFunctions.TruncateTime(w.WorkDate) >= DbFunctions.TruncateTime(dpFrom.Value) & DbFunctions.TruncateTime(w.WorkDate) <= DbFunctions.TruncateTime(dpTo.Value)); data = data.OrderByDescending(o => o.WorkDate); EventsDataContext eventsContext = new EventsDataContext(); foreach (var grp in data.GroupBy(work => work.WorkId)) { var firstWork = grp.FirstOrDefault(); if (firstWork == default(InstallersWorks_Works)) { throw new InvalidDataException("getting firstWork"); } if (!string.IsNullOrEmpty(firstWork.Event)) //авария { var workEvent = eventsContext.EventsEntities.Events.FirstOrDefault(e => e.Number.ToString() == firstWork.Event); if (workEvent==null) throw new InvalidDataException("getting workEvent"); int firmId = workEvent.FirmId.HasValue ? workEvent.FirmId.Value : -1; int customerId = workEvent.CustomerId.HasValue ? workEvent.CustomerId.Value : -1; if (firmId<0 | customerId <0) throw new InvalidDataException("getting customer info"); customers.Add(new CustomerInfo() { Address = firstWork.Address, FirmId = firmId, CustomerId = customerId, WorkType = firstWork.InstallersWorks_WorkTypes.TypeDescription }); } else if (!string.IsNullOrEmpty(firstWork.AssNomer)) //наряд { var workAssignment = numEquContext.NumEquipmentEntities.Assignments.SingleOrDefault(a => a.Nomer == firstWork.AssNomer); if (workAssignment == null) throw new InvalidDataException("getting workAssignment"); int firmId = workAssignment.FirmId; int customerId = Convert.ToInt32(workAssignment.Customer_Id); customers.Add(new CustomerInfo() { Address = firstWork.Address, FirmId = firmId, CustomerId = customerId, WorkType = firstWork.InstallersWorks_WorkTypes.TypeDescription }); } else //другое { customers.Add(new CustomerInfo() { Address = firstWork.Address, Title = "Без номера договора", FirmId = -1, CustomerId = -1, WorkType = firstWork.InstallersWorks_WorkTypes.TypeDescription }); } } foreach (CustomerInfo customerInfo in customers) { var cli = customerInfo; if (cli.FirmId != -1) { var ci = _cachedCustomers.SingleOrDefault(c => c.FirmId == cli.FirmId & c.Customer_id.Trim() == cli.CustomerId.ToString()); customerInfo.Title = ci == null ? "Абонент удален" : ci.Title; } } _dataSet.PerAbonentDataSimple.Clear(); foreach (CustomerInfo customerInfo in customers) { ReportDataSet.PerAbonentDataSimpleRow newRow = _dataSet.PerAbonentDataSimple.NewPerAbonentDataSimpleRow(); newRow.Firmid = customerInfo.FirmId; newRow.CustomerId = customerInfo.CustomerId; newRow.Address = customerInfo.Address; newRow.WorkType = customerInfo.WorkType; newRow.Title = customerInfo.Title; _dataSet.PerAbonentDataSimple.AddPerAbonentDataSimpleRow(newRow); } Extensions.RunActionInGUIThread(() => { sp0.StatusText = @"Обновление отчета"; SetReportSource(); }, _uiScheduler); }; sp0.ShowDialog(this); _dataLoading = false; }
private void PerPersonsSelect_Shown(object sender, EventArgs e) { cbPeriod.SelectedIndex = 3; cbDetails.SelectedIndex = Properties.Settings.Default.PerAbonentDetailsLevel; MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка отчета", StatusText = @"Загрузка общих данных" }; sp0.WorkingFunction = () => { InstallersWorks_Entities context = new InstallersWorks_Entities(); context.Configuration.ProxyCreationEnabled = false; context.Configuration.LazyLoadingEnabled= false; var types = context.InstallersWorks_WorkTypes.OrderBy(o => o.TypeDescription).AsNoTracking().ToList(); context.Configuration.ProxyCreationEnabled = true; context.Configuration.LazyLoadingEnabled = true; types.Insert(0, new InstallersWorks_WorkTypes() { Id = Guid.Empty, TypeDescription = "Все типы" }); Extensions.RunActionInGUIThread(() => { cbWorkTypes.DisplayMember = "TypeDescription"; cbWorkTypes.ValueMember = "Id"; cbWorkTypes.DataSource = types.ToList(); }, _uiScheduler); }; sp0.ShowDialog(this); cbWorkTypes.SelectedValue = Guid.Empty; btSendReport.Enabled = SharedAppData.IsAccesible(ReportSenderForm.ObjectAccessId); LoadReport(); }
private void RefreshData() { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) { Text = @"Загрузка данных редактора" }; sp0.WorkingFunction = () => { sp0.StatusText = "Загрузка данных"; var where = GenerateWhereTree(); var contactsQuery = _dataContexts.AccEquipmentV2Entities.EmergencyContacts.OrderBy(ec => ec.PlaceDescription); _contacts = @where == null ? contactsQuery.ToList() : contactsQuery.Where(@where).ToList(); }; sp0.ShowDialog(this); gvContactsList.DrawRowNumber = false; gvContactsList.DataSource = _contacts; }
private void EventsMainForm_Shown(object sender, EventArgs e) { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); bool isRestarting = false; List<Access_Users> users = new List<Access_Users>(); MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) {Text = @"Запуск приложения"}; sp0.WorkingFunction = () => { #region Stage1 (Update app) sp0.StatusText = "Проверка обновлений для программы"; string message; if (!CheckApplicationUpdateAvailable(out message)) { if (message != string.Empty) throw new Exception(message); } else { try { ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; sp0.StatusText = @"Обновление приложения"; Properties.Settings.Default.FirstUse = true; Properties.Settings.Default.Save(); if (Properties.Settings.Default.UpgradeRequired) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } ad.Update(); MessageBox.Show(this, @"Обновления приложения прошло успешно, нажмите ОК для перезапуска программы", "", MessageBoxButtons.OK); isRestarting = true; Invoke(new Action(Application.Restart)); } catch (DeploymentDownloadException dde) { MessageBox.Show(this, @"Обновление для приложения завершилась с ошибкой: " + dde.Message); Application.Exit(); } } #endregion #region Detect Debug|Release run #if DEBUG if (!Debugger.IsAttached) { Text += @"Попытка запуска отладочной версии программы без среды разработки! Переустановите приложение!"; //throw new Exception(@"Попытка запуска отладочной версии программы без среды разработки! Переустановите приложение!"); } #else //if (Debugger.IsAttached) //{ // throw new Exception(@"Запущена релизная версия программы из среды разработки! Измените платформу на Debug!"); //} #endif #endregion #region Stage2 (database connect) sp0.StatusText = "Подключение к базе данных"; _dataContexts = new MainDataContexts(DataConsumers.Events_V2); _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = false; _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = false; var tUsers = _dataContexts.AccEquipmentV2Entities.Access_Users.OrderBy(u => u.Description) .Include(i => i.Department) .Select(u => new { u.Description, u.Id, u.IsAdmin, u.DepartmentId, Password = "", u.Email }) .ToList(); tUsers.ForEach(t => users.Add(new Access_Users() {Id = t.Id, Description = t.Description, IsAdmin = t.IsAdmin, DepartmentId = t.DepartmentId, Email = t.Email})); _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = true; _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = true; SharedAppData.HistoryStore = new HistoryStore(); //TODO:implement history! #endregion }; sp0.ShowDialog(this); if (isRestarting) return; #region Stage 3 Authorization if (users == null) { throw new Exception(@"Неизвествная ошибка в программе"); } Access_Users fakeUser = new Access_Users() {Id = Guid.Empty, Description = "--- выберите пользователя для входа в систему ---"}; users.Insert(0, fakeUser); InputLogin input = new InputLogin { ComboBox1 = { DisplayMember = "Description", ValueMember = "Id", DataSource = users } }; var selectedUser = ((List<Access_Users>) input.ComboBox1.DataSource).SingleOrDefault(u => u.Id == Properties.Settings.Default.LastLoggedId); input.ComboBox1.SelectedItem = selectedUser ?? fakeUser; input.btnOk.Click += (_, __) => { if (input.ComboBox1.SelectedItem == fakeUser) { input.DialogResult = DialogResult.None; return; } var authUser = (Access_Users) input.ComboBox1.SelectedItem; bool? checkResult = _dataContexts.AccEquipmentV2Entities.sp_CheckLogin(authUser.Id, input.InputLine1.Text).SingleOrDefault(); if (checkResult.HasValue && checkResult.Value) { input.DialogResult = DialogResult.OK; } else { MessageBox.Show(@"Неправильные данные для авторизации!"); SharedAppData.HistoryStore.AddHistoryEvent("LoginFailed", "RequestUser: "******"A0E4686D-9CFD-4868-8759-8C3EBEAA40E3".ToLower()); _dataContexts.AccEquipmentV2Entities.Access_Users.Attach(SharedAppData.LoggedUser); _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = false; _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = false; _dataContexts.AccEquipmentV2Entities.Entry(SharedAppData.LoggedUser).Collection(r => r.Access_Associations).Load(); _dataContexts.AccEquipmentV2Entities.Entry(SharedAppData.LoggedUser).Reference(r => r.Department).Load(); _dataContexts.AccEquipmentV2Entities.Configuration.ProxyCreationEnabled = true; _dataContexts.AccEquipmentV2Entities.Configuration.LazyLoadingEnabled = true; SharedAppData.HistoryStore.AddHistoryEvent("LoginComplete", "RequestUser: "******" [" + SharedAppData.LoggedUser.Description + @"]"; btEReceivers.Visible = SharedAppData.LoggedUser.IsAdmin; if (!SharedAppData.IsAccesible(ObjectAccessId)) { MessageBox.Show(@"Отсутсвуют права на использование приложения!"); Application.Exit(); return; } #endregion #region Stage 4 Continue startup MiniSplash_TF sp = new MiniSplash_TF(Resources.load4) { Text = @"Запуск приложения", StatusText = "Загрузка дополнительных данных", WorkingFunction = () => { _dataContexts.RefreshSideLinkInfos(); _manager = new ENotifySenderManager(_dataContexts,this); } }; sp.ShowDialog(); #endregion #region NotifyServiceClient init _clientProcessor = new ClientProcessor(); _clientProcessor.OnServerOnline += (message, icon) => RunActionInGUIThread(() => { btNotifyDisconnect.Enabled = true; btNotifyConnect.Enabled = false; notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); }); _clientProcessor.OnMessageShow += (message, icon) => RunActionInGUIThread(() => { if (icon == ToolTipIcon.Error) { btNotifyDisconnect.Enabled = false; btNotifyConnect.Enabled = true; notifyIcon.ShowBalloonTip(10, @"Ошибка", message, icon); } else { notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); } }); _clientProcessor.OnServerOffline += (message, icon) => RunActionInGUIThread(() => { btNotifyDisconnect.Enabled = false; btNotifyConnect.Enabled = true; notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); }); _clientProcessor.OnReceiveNotifyApp += (data) => RunActionInGUIThread(() => { Guid eventId; NotifyData notifyData = new NotifyData(data); if (!Guid.TryParse(notifyData.Data, out eventId)) { notifyIcon.ShowBalloonTip(5, @"Уведомление", @"Получены неправильные данные о обновленной заявке!", ToolTipIcon.Info); return; } else { string message = "Данные о заявках обновились"; if (!_dataHandlerLoading) { _dataHandlerLoading = true; RefreshCurrentPage(); _dataHandlerLoading = false; } var eventRefreshed = _dataContexts.AccEquipmentV2Entities.Events.SingleOrDefault(ev => ev.Id == eventId); if (eventRefreshed != null) { int customerId = eventRefreshed.CustomerId.HasValue ? eventRefreshed.CustomerId.Value : 0; int firmId = eventRefreshed.FirmId.HasValue ? eventRefreshed.FirmId.Value : 0; string[] customerInfo = _dataContexts.GetCustomerDescription2(firmId, customerId); message = string.Format("Заявка №{0} {1}, {2} - данные обновились!", eventRefreshed.Number, customerInfo[0], customerInfo[1]); } notifyIcon.ShowBalloonTip(5, @"Уведомление", message, ToolTipIcon.Error); } }); _clientProcessor.ConnectService(); #endregion #region Visual elements init Cursor = Cursors.WaitCursor; Version version = ApplicationDeployment.IsNetworkDeployed ? ApplicationDeployment.CurrentDeployment.CurrentVersion : System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; VersionLabel.Text = string.Format("Версия:{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); VersionLabel.Visible = true; List<Department> deps = _dataContexts.AccEquipmentV2Entities.Departments.OrderBy(o => o.Description).ToList(); deps.Insert(0, new Department() {Id = Guid.Empty, Description = @"Все подразделения"}); deps.Insert(1, new Department() {Id = _customSelfGuidValue, Description = @"Только свои заявки"}); deps.Insert(2, new Department() {Id = _customSelfDepartmentGuidValue, Description = @"Только заявки своего департамента"}); cbDepartmentFilter.DataSource = deps; List<KeyValuePair<string, int>> data1 = Enum.GetValues(typeof (EventState)) .Cast<EventState>() .Select(c => new KeyValuePair<string, int>(c.GetAttributeValue<DescriptionAttribute, string>(x => x.Description), (int) c)) .Where(k => !string.IsNullOrEmpty(k.Key)) .ToList(); data1.Insert(0, new KeyValuePair<string, int>("Все заявки", -100)); cbEventStateFilter.DataSource = data1; List<KeyValuePair<string, int>> data2 = Enum.GetValues(typeof (EventType)) .Cast<EventType>() .Select(c => new KeyValuePair<string, int>(c.GetAttributeValue<DescriptionAttribute, string>(x => x.Description), (int) c)) .Where(k => !string.IsNullOrEmpty(k.Key)) .ToList(); data2.Insert(0, new KeyValuePair<string, int>("Все заявки", -100)); cbEventTypeFilter.DataSource = data2; if (Settings.Default.SelectedDepartmentId != Guid.Empty) { ChangeDepartmentBox(Settings.Default.SelectedDepartmentId); cbDepartmentFilter.SelectedValue = Settings.Default.SelectedDepartmentId; } if (Settings.Default.SelectedEventState != -100) { UpdateFilterValue(FilterId.EventState, Settings.Default.SelectedEventState); cbEventStateFilter.SelectedValue = Settings.Default.SelectedEventState; } if (Settings.Default.SelectedEventType != -100) { UpdateFilterValue(FilterId.EventType, Settings.Default.SelectedEventType); cbEventTypeFilter.SelectedValue = Settings.Default.SelectedEventType; } navigationBar.InitSetting(Properties.Settings.Default.NB_SortOrder, Properties.Settings.Default.NB_RowsOnPage, Properties.Settings.Default.NB_OptionsVisible); navigationBar.OnSettingChanged += (s1, s2, s3) => { bool change = false; if (Properties.Settings.Default.NB_SortOrder != s1) { Properties.Settings.Default.NB_SortOrder = s1; change = true; } if (Properties.Settings.Default.NB_RowsOnPage != s2) { Properties.Settings.Default.NB_RowsOnPage = s2; change = true; } if (Properties.Settings.Default.NB_OptionsVisible != s3) { Properties.Settings.Default.NB_OptionsVisible = s3; change = true; } if (change) Properties.Settings.Default.Save(); }; navigationBar.SetDataSouce(_dataContexts.AccEquipmentV2Entities.Events); navigationBar.OnNavigationChanged += RefreshCurrentPage; navigationBar.Visible = true; navigationBar.SortProperty = dcIndex.DataPropertyName; gvEvents.ColumnHeadersVisible = true; ucNumberFilter.OnFilterKeyDown += (_, __) => { if (__.KeyCode == Keys.Return) { UpdateFilterValue(FilterId.Number, ucNumberFilter.FilterText != string.Empty ? ucNumberFilter.FilterText : null); RefreshCurrentPage(); __.Handled = (__.SuppressKeyPress = true); } }; ucNumberFilter.OnClearButtonDown += (_, __) => { UpdateFilterValue(FilterId.Number, null); RefreshCurrentPage(); }; ucCustomerIdFilter.OnFilterKeyDown += (_, __) => { if (__.KeyCode == Keys.Return) { UpdateFilterValue(FilterId.CustomerId, ucCustomerIdFilter.FilterText != string.Empty ? ucCustomerIdFilter.FilterText : null); RefreshCurrentPage(); __.Handled = (__.SuppressKeyPress = true); } }; ucCustomerIdFilter.OnClearButtonDown += (_, __) => { UpdateFilterValue(FilterId.CustomerId, null); RefreshCurrentPage(); }; ucCustomerSideFilter.tbFilterText.Width = 180; ucCustomerSideFilter.OnFilterKeyDown += (_, __) => { if (__.KeyCode == Keys.Return) { UpdateFilterValue(FilterId.CustomerSide, ucCustomerSideFilter.FilterText != string.Empty ? ucCustomerSideFilter.FilterText : null); RefreshCurrentPage(); __.Handled = (__.SuppressKeyPress = true); } }; ucCustomerSideFilter.OnClearButtonDown += (_, __) => { UpdateFilterValue(FilterId.CustomerSide, null); RefreshCurrentPage(); }; ucEquipmentPort.tbFilterText.Width = 180; ucEquipmentPort.OnFilterKeyDown += (_, __) => { if (__.KeyCode == Keys.Return) { UpdateFilterValue(FilterId.EquipmentPort, ucEquipmentPort.FilterText != string.Empty ? ucEquipmentPort.FilterText : null); RefreshCurrentPage(); __.Handled = (__.SuppressKeyPress = true); } }; ucEquipmentPort.OnClearButtonDown += (_, __) => { UpdateFilterValue(FilterId.EquipmentPort, null); RefreshCurrentPage(); }; miMainToolBar.Enabled = true; Cursor = Cursors.Default; #endregion #region First run if (Properties.Settings.Default.FirstUse) { Properties.Settings.Default.FirstUse = false; Properties.Settings.Default.Save(); if (FirstUseData.NeedShow) MessageBox.Show(FirstUseData.FirstUseText, FirstUseData.FirstUseCaption, MessageBoxButtons.OK); } #endregion #if !DEBUG Task.Factory.StartNew(() => { while (_chekingRun) { Thread.Sleep(10000); if (btNotifyConnect.Enabled) { #region scrolling text :) //if (!_startedScrolling) //{ // _startedScrolling = true; // RunActionInGUIThread(() => toolStripStatusLabel1.Text = NotConnectScrolltext); // Task.Factory.StartNew(() => // { // while (_startedScrolling) // { // var size = TextRenderer.MeasureText(toolStripStatusLabel1.Text, toolStripStatusLabel1.Font); // string movingText = toolStripStatusLabel1.Text; // if (size.Width+10 > toolStripStatusLabel1.Width) // { // movingText = movingText.Substring(1) + movingText[0]; // } // else // { // movingText = " " + movingText; // } // RunActionInGUIThread(() => toolStripStatusLabel1.Text = movingText); // Thread.Sleep(50); // } // }); //} #endregion RunActionInGUIThread(() => notifyIcon.ShowBalloonTip(5, @"Уведомление", NotConnectScrolltext, ToolTipIcon.Warning)); } else { //_startedScrolling = false; //RunActionInGUIThread(() => toolStripStatusLabel1.Text = ""); } } }, TaskCreationOptions.LongRunning); #endif }
private void IWMainForm_Shown(object sender, EventArgs e) { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); bool isRestarting = false; List<Access_Users> users = new List<Access_Users>(); MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Запуск приложения",StatusText = ""}; sp0.WorkingFunction = () => { #region Stage1 (Update app) sp0.StatusText = "Проверка обновлений для программы"; string message; if (!CheckApplicationUpdateAvailable(out message)) { if (message != string.Empty) throw new Exception(message); } else { try { ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; sp0.StatusText = @"Обновление приложения"; Properties.Settings.Default.Save(); if (Properties.Settings.Default.UpgradeRequired) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpgradeRequired = false; Properties.Settings.Default.Save(); } ad.Update(); MessageBox.Show(this, @"Обновления приложения прошло успешно, нажмите ОК для перезапуска программы", "", MessageBoxButtons.OK); isRestarting = true; Invoke(new Action(Application.Restart)); } catch (DeploymentDownloadException dde) { MessageBox.Show(this, @"Обновление для приложения завершилась с ошибкой: " + dde.Message); Application.Exit(); } } #endregion #region Detect Debug|Release run #if DEBUG if (!Debugger.IsAttached) { Text += @"Попытка запуска отладочной версии программы без среды разработки! Переустановите приложение!"; //throw new Exception(@"Попытка запуска отладочной версии программы без среды разработки! Переустановите приложение!"); } #else //if (Debugger.IsAttached) //{ // throw new Exception(@"Запущена релизная версия программы из среды разработки! Измените платформу на Debug!"); //} #endif #endregion #region Stage2 (database connect) sp0.StatusText = "Подключение к базе данных"; _dataContexts = new MainDataContexts(); _dataContexts.IWEntities.Configuration.ProxyCreationEnabled = false; _dataContexts.IWEntities.Configuration.LazyLoadingEnabled = false; var tUsers = _dataContexts.IWEntities.Access_Users.OrderBy(u => u.Description) .Include(i => i.Department) .Select(u => new { u.Description, u.Id, u.IsAdmin, u.DepartmentId, Password = "", u.Email }) .ToList(); tUsers.ForEach(t => users.Add(new Access_Users() { Id = t.Id, Description = t.Description, IsAdmin = t.IsAdmin, DepartmentId = t.DepartmentId, Email = t.Email })); _dataContexts.IWEntities.Configuration.ProxyCreationEnabled = true; _dataContexts.IWEntities.Configuration.LazyLoadingEnabled = true; SharedAppData.HistoryStore = new HistoryStore(); //TODO:implement history! #endregion }; sp0.ShowDialog(this); if (isRestarting) return; #region Authorization if (users == null) { throw new Exception(@"Неизвествная ошибка в программе"); } Access_Users fakeUser = new Access_Users() { Id = Guid.Empty, Description = "--- выберите пользователя для входа в систему ---" }; users.Insert(0, fakeUser); InputLogin input = new InputLogin { ComboBox1 = { DisplayMember = "Description", ValueMember = "Id", DataSource = users } }; var selectedUser = ((List<Access_Users>)input.ComboBox1.DataSource).SingleOrDefault(u => u.Id == Properties.Settings.Default.LastLoggedId); input.ComboBox1.SelectedItem = selectedUser ?? fakeUser; input.btnOk.Click += (_, __) => { if (input.ComboBox1.SelectedItem == fakeUser) { input.DialogResult = DialogResult.None; return; } var authUser = (Access_Users)input.ComboBox1.SelectedItem; bool? checkResult = _dataContexts.IWEntities.sp_CheckLogin(authUser.Id, input.InputLine1.Text).SingleOrDefault(); if (checkResult.HasValue && checkResult.Value) { input.DialogResult = DialogResult.OK; } else { MessageBox.Show(@"Неправильные данные для авторизации!"); SharedAppData.HistoryStore.AddHistoryEvent("LoginFailed", "RequestUser: "******"Запуск приложения",StatusText = @"Загрузка данных"}; sp.WorkingFunction = () => { Properties.Settings.Default.LastLoggedId = (Guid) input.ComboBox1.SelectedValue; Properties.Settings.Default.Save(); SharedAppData.LoggedUser = (Access_Users) input.ComboBox1.SelectedItem; _dataContexts.IWEntities.Access_Users.Attach(SharedAppData.LoggedUser); _dataContexts.IWEntities.Configuration.ProxyCreationEnabled = false; _dataContexts.IWEntities.Configuration.LazyLoadingEnabled = false; _dataContexts.IWEntities.Entry(SharedAppData.LoggedUser).Collection(r => r.Access_Associations).Load(); _dataContexts.IWEntities.Entry(SharedAppData.LoggedUser).Reference(r => r.Department).Load(); _dataContexts.IWEntities.Configuration.ProxyCreationEnabled = true; _dataContexts.IWEntities.Configuration.LazyLoadingEnabled = true; SharedAppData.HistoryStore.AddHistoryEvent("LoginComplete", "RequestUser: "******" [" + SharedAppData.LoggedUser.Description + @"]"; if (!SharedAppData.IsAccesible(ObjectAccessId)) { MessageBox.Show(@"Отсутсвуют права на использование приложения!",@"Ошибка!",MessageBoxButtons.OK,MessageBoxIcon.Error); Application.Exit(); return; } #endregion #region Init visual element Version version = ApplicationDeployment.IsNetworkDeployed ? ApplicationDeployment.CurrentDeployment.CurrentVersion : System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; VersionLabel.Text = string.Format("Версия:{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); VersionLabel.Visible = true; navigationBar.InitSetting(Properties.Settings.Default.NB_SortOrder, Properties.Settings.Default.NB_RowsOnPage, Properties.Settings.Default.NB_OptionsVisible); navigationBar.OnSettingChanged += (s1, s2, s3) => { bool change = false; if (Properties.Settings.Default.NB_SortOrder != s1) { Properties.Settings.Default.NB_SortOrder = s1; change = true; } if (Properties.Settings.Default.NB_RowsOnPage != s2) { Properties.Settings.Default.NB_RowsOnPage = s2; change = true; } if (Properties.Settings.Default.NB_OptionsVisible != s3) { Properties.Settings.Default.NB_OptionsVisible = s3; change = true; } if (change) Properties.Settings.Default.Save(); }; LoadData(); navigationBar.SetDataSourceList<WorkInfo>(_totalWorks); navigationBar.OnNavigationChanged += ()=> RefreshCurrentPage(); navigationBar.Visible = true; miAddTask.Enabled = SharedAppData.IsFlagSet(ObjectAccessId, RightsFlags.Add); miDeleteTask.Enabled = SharedAppData.IsFlagSet(ObjectAccessId, RightsFlags.Delete); miChangeTask.Enabled = SharedAppData.IsFlagsSet(ObjectAccessId, new[] {RightsFlags.Change, RightsFlags.View}); RefreshCurrentPage(false); #endregion #region Notifier service connection _clientProcessor = new ClientProcessor(); _clientProcessor.OnServerOnline += (message, icon) => Extensions.RunActionInGUIThread(() => { btNotifyDisconnect.Enabled = true; btNotifyConnect.Enabled = false; notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); },_uiScheduler); _clientProcessor.OnMessageShow += (message, icon) => Extensions.RunActionInGUIThread(() => { if (icon == ToolTipIcon.Error) { btNotifyDisconnect.Enabled = false; btNotifyConnect.Enabled = true; notifyIcon.ShowBalloonTip(10, @"Ошибка", message, icon); } else { notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); } }, _uiScheduler); _clientProcessor.OnServerOffline += (message, icon) => Extensions.RunActionInGUIThread(() => { btNotifyDisconnect.Enabled = false; btNotifyConnect.Enabled = true; notifyIcon.ShowBalloonTip(5, @"Уведомление", message, icon); },_uiScheduler); _clientProcessor.OnReceiveNotifyApp += (data) => Extensions.RunActionInGUIThread(() => { Guid eventId; NotifyData notifyData = new NotifyData(data); if (!Guid.TryParse(notifyData.Data, out eventId)) { notifyIcon.ShowBalloonTip(5, @"Уведомление", @"Получены неправильные данные в обновлении!", ToolTipIcon.Error); return; } if (!_dataHandlerLoading) { _dataHandlerLoading = true; RefreshCurrentPage(); _dataHandlerLoading = false; } notifyIcon.ShowBalloonTip(5, @"Уведомление", @"Данные обновились!", ToolTipIcon.Info); },_uiScheduler); _clientProcessor.ConnectService(); #endregion Task.Factory.StartNew(() => { while (_chekingRun) { Thread.Sleep(10000); if (btNotifyConnect.Enabled) { #region scrolling text :) //if (!_startedScrolling) //{ // _startedScrolling = true; // RunActionInGUIThread(() => toolStripStatusLabel1.Text = NotConnectScrolltext); // Task.Factory.StartNew(() => // { // while (_startedScrolling) // { // var size = TextRenderer.MeasureText(toolStripStatusLabel1.Text, toolStripStatusLabel1.Font); // string movingText = toolStripStatusLabel1.Text; // if (size.Width+10 > toolStripStatusLabel1.Width) // { // movingText = movingText.Substring(1) + movingText[0]; // } // else // { // movingText = " " + movingText; // } // RunActionInGUIThread(() => toolStripStatusLabel1.Text = movingText); // Thread.Sleep(50); // } // }); //} #endregion Extensions.RunActionInGUIThread(() => notifyIcon.ShowBalloonTip(5, @"Уведомление", NotConnectScrolltext, ToolTipIcon.Warning),_uiScheduler); } else { //_startedScrolling = false; //RunActionInGUIThread(() => toolStripStatusLabel1.Text = ""); } } }, TaskCreationOptions.LongRunning); }
private void LoadReport() { Guid persId = Guid.Empty; if (cbPersons.SelectedValue != null) persId = (Guid) cbPersons.SelectedValue; //if (persId == Guid.Empty) // return; Guid typeId = Guid.Empty; if (cbWorkTypes.SelectedValue!=null) typeId = (Guid)cbWorkTypes.SelectedValue; MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка отчета", StatusText = @"Загрузка данных отчета" }; sp0.WorkingFunction = () => { InstallersWorks_Entities context = new InstallersWorks_Entities(); var data = context.InstallersWorks_Works .Include(i => i.InstallersWorks_WorkTypes) .Include(i => i.InstallersWorks_Personalities); if (persId != Guid.Empty) data = data.Where(w => w.WorkPersonId == persId); if (typeId != Guid.Empty) data = data.Where(w => w.WorkTypeId == typeId); if (dpFrom.Enabled) data = data .Where(w => DbFunctions.TruncateTime(w.WorkDate) >= DbFunctions.TruncateTime(dpFrom.Value) & DbFunctions.TruncateTime(w.WorkDate) <= DbFunctions.TruncateTime(dpTo.Value)); data = data.OrderByDescending(o => o.WorkDate); _dataSet.PerPersonDataSimple.Clear(); foreach (InstallersWorks_Works works in data) { ReportDataSet.PerPersonDataSimpleRow newRow = _dataSet.PerPersonDataSimple.NewPerPersonDataSimpleRow(); newRow.Id = works.Id; newRow.Person = works.InstallersWorks_Personalities.ShortFullName; newRow.WorkDate = works.WorkDate; newRow.WorkType = works.InstallersWorks_WorkTypes.TypeDescription; newRow.Description = works.Event + works.AssNomer + Environment.NewLine + works.Address; _dataSet.PerPersonDataSimple.AddPerPersonDataSimpleRow(newRow); } Extensions.RunActionInGUIThread(() => { sp0.StatusText = @"Обновление отчета"; reportViewer.Reset(); reportViewer.LocalReport.DataSources.Clear(); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet", (DataTable) _dataSet.PerPersonDataSimple)); reportViewer.LocalReport.ReportEmbeddedResource = "InstallersWork.Reports.PerPersons.PerPersonPeportSimple.rdlc"; ReportParameter param2 = new ReportParameter("ReportHeader1", "Отчет о работах сотрудников за период"); ReportParameter param1 = new ReportParameter("ReportHeaderField1", "с " + dpFrom.Value.ToLongDateString() + " по " + dpTo.Value.ToLongDateString()); reportViewer.LocalReport.SetParameters(new ReportParameter[] { param1, param2 }); reportViewer.RefreshReport(); }, _uiScheduler); }; sp0.ShowDialog(this); }
private void EventReportForm_Shown(object sender, EventArgs e) { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); MiniSplash_TF sp = new MiniSplash_TF(Resources.load4) { Text = @"Загрузка отчета", StatusText = "Подготовка данных" }; sp.WorkingFunction = () => { _dataSet.EventInfo.Clear(); ReportDataSet.EventInfoRow newRow = _dataSet.EventInfo.NewEventInfoRow(); newRow.CreationDate = _eventInfo.CreationDate.ToString("dd/MM/yyyy HH:mm"); newRow.Description = _eventInfo.Tag.Description; newRow.CreationUser = _eventInfo.Tag.Access_Users.Description + @" [" + (_eventInfo.Tag.Access_Users.Department != null ? _eventInfo.Tag.Access_Users.Department.Description : "Неизвестное подразделение") + @"]"; newRow.State = ((EventState) _eventInfo.Tag.State).GetAttributeValue<DescriptionAttribute, string>(x => x.Description); newRow.Type = ((EventType) _eventInfo.Tag.Type).GetAttributeValue<DescriptionAttribute, string>(x => x.Description); newRow.Number = _eventInfo.Number; newRow.EventIndex = _eventInfo.EventIndex; newRow.CustomerInfo = _eventInfo.Tag.CustomerInfo; newRow.CustomerDescription = _eventInfo.Tag.FirmId.HasValue & _eventInfo.Tag.CustomerId.HasValue ? _dataContexts.GetCustomerDescription(_eventInfo.Tag.FirmId.Value, _eventInfo.Tag.CustomerId.Value) : string.Empty; newRow.CustomerSide = string.Empty; if (_eventInfo.Tag.CustomerSide != null) { newRow.CustomerSide = _eventInfo.Tag.CustomerSide.Description; } else { if (_eventInfo.Tag.EquipmentPort != null) { newRow.CustomerSide = _eventInfo.Tag.EquipmentPort.SideLink.EquipmentPort.Equipment.Area.Description; } } newRow.CustomerPort = _eventInfo.Tag.EquipmentPort != null ? GetPortFullDescription(_eventInfo.Tag.EquipmentPort) : string.Empty; newRow.CloseDate = _eventInfo.Tag.CloseDate.HasValue ? _eventInfo.Tag.CloseDate.Value.ToString("dd/MM/yyyy HH:mm") : string.Empty; newRow.CheckDate = _eventInfo.Tag.CheckDate.HasValue ? _eventInfo.Tag.CheckDate.Value.ToString("dd/MM/yyyy HH:mm") : string.Empty; newRow.CloseInfo = _eventInfo.Tag.State == (int) EventState.ClosedEvent ? _eventInfo.Tag.CloseInfo : string.Empty; newRow.ClosePerson = _eventInfo.Tag.State == (int) EventState.ClosedEvent ? _eventInfo.Tag.ClosePerson : string.Empty; newRow.CheckPerson = _eventInfo.Tag.Access_Users1 != null ? _eventInfo.Tag.Access_Users1.Description + @" [" + (_eventInfo.Tag.Access_Users1.Department != null ? _eventInfo.Tag.Access_Users1.Department.Description : "Неизвестное подразделение") + @"]" : string.Empty; newRow.ClosePersonId = _eventInfo.Tag.Access_Users2 != null ? _eventInfo.Tag.Access_Users2.Description + @" [" + (_eventInfo.Tag.Access_Users2.Department != null ? _eventInfo.Tag.Access_Users2.Department.Description : "Неизвестное подразделение") + @"]" : string.Empty; _dataSet.EventInfo.AddEventInfoRow(newRow); _dataSet.EventComments.Clear(); if (_eventInfo.Tag.EventComments.Any()) foreach (EventComment comment in _eventInfo.Tag.EventComments) { ReportDataSet.EventCommentsRow newCommentRow = _dataSet.EventComments.NewEventCommentsRow(); newCommentRow.Description = comment.Description; newCommentRow.CreationDate = comment.CreationDate.ToString("dd/MM/yyyy HH:mm"); newCommentRow.CreationUser = comment.Access_Users.Description + @" [" + (comment.Access_Users.Department != null ? _eventInfo.Tag.Access_Users.Department.Description : "Неизвестное подразделение") + @"]"; _dataSet.EventComments.AddEventCommentsRow(newCommentRow); } sp.StatusText = "Загрузка отчета"; RunActionInGUIThread(()=> { reportViewer.Reset(); reportViewer.LocalReport.DataSources.Clear(); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("EventComments", (DataTable) _dataSet.EventComments)); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("EventInfo", (DataTable) _dataSet.EventInfo)); reportViewer.LocalReport.ReportEmbeddedResource = "Events_V2.Reports.EventReport.EventReport.rdlc"; reportViewer.LocalReport.SetParameters(new List<ReportParameter>() { new ReportParameter("EventState",((int)_eventInfo.Tag.State).ToString()) }); reportViewer.RefreshReport(); }); }; sp.ShowDialog(); }
private void LoadData() { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка данных", StatusText = @"Загрузка данных о событиях" }; sp0.WorkingFunction = () => { EventsDataContext context = new EventsDataContext(); var data = context.EventsEntities.Events .Include(i => i.CustomerSide) .Include(i => i.EquipmentPort) .Include(i => i.EquipmentPort.Equipment.Area) .Where(ev => ev.CreationDate >= DbFunctions.AddDays(dpFrom.Value, -1) & ev.CreationDate <= DbFunctions.AddDays(dpTo.Value, 1)); if (cbEventsAddData.Checked) { _eventInfos = ( from ev in data from cust in context.EventsEntities.EventAndCustomersViews .Where(c => c.Id == ev.Id) .DefaultIfEmpty() select new EventInfo() { Number = ev.Number, Index = ev.EventIndex.HasValue ? ev.EventIndex.Value : 0, Customer = cust.Title, State = ev.State, Address = ev.CustomerSide != null ? ev.CustomerSide.Description : ev.EquipmentPort != null ? ev.EquipmentPort.Equipment.Area.Description : string.Empty, Description = ev.Description, CreationDate = ev.CreationDate } ).OrderByDescending(o => o.CreationDate) .ToList(); } else { _eventInfos = data.Select(ev => new EventInfo() { Number = ev.Number, Index=ev.EventIndex.HasValue ? ev.EventIndex.Value: 0, State=ev.State, Address = ev.CustomerSide != null ? ev.CustomerSide.Description : ev.EquipmentPort != null ? ev.EquipmentPort.Equipment.Area.Description : string.Empty, Description = ev.Description, Customer=string.Empty, CreationDate = ev.CreationDate }).OrderByDescending(o => o.CreationDate).ToList(); } Extensions.RunActionInGUIThread(() => { SetGridVisualStyle(); gvEvents.DataSource = _eventInfos; }, _uiScheduler); }; sp0.ShowDialog(this); }
private void btSend_Click(object sender, EventArgs e) { if (tbReceivers.Text != Settings.Default.DutyReceiversList) { OnDefaultListChanged(); } MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"загрузка данных", StatusText = @"Экспорт данных отчета" }; sp0.WorkingFunction = () => { Microsoft.Reporting.WinForms.Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; byte[] exportData = _reportViewer.LocalReport.Render("Excel", null, PageCountMode.Actual, out mimeType, out encoding, out extension, out streamids, out warnings); if (warnings.Any()) { string wrngs = string.Empty; warnings.ToList().ForEach(w => wrngs += Environment.NewLine + w.Message); tbMessageBody.Invoke(new Func<string>(() => tbMessageBody.Text = tbMessageBody.Text.Insert(0, wrngs))); } MemoryStream memStream = new MemoryStream(); memStream.Write(exportData, 0, exportData.Length); memStream.Flush(); ContentType ct = new ContentType(mimeType); memStream.Position = 0; Attachment attach = new Attachment(memStream, ct); attach.ContentDisposition.FileName = "report.xls"; string from = !string.IsNullOrEmpty(SharedAppData.LoggedUser.Email) ? SharedAppData.LoggedUser.Description + " <" + SharedAppData.LoggedUser.Email + ">" : "*****@*****.**"; var rdText = (string)tbMessageBody.Invoke(new Func<string>(() => tbMessageBody.Text)); _subject = Regex.Split(_subject, Environment.NewLine)[0]; MailMessage mailMessage = new MailMessage { From = new MailAddress(from), Subject = _subject, Body = rdText }; mailMessage.Headers.Add("Return-Path", from); mailMessage.Headers.Add("X-Original-To", from); mailMessage.Headers.Add("X-Mailer", "report sender"); mailMessage.Headers.Add("Message-ID", "<" + Guid.NewGuid().ToString() + "@duty>"); mailMessage.ReplyToList.Add(from); mailMessage.Attachments.Add(attach); tbReceivers.Text.Split(',').ToList().ForEach(r => mailMessage.To.Add(r)); sp0.StatusText = @"Отправка сообщения"; SmtpClient client = new SmtpClient("10.100.1.253") {EnableSsl = false, DeliveryMethod = SmtpDeliveryMethod.Network}; client.Send(mailMessage); mailMessage.Dispose(); }; sp0.ShowDialog(this); DialogResult = DialogResult.OK; }
private void tbPhoneNumber_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return) { MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load4) {Text = @"Загрузка данных абонентов"}; List<Teleph> data=new List<Teleph>(); sp0.WorkingFunction = () => { sp0.StatusText = "Поиск совпадений по номеру " + tbPhoneNumber.Text; data = _dataContexts.NumEquipmentEntities.Telephs.Where(phone => _correctsFirmId.Any(id => id == phone.FirmId)).Where(_wherePhoneNumExpression).ToList(); if (data.Count == 0) { MessageBox.Show(@"По номеру " + tbPhoneNumber.Text + @" ничего не найдено!"); return; } }; sp0.ContinueFunction = () => { gvPhones.DataSource = data; }; sp0.ShowDialog(this); e.Handled = (e.SuppressKeyPress = true); } }
public void SendNotify(Event notifiedEvent, RequestAction action,NotifyReceiversList receiversList,object tag=null) { MiniSplash_TF sp0 = new MiniSplash_TF(Properties.Resources.load4) {Text=@"Отправка сообщения" , StatusText = @"Отправка почтового уведомления"}; sp0.WorkingFunction = () => { ClearHeaders(); List<string> fullReceivers = new List<string>(); List<string> shortReceivers = new List<string>(); if (receiversList != null) { List<NotifyReceiver> receivers = receiversList.NotifyReceivers.ToList(); receivers.ForEach(r => { if (r.Required) r.Selected = true; }); var selectedReceivers = receivers.Where(r => r.Selected).ToList(); if (selectedReceivers.Count == 0) return; fullReceivers = selectedReceivers.Where(r => !r.IsSms).Select(r => r.Receiver).ToList(); shortReceivers = selectedReceivers.Where(r => r.IsSms).Select(r => r.Receiver).ToList(); } else { if (tag != null) { var data = tag as string[]; if (data != null) { fullReceivers.Add(data[0]); if (data.Length == 2) shortReceivers.Add(data[1]); } } } string shortDepartmentId = string.Empty; if (notifiedEvent.Access_Users.Department != null) if (notifiedEvent.Access_Users.Department.ShortId != string.Empty) shortDepartmentId = notifiedEvent.Access_Users.Department.ShortId.Trim() + ";"; string eventNumber = @"#" + notifiedEvent.Number; string eventTypeDescription = ((EventType) notifiedEvent.Type).GetAttributeValue<DescriptionAttribute, string>(x => x.Description); string eventIndex = notifiedEvent.EventIndex.ToString(); int customerId = notifiedEvent.CustomerId.HasValue ? notifiedEvent.CustomerId.Value : 0; int firmId = notifiedEvent.FirmId.HasValue ? notifiedEvent.FirmId.Value : 0; string[] customerInfo = _dataContexts.GetCustomerDescription2(firmId, customerId); string eventCustomerFull = string.Join(",", customerInfo); string fullEventText = string.Empty; string shortEventText = string.Empty; string fullEmailSubject = string.Empty; string shortEmailSubject = string.Empty; string eventCustomerSide = string.Empty; string eventCustomerPort = string.Empty; string eventCustomerPortShort = string.Empty; if (notifiedEvent.CustomerSide != null) { eventCustomerSide = notifiedEvent.CustomerSide.Description; if (notifiedEvent.EquipmentPort != null) { eventCustomerPort = GetPortFullDescription(notifiedEvent.EquipmentPort); eventCustomerPortShort = GetPortShortDescription(notifiedEvent.EquipmentPort); } } else { if (notifiedEvent.EquipmentPort != null) { if (notifiedEvent.EquipmentPort.SideLink.LinkType == (int) SideLinkType.toEquipmentPort) eventCustomerPort = GetPortFullDescription(notifiedEvent.EquipmentPort.SideLink.EquipmentPort); eventCustomerSide = notifiedEvent.EquipmentPort.Equipment.Area.Description; eventCustomerPortShort = GetPortShortDescription(notifiedEvent.EquipmentPort); } } string eventCustomerContact = notifiedEvent.CustomerInfo; string eventDescription = notifiedEvent.Description; switch (action) { case RequestAction.Transfer: { var user = notifiedEvent.Access_Users; if (user == null) return; fullEmailSubject = @"Номер заявки: " + eventNumber + @" изменена"; fullEventText = @"Заявка: " + eventNumber + " передана в департамент [" + user.Department.Description + "]"; //+ @"Тип заявки: " + eventTypeDescription + Environment.NewLine //+ @"Вес заявки: " + eventIndex + Environment.NewLine //+ @"Абонент: " + eventCustomerFull + Environment.NewLine //+ (!string.IsNullOrEmpty(eventCustomerSide) ? @"Площадка абонента: " + eventCustomerSide + Environment.NewLine : "") //+ (!string.IsNullOrEmpty(eventCustomerPort) ? @"Порт абонента: " + eventCustomerPort + Environment.NewLine : "") //+ @"Контакт абонента: " + eventCustomerContact + Environment.NewLine //+ @"Текст заявки: " + eventDescription; _headers.Add(new KeyValuePair<string, string>("Message-ID", "<" + notifiedEvent.Id.ToString() + "@transfer.event>")); break; } case RequestAction.Renew: case RequestAction.New: { fullEventText = @"Номер заявки: " + eventNumber + @" Новая заявка" + Environment.NewLine + @"Тип заявки: " + eventTypeDescription + Environment.NewLine + @"Вес заявки: " + eventIndex + Environment.NewLine + @"Абонент: " + eventCustomerFull + Environment.NewLine + (!string.IsNullOrEmpty(eventCustomerSide) ? @"Площадка абонента: " + eventCustomerSide + Environment.NewLine : "") + (!string.IsNullOrEmpty(eventCustomerPort) ? @"Порт абонента: " + eventCustomerPort + Environment.NewLine : "") + @"Контакт абонента: " + eventCustomerContact + Environment.NewLine + @"Текст заявки: " + eventDescription; fullEmailSubject = eventNumber + ", " + eventCustomerFull + (!string.IsNullOrEmpty(eventCustomerSide) ? ", " + eventCustomerSide : ""); shortEventText = eventNumber + ";NEW;" + shortDepartmentId + customerId + ";" + eventIndex + ";" + eventCustomerSide + ";" + eventDescription + ";" + customerInfo.Last(); shortEmailSubject = ""; _headers.Add(new KeyValuePair<string, string>("Message-ID", "<" + notifiedEvent.Id.ToString() + "@open.event>")); break; } case RequestAction.Edit: break; case RequestAction.Remedy: { string remedyPerson = string.Empty; string remedyData = string.Empty; if (tag != null) { var data = tag as string[]; if (data != null) { remedyPerson = data[0]; remedyData = data[1]; } } fullEventText = @"Номер заявки: " + eventNumber + @" Изменено состояние" + Environment.NewLine + @"Тип заявки: " + eventTypeDescription + Environment.NewLine + @"Вес заявки: " + eventIndex + Environment.NewLine + @"Устранил: " + remedyPerson + @" Выполнены работы: " + remedyData + Environment.NewLine + @"Абонент: " + eventCustomerFull + Environment.NewLine + (!string.IsNullOrEmpty(eventCustomerSide) ? @"Площадка абонента: " + eventCustomerSide + Environment.NewLine : "") + (!string.IsNullOrEmpty(eventCustomerPort) ? @"Порт абонента: " + eventCustomerPort + Environment.NewLine : "") + @"Текст заявки: " + eventDescription; fullEmailSubject = eventNumber + ", " + eventCustomerFull + (!string.IsNullOrEmpty(eventCustomerSide) ? ", " + eventCustomerSide : ""); shortEventText = eventNumber + ";REMEDY;" + shortDepartmentId + customerId + ";" + eventIndex + ";" + (eventCustomerSide) + ";" + remedyPerson + ";" + remedyData + ";" + eventDescription + ";" + customerInfo.Last(); shortEmailSubject = ""; _headers.Add(new KeyValuePair<string, string>("Message-ID", "<" + notifiedEvent.Id.ToString() + "@remedy.event>")); _headers.Add(new KeyValuePair<string, string>("References", "<" + notifiedEvent.Id.ToString() + "@open.event>")); _headers.Add(new KeyValuePair<string, string>("In-Reply-To", "<" + notifiedEvent.Id.ToString() + "@open.event>")); break; } case RequestAction.Close: { string closedPerson = notifiedEvent.Access_Users2 != null ? notifiedEvent.Access_Users2.Description : string.Empty; string checkPerson = notifiedEvent.Access_Users1 != null ? notifiedEvent.Access_Users1.Description : string.Empty; string closedDate = notifiedEvent.CloseDate.HasValue ? notifiedEvent.CloseDate.Value.ToShortDateString() : string.Empty; string closedFixer = notifiedEvent.ClosePerson; string closedCheckDate = notifiedEvent.CheckDate.HasValue ? notifiedEvent.CheckDate.Value.ToShortDateString() : string.Empty; fullEmailSubject = eventNumber + ", " + eventCustomerFull + (!string.IsNullOrEmpty(eventCustomerSide) ? ", " + eventCustomerSide : ""); fullEventText = @"Номер заявки: " + eventNumber + @" Закрытие заявки" + Environment.NewLine + @"Тип заявки: " + eventTypeDescription + Environment.NewLine + @"Абонент: " + eventCustomerFull + Environment.NewLine + (!string.IsNullOrEmpty(eventCustomerSide) ? @"Площадка абонента: " + eventCustomerSide + Environment.NewLine : "") + (!string.IsNullOrEmpty(eventCustomerPort) ? @"Порт абонента: " + eventCustomerPort + Environment.NewLine : "") + @"Закрыл: " + closedPerson + " " + closedDate + Environment.NewLine + @"Проверил: " + checkPerson + " " + closedDate + Environment.NewLine + @"Исполнитель: " + closedFixer + " " + closedCheckDate + Environment.NewLine + @"Отчет: " + notifiedEvent.CloseInfo; shortEventText = eventNumber + ";CLOSE;" + shortDepartmentId + customerId + ";" + eventIndex + ";" + eventCustomerSide + ";" + closedPerson + ";" + eventDescription + ";" + customerInfo.Last(); _headers.Add(new KeyValuePair<string, string>("Message-ID", "<" + notifiedEvent.Id.ToString() + "@close.event>")); _headers.Add(new KeyValuePair<string, string>("References", "<" + notifiedEvent.Id.ToString() + "@open.event>")); _headers.Add(new KeyValuePair<string, string>("In-Reply-To", "<" + notifiedEvent.Id.ToString() + "@open.event>")); break; } case RequestAction.Unknown: break; default: throw new ArgumentOutOfRangeException("action"); } if (fullReceivers.Any()) { try { if (!string.IsNullOrEmpty(fullEventText)) { string emailFrom = @"*****@*****.**"; if (SharedAppData.LoggedUser.Email != null && !string.IsNullOrEmpty(SharedAppData.LoggedUser.Email)) { emailFrom = SharedAppData.LoggedUser.Email; } SendEmail(_headers, fullReceivers, emailFrom, fullEmailSubject, fullEventText); } } catch (Exception) { throw; } } if (shortReceivers.Any()) { try { if (!string.IsNullOrEmpty(shortEventText)) { shortEventText = Translator.ToTranslite(shortEventText); shortReceivers.ForEach(receiver => { MailMessage mailMessage = new MailMessage {From = new MailAddress("*****@*****.**"), Subject = shortEmailSubject, Body = shortEventText}; mailMessage.Headers.Add("Return-Path", "*****@*****.**"); mailMessage.Headers.Add("X-Original-To", "*****@*****.**"); mailMessage.Headers.Add("X-Mailer", "event registrator"); mailMessage.ReplyToList.Add("*****@*****.**"); mailMessage.To.Add(receiver); SmtpClient client = new SmtpClient("212.90.160.3") {EnableSsl = false, DeliveryMethod = SmtpDeliveryMethod.Network}; client.Send(mailMessage); mailMessage.Dispose(); }); } } catch (Exception) { throw; } } }; sp0.ShowDialog(_parentForm); }
private void LoadReport() { Guid typeId = Guid.Empty; if (cbWorkTypes.SelectedValue!=null) typeId = (Guid)cbWorkTypes.SelectedValue; MiniSplash_TF sp0 = new MiniSplash_TF(Resources.load1) { Text = @"Загрузка отчета", StatusText = @"Загрузка данных отчета" }; sp0.WorkingFunction = () => { InstallersWorks_Entities context = new InstallersWorks_Entities(); var data = context.InstallersWorks_Works .Include(i => i.InstallersWorks_WorkTypes) .Include(i => i.InstallersWorks_Personalities); if (typeId != Guid.Empty) data = data.Where(w => w.WorkTypeId == typeId); DateTime startDate; DateTime endDate; if (dpFrom.Enabled) { startDate = dpFrom.Value; endDate = dpTo.Value; } else { startDate = context.InstallersWorks_Works.Min(m => m.WorkDate); endDate = context.InstallersWorks_Works.Max(m => m.WorkDate); } data = data .Where(w => DbFunctions.TruncateTime(w.WorkDate) >= DbFunctions.TruncateTime(startDate) & DbFunctions.TruncateTime(w.WorkDate) <= DbFunctions.TruncateTime(endDate)) .OrderByDescending(o => o.WorkDate); var listData = data.ToList(); var groups = listData.GroupBy(g => g.WorkId).Select(fg => new { fg.Key, Works = fg.OrderBy(o => o.InstallersWorks_Personalities != null ? o.InstallersWorks_Personalities.PersonSurname : "Сотрудник удален") }); _dataSet.WorksData.Clear(); foreach (var grpCable in groups) { var defaultWork = grpCable.Works.FirstOrDefault(); if (defaultWork == default(InstallersWorks_Works)) throw new InvalidDataException(); ReportDataSet.WorksDataRow newRow = _dataSet.WorksData.NewWorksDataRow(); string personalDescription = string.Empty; foreach (var wrk in grpCable.Works) { if (personalDescription != string.Empty) personalDescription += " / "; personalDescription += wrk.InstallersWorks_Personalities != null ? wrk.InstallersWorks_Personalities.PersonSurname : "Сотрудник удален"; } newRow.Id = defaultWork.Id; newRow.Persons = personalDescription; newRow.WorkDate = defaultWork.WorkDate.Date; newRow.WorkDescription = defaultWork.Event + defaultWork.AssNomer + Environment.NewLine + defaultWork.Address; newRow.WorkType = defaultWork.InstallersWorks_WorkTypes.TypeDescription; newRow.Mileage = defaultWork.Mileage.HasValue ? defaultWork.Mileage.Value : 0; newRow.Comment = defaultWork.Comment; _dataSet.WorksData.AddWorksDataRow(newRow); } Extensions.RunActionInGUIThread(() => { sp0.StatusText = @"Обновление отчета"; reportViewer.Reset(); reportViewer.LocalReport.DataSources.Clear(); reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet", (DataTable)_dataSet.WorksData)); reportViewer.LocalReport.ReportEmbeddedResource = "InstallersWork.Reports.WorkDays.WorksTotalCutHeader.rdlc"; List<ReportParameter> repParams = new List<ReportParameter> { new ReportParameter("ReportHeader1","Отчет о выполненных работах с " + startDate.ToLongDateString() + " по " + endDate.ToLongDateString()), }; if ((Guid) cbWorkTypes.SelectedValue != Guid.Empty) { var desc = cbWorkTypes.SelectedItem as InstallersWorks_WorkTypes; if (desc==null) throw new InvalidCastException(); repParams.Add(new ReportParameter("ReportHeaderField1", "по типу " + desc.TypeDescription)); //reportViewer.LocalReport.ReportEmbeddedResource = "InstallersWork.Reports.WorkDays.WorksTotal.rdlc"; //repParams.Add(new ReportParameter("ReportHeader2", "по типу")); //repParams.Add(new ReportParameter("ReportHeaderField2", desc.TypeDescription)); } reportViewer.LocalReport.SetParameters(repParams); reportViewer.RefreshReport(); }, _uiScheduler); }; sp0.ShowDialog(this); }