public GetDataControl() { InitializeComponent(); _window = TMPApplication.ServiceInjector.Instance.GetService <TMPApplication.WpfDialogs.Contracts.IWindowWithDialogs>(); if (_window == null) { throw new ArgumentNullException("Not found Window that implementing IWindowWithDialogs"); } CancelCommand = new DelegateCommand( o => { var q = _window.DialogQuestion(Strings.InterruptQuestion); q.Yes = () => { _cts.Cancel(); App.Current.MainWindow.TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Error; }; q.Show(); }, o => _cts != null && (_cts.IsCancellationRequested == false)); CloseControlCommand = new DelegateCommand(o => { if (_onClosed != null) { _onClosed(); } }); SaveAllCommand = new DelegateCommand(o => { CommonOpenFileDialog cfd = new CommonOpenFileDialog(); cfd.Title = Strings.SelectFolderToSave; cfd.IsFolderPicker = true; cfd.AddToMostRecentlyUsedList = false; cfd.EnsurePathExists = true; cfd.Multiselect = false; cfd.ShowPlacesList = true; cfd.AllowNonFileSystemItems = true; if (cfd.ShowDialog() == CommonFileDialogResult.Ok) { App.Log("Сохранение всех отчётов в папку"); try { var folder = cfd.FileName; foreach (var item in _list) { if (item.Status == ListPointStatus.Готово) { if (item.ResultType == "txt") { System.IO.File.WriteAllText( System.IO.Path.Combine(folder, item.ResultName + ".csv"), TrimStringValue((string)item.ResultValue), Encoding.UTF8); } else if (item.ResultType == "xls") { byte[] bytes = (byte[])item.ResultValue; if (bytes != null) { System.IO.File.WriteAllBytes( System.IO.Path.Combine(folder, item.ResultName + ".xls"), bytes); } } else { System.IO.File.WriteAllText( System.IO.Path.Combine(folder, item.ResultName + ".txt"), TrimStringValue((string)item.ResultValue), Encoding.UTF8); } } } } catch (Exception ex) { _window.ShowDialogError(ex, Strings.ErrorOnSave); } } }, o => _list != null && _list.All(i => i.ResultValue != null)); SaveAllInSigleFileCommand = new DelegateCommand(o => { bool isStringContent = _list.Where(i => i.Status == ListPointStatus.Готово).All(i => i.ResultType != "xls"); if (isStringContent) { try { StringBuilder sb = new StringBuilder(); foreach (var item in _list) { if (item.Status == ListPointStatus.Готово) { sb.AppendLine(TrimStringValue((string)item.ResultValue)); } } Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.Filter = Strings.DialogCsvFilter; sfd.DefaultExt = ".csv"; sfd.AddExtension = true; sfd.FileName = DateTime.Now.AddMonths(-1).ToString(Strings.MultipleFileNameTemplate); Nullable <bool> result = sfd.ShowDialog(App.Current.MainWindow); if (result == true) { App.Log("Сохранение всех отчётов в один файл"); System.IO.File.WriteAllText(sfd.FileName, sb.ToString(), Encoding.UTF8); } } catch (Exception ex) { _window.ShowDialogError(ex, Strings.ErrorOnSave); } } }, o => _list != null && _list.All(i => i.ResultValue != null) && _list.All(i => i.ResultType != "xls")); SaveCommand = new DelegateCommand(o => { try { ListPointWithResult point = o as ListPointWithResult; if (point != null) { Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.FileName = String.Format(Strings.SingleFileNameTemplate, point.ResultName, DateTime.Now.AddMonths(-1)); sfd.AddExtension = true; if (point.ResultType == "xls") { sfd.Filter = Strings.DialogXlsFilter; sfd.DefaultExt = ".xls"; } else if (point.ResultType == "txt") { sfd.Filter = Strings.DialogCsvFilter; sfd.DefaultExt = ".csv"; } else { sfd.Filter = Strings.DialogTxtFilter; sfd.DefaultExt = ".txt"; } Nullable <bool> result = sfd.ShowDialog(App.Current.MainWindow); if (result == true) { App.Log("Сохранение отчёта"); if (point.ResultType == "xls") { byte[] bytes = (byte[])point.ResultValue; if (bytes != null) { System.IO.File.WriteAllBytes(sfd.FileName, bytes); } } else { System.IO.File.WriteAllText(sfd.FileName, TrimStringValue((string)point.ResultValue), Encoding.UTF8); } } } } catch (Exception ex) { _window.ShowDialogError(ex, Strings.ErrorOnSave); } }); DataContext = this; }
private async Task <bool> CheckServiceAvailability() { string error = string.Empty; bool result = false; Action <bool> onFinally = (ok) => { if (ok) { result = true; ServiceAvailability = true; IsReportSettingsEnabled = true; } else { _window.ShowDialogError(error); result = false; ServiceAvailability = false; } }; try { bool serverAvailability = ServiceHelper.IsServerOnline(); if (serverAvailability) { ServerAvailability = true; // проверка наличия доступа bool hasRights = await ServiceHelper.LoginAsync(true); string answer = ServiceHelper.ErrorMessage; // если доступ не получен и не авторизованы if (hasRights == false) { if (String.IsNullOrEmpty(answer)) { error = Strings.IncorrectService; onFinally(false); } hasRights = await ServiceHelper.LoginAsync(); // авторизация не успешна if (hasRights == false) { error = Strings.AuthorizationFailed; onFinally(false); } else { onFinally(true); } } else { if (answer == "result=0&user=") { hasRights = await ServiceHelper.LoginAsync(); if (hasRights) { onFinally(true); } else { onFinally(false); } } else { onFinally(true); } } } else { ServerAvailability = false; onFinally(false); } } catch (Exception ex) { string message = String.Format(Strings.Error, ex.Message); error = message; onFinally(false); return(false); } return(result); }
private void PrepareReport(ListPointWithResult point) { int groupId = point.Id; string param = String.Format("__invoker=undefined&RP_ID={0}&RP_NAME={1}&errorDispatch=false&dataBlock=PARAMETERS&action=GET", _selectedReport.RP_ID, _selectedReport.RP_NAME); string url = @"{0}scripts/reports.asp"; string answer = ServiceHelper.ExecuteFunctionAsync(ServiceHelper.MakeRequestAsync, url, param, true, (p) => ServiceHelper.DecodeAnswer(p)).Result; if (String.IsNullOrEmpty(answer) == false && answer.Contains("result=0")) { var records = Utils.ParseRecords(answer); if (records == null) { System.Diagnostics.Debugger.Break(); } List <RPQ> rpqs = new List <RPQ>(records.Count); foreach (var nvc in records) { if (nvc.Get("COLUMN_NAME") != "GR_ID") { _window.ShowDialogError(Strings.InvalidReport); return; } RPQ rpq = new RPQ(); for (int i = 0; i < nvc.Count; i++) { #region азбор полей switch (nvc.GetKey(i)) { case "RPQ_ID": rpq.RPQ_ID = nvc[i]; break; case "RPQ_NAME": rpq.RPQ_NAME = nvc[i]; break; case "TABLE_NAME": rpq.TABLE_NAME = nvc[i]; break; case "RPQF_ID": rpq.RPQF_ID = nvc[i]; break; case "RPQO_ID": rpq.RPQO_ID = nvc[i]; break; case "RPQO_CODE": rpq.RPQO_CODE = nvc[i]; break; case "RPQF_VALUE": rpq.RPQF_VALUE = nvc[i]; break; case "FIELD_DESC": rpq.FIELD_DESC = nvc[i]; break; case "RPQF_ALLOW_EMPTY_VALUES": rpq.RPQF_ALLOW_EMPTY_VALUES = nvc[i]; break; case "DATA_TYPE": rpq.DATA_TYPE = nvc[i]; break; } #endregion азбор полей } rpqs.Add(rpq); } param = String.Format("__invoker=undefined&RP_ID={0}&RP_NAME={1}&errorDispatch=false&dataBlock=PREPARED_RP&action=GET", _selectedReport.RP_ID, _selectedReport.RP_NAME); url = @"{0}scripts/reports.asp"; answer = ServiceHelper.ExecuteFunctionAsync(ServiceHelper.MakeRequestAsync, url, param, true, (p) => ServiceHelper.DecodeAnswer(p)).Result; if (String.IsNullOrEmpty(answer) == false && answer.Contains("result=0")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < rpqs.Count; i++) { RPQ rpq = rpqs[i]; sb.AppendFormat("RPQF_{0}={1}&DATA_TYPE_0_{2}={3}&RPQF_VALUE_0_{2}={1}&COLUMN_NAME_0_{2}={4}&RPQO_ID_0_{2}={5}&RPQF_ID_0_{2}={0}&", rpq.RPQF_ID, //0 groupId, //1 i, //2 rpq.DATA_TYPE, //3 rpq.COLUMN_NAME, //4 rpq.RPQO_ID //5 ); } sb.AppendFormat("RPQ_NAME_0={0}&RPQ_ID_0={1}&RPQF_COUNT_0={2}&RPQ_COUNT=1&export_to_html=0&RP_ID={3}&action=SHOW_REPORT", rpqs[0].RPQ_NAME, rpqs[0].RPQ_ID, rpqs.Count, _selectedReport.RP_ID); url = @"{0}scripts/ReportGenerator.asp"; answer = ServiceHelper.MakeRequestAsync(url, sb.ToString()).Result; if (ServiceHelper.StatusCode == System.Net.HttpStatusCode.OK) { // получение имени файла /* * <HTML> * <HEAD> * <META HTTP-EQUIV=Refresh CONTENT="0;URL=../\\reports\2016\12\30\Для расчета балансов ПС до 35кВ_2016_12_30_113404_1.txt"> * </HEAD> * </HTML> */ Match KeywordMatch = Regex.Match(answer, "<meta HTTP-EQUIV=Refresh content=\"([^<]*)\">", RegexOptions.IgnoreCase | RegexOptions.Multiline); string metaKeywords = KeywordMatch.Groups[1].Value; string file = metaKeywords.Substring(8).Replace("../", "").Replace("\\", "/"); var client = new WebClient(); if (file.EndsWith(".txt")) { point.ResultValue = client.DownloadString(ServiceHelper.SiteAddress + file); point.ResultType = "txt"; } else if (file.EndsWith(".xls")) { point.ResultValue = client.DownloadData(ServiceHelper.SiteAddress + file); point.ResultType = "xls"; } else { point.ResultValue = client.DownloadString(ServiceHelper.SiteAddress + file); point.ResultType = "unknown"; } } } } }