Esempio n. 1
0
        public void Stop()
        {
            if (asyncResult == null)
            {
                return;
            }
            IAsyncResult ar = asyncResult;

            asyncResult = null;

            Report = action.EndInvoke(ar);
        }
Esempio n. 2
0
        public string ImportFile(string modelId, string filePath, string importUri)
        {
            if (!File.Exists(filePath))
            {
                throw new Exception(
                          String.Format("File {0} does not exist", filePath));
            }
            var filestream = new FileStream(filePath, FileMode.Open);
            var fileName   = Path.GetFileName(filePath);
            var imfuri     = String.Format(importUri, modelId, fileName);
            var request    = new HttpRequestMessage(HttpMethod.Post, imfuri);

            request.Content = new StreamContent(filestream);
            var response = HttpClient.SendAsync(request).Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(
                          String.Format("Error {0}: Failed to import file {1}, for model {2} \n reason {3}",
                                        response.StatusCode, filePath, modelId, response.ReasonPhrase));
            }

            //process response if success
            var nodeList = XmlUtils.ExtractXmlElementList(response.Content.ReadAsStreamAsync().Result,
                                                          "//a:entry/a:content/m:properties/*");

            var report = new ImportReport {
                Info = fileName
            };

            foreach (XmlNode node in nodeList)
            {
                if ("LineCount".Equals(node.LocalName))
                {
                    report.LineCount = int.Parse(node.InnerText);
                }
                if ("ErrorCount".Equals(node.LocalName))
                {
                    report.ErrorCount = int.Parse(node.InnerText);
                }
            }
            var reportString = report.ToString();

            return(reportString);
        }
Esempio n. 3
0
        public ImportReport Import()
        {
            Batch fileContents = null;
            var importReport = new ImportReport();

            try
            {
                fileContents = FileParser.Parse();
                MergeData(fileContents);
                importReport.IsSuccess = true;
            }
            catch (Exception ex)
            {
                importReport.IsSuccess = false;
                importReport.InnerException = ex;
            }

            return importReport;
        }
Esempio n. 4
0
 public ViewModelImportReport()
 {
     importReportData                = new ImportReport();
     importReportData.StationName    = @"Tín Nghĩa";
     importReportData.ReportDate     = DateTime.Now;
     importReportData.StaffName      = @"Nguyễn Văn A";
     importReportData.StaffPos       = @"Trạm trưởng";
     importReportData.TemplateBottle = @"DSHFKJSHFKJ";
     importReportData.DriverName     = "dhfkshfkjs";
     importReportData.CarPlate       = "dfsjlfjs";
     importReportData.BeginCapacity  = 100;
     importReportData.BeginLevel     = 1.05;
     importReportData.BeginTotalPump = 748274947;
     importReportData.EndCapacity    = 10000;
     importReportData.EndLevel       = 100.05;
     importReportData.EndTotalPump   = 748274947;
     importReportData.ImportCapacity = 10000;
     importReportData.RealCapacity   = 9900;
     importReportData.Fuel           = @"Xăng A92";
 }
Esempio n. 5
0
        public ImportReport ImportFile(string modelId, string fileName, Stream stream, string importUri)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, String.Format(importUri, modelId, fileName));

            request.Content = new StreamContent(stream);
            var response = _httpClient.SendAsync(request).Result;


            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(
                          String.Format("Error {0}: Failed to import file {1}, for model {2} \n reason {3}",
                                        response.StatusCode, fileName, modelId, ExtractErrorInfo(response)));
            }

            //process response if success
            var nodeList = XmlUtils.ExtractXmlElementList(response.Content.ReadAsStreamAsync().Result,
                                                          "//a:entry/a:content/m:properties/*");

            var report = new ImportReport {
                Info = fileName
            };

            foreach (XmlNode node in nodeList)
            {
                if ("LineCount".Equals(node.LocalName))
                {
                    report.LineCount = int.Parse(node.InnerText);
                }
                if ("ErrorCount".Equals(node.LocalName))
                {
                    report.ErrorCount = int.Parse(node.InnerText);
                }
            }
            return(report);
        }
Esempio n. 6
0
 private void HubCommunicator_ImportReportNotification(object sender, ValueEventArgs<ImportReport> e)
 {
     Deployment.Current.Dispatcher.BeginInvoke(
          () =>
          {
              Report = e.Value;
          });
 }
        /// <summary>
        /// Import the given file (catalog/usage) to the given model. 
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="filePath"></param>
        /// <param name="importUri"></param>
        /// <returns></returns>
        private ImportReport ImportFile(string modelId, string filePath, string importUri)
        {
            var filestream = new FileStream(filePath, FileMode.Open);
            var fileName = Path.GetFileName(filePath);
            var request = new HttpRequestMessage(HttpMethod.Post, String.Format(importUri, modelId, fileName));

            request.Content = new StreamContent(filestream);
            var response = _httpClient.SendAsync(request).Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(
                    String.Format("Error {0}: Failed to import file {1}, for model {2} \n reason {3}",
                        response.StatusCode, filePath, modelId, ExtractErrorInfo(response)));
            }

            //process response if success
            var nodeList = XmlUtils.ExtractXmlElementList(response.Content.ReadAsStreamAsync().Result,
                "//a:entry/a:content/m:properties/*");

            var report = new ImportReport { Info = fileName };
            foreach (XmlNode node in nodeList)
            {
                if ("LineCount".Equals(node.LocalName))
                {
                    report.LineCount = int.Parse(node.InnerText);
                }
                if ("ErrorCount".Equals(node.LocalName))
                {
                    report.ErrorCount = int.Parse(node.InnerText);
                }
            }
            return report;
        }
Esempio n. 8
0
 /// <summary>
 /// The send import report.
 /// </summary>
 /// <param name="initiatorId">
 /// The initiator id.
 /// </param>
 /// <param name="exceptions">
 /// The exceptions.
 /// </param>
 public static void SendImportReport(string initiatorId, ImportReport report)
 {
     if (report != null)
         ServerStatusHub.NotifyImportReport(initiatorId, report);
 }
Esempio n. 9
0
        internal static void RemoveBrokenTopLevelObjects(ProcessEdit procEdit, ImportReport report)
        {
            var propList =
                procEdit.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(ExportableAttribute), false).Any(x => ((ExportableAttribute)x).PropertyType == ExportType.Expandable));

            foreach (var prop in propList)
            {
                var itemList = prop.GetValue(procEdit) as IList;

                if (itemList == null)
                    continue;

                var brokenItemList = itemList.Cast<IEditableBusinessObject>().Where(x => x.IsValid == false).ToList();
                
                foreach (var item in brokenItemList)
                {
                    var reportProcess = report.Processes.First(x => x.ProcessName == procEdit.Name);

                    switch (prop.Name)
                    {
                        case "ActionRuleList":
                            reportProcess.BrokenRules.Add(itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + " skipped due to errors");
                            break;
                        case "FilterList":
                            reportProcess.BrokenFilters.Add(itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + " skipped due to errors");
                            break;
                        case "TriggerList":
                            reportProcess.BrokenTriggers.Add(itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + " skipped due to errors");
                            break;
                        case "ESyncProcessList":
                            reportProcess.BrokenESyncDesigner.Add(itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + " skipped due to errors");
                            break;
                        case "ExternalDataList":
                            reportProcess.BrokenExternalData.Add(itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + " skipped due to errors");
                            break;
                        default:
                            reportProcess.OtherErrors.Add(prop.Name + " \"" + itemList[itemList.IndexOf(item)].GetType().GetProperty("Name").GetValue(itemList[itemList.IndexOf(item)]).ToString() + "\"" + " skipped due to errors");
                            break;
                    }
                    
                    itemList.Remove(item);
                }
            }
        }
Esempio n. 10
0
        internal static void RemoveBrokenFields(ProcessEdit procEdit, ImportReport report)
        {
            foreach (var section in procEdit.SectionList.Where(x => x.IsValid == false).ToList())
            {
                var fieldsToRemove = section.FieldList.Where(x => x.IsValid == false).ToList();

                foreach (var field in fieldsToRemove)
                {
                    var crStep = field.StepList.FirstOrDefault(x => x is CrossRefRequiredStepEdit) as CrossRefRequiredStepEdit;

                    if (crStep != null)
                    {
                        var selectedFields = crStep.SelectedFields.Where(x => !x.IsValid).ToList();

                        foreach (var displayField in selectedFields)
                        {
                            crStep.SelectedFields.Remove(displayField);

                            report.Processes.First(x => x.ProcessName == procEdit.Name).BrokenFields.Add(string.Format("Section \"{0}\", Field \"{1}\" (Error: Display Field {2} is not valid, please resolve this issue manually)", section.Name, field.Name, displayField.FieldName));
                        }
                    }

                    var dlStep = field.StepList.FirstOrDefault(x => x is DisplayListRequiredStepEdit) as DisplayListRequiredStepEdit;

                    if (dlStep != null)
                    {
                        var selectedFields = dlStep.SelectedFields.Where(x => !x.IsValid).ToList();

                        foreach (var displayField in selectedFields)
                        {
                            dlStep.SelectedFields.Remove(displayField);

                            report.Processes.First(x => x.ProcessName == procEdit.Name).BrokenFields.Add(string.Format("Section \"{0}\", Field \"{1}\" (Error: Display Field {2} is not valid, please resolve this issue manually)", section.Name, field.Name, displayField.FieldName));
                        }
                    }

                    procEdit.ResumeRuleChecking();

                    if (!field.IsValid)
                    {
                        section.FieldList.Remove(field);

                        report.Processes.First(x => x.ProcessName == procEdit.Name).BrokenFields.Add(string.Format("Section \"{0}\", Field \"{1}\" (Error: {2})", section.Name, field.Name, field.GetBrokenRules().ToString(",")));
                    }
                }
            }
        }
Esempio n. 11
0
        public string UploadFileSDMXSchema()
        {
            string _result = JsonMessage.GetError(Resources.Notification.err_file_empty);

            // Retrive Logged user
            SDMX_Dataloader.Engine.Client client = null;
            try
            {
                client = HttpContext.Current.Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client; if (client == null) throw new Exception("Session Expiried");
            }
            catch (Exception ex)
            {
                return JsonMessage.SessionExpired;
            }

            try
            {

                if (!UserDef.UserCan(client.LoggedUser, UserDef.ActionDef.CRUDSchema))
                    return JsonMessage.GetError(Resources.Notification.err_action_denied);

                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["sdmxSchemaFiles"];

                    if (httpPostedFile != null)
                    {
                        // Check file exist
                        if (httpPostedFile.FileName == string.Empty)
                        {
                            _result= JsonMessage.GetError(Resources.Notification.err_file_not_found);
                        }

                        // check file type (only .csv)
                        string[] FileExt = httpPostedFile.FileName.Split('.');
                        string FileEx = FileExt[FileExt.Length - 1];
                        if (FileEx.ToLower() != "xml")
                        {
                            _result = JsonMessage.GetError(Resources.Notification.err_file_bad_type);
                        }

                        // Check file exist
                        if (httpPostedFile.ContentLength < 1)
                        {
                            _result = JsonMessage.GetError(Resources.Notification.err_file_empty);
                        }

                        // For save file
                        //var fileSavePath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), httpPostedFile.FileName);
                        //httpPostedFile.SaveAs(fileSavePath);

                        IList<Estat.Sri.MappingStore.Store.Model.ArtefactImportStatus> resultItem= DataSDMX.SubmitStructure(httpPostedFile.InputStream);

                        if (resultItem == null)
                        {
                            _result = JsonMessage.GetError(Resources.Notification.err_import_data);
                        }
                        else
                        {
                            List<ImportReport> _textResults = new List<ImportReport>();
                            foreach (Estat.Sri.MappingStore.Store.Model.ArtefactImportStatus ArtStat in resultItem)
                            {
                                ImportReport report = new ImportReport()
                                {
                                    StructureReference = ArtStat.ImportMessage.StructureReference.MaintainableId.ToString() + "-" + ArtStat.ImportMessage.StructureReference.AgencyId.ToString() + "-" + ArtStat.ImportMessage.StructureReference.Version.ToString(),
                                    Status = (ArtStat.ImportMessage.Status == Estat.Sri.MappingStore.Store.ImportMessageStatus.Success) ? "success" : "error",
                                    Message = ArtStat.ImportMessage.Message
                                };
                                _textResults.Add(report);
                            }

                            _result = JsonMessage.GetData(_textResults);
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);

                _result = JsonMessage.GetError(ex.Message);

                //_result = JsonMessage.ErrorOccured;
            }
            finally
            {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/json";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.Write(_result);
                HttpContext.Current.Response.End();
            }

            return JsonMessage.ErrorOccured;
        }
Esempio n. 12
0
 public ViewModelImportReport(ImportReport importReportData)
 {
     this.importReportData = importReportData;
 }
Esempio n. 13
0
        /// <summary>
        /// The begin import.
        /// </summary>
        /// <param name="processId">
        /// The process id.
        /// </param>
        /// <param name="initiatorId">
        /// The initiator id.
        /// </param>
        /// <param name="roleList">
        /// The role list.
        /// </param>
        /// <param name="businessUnitList">
        /// The business unit list.
        /// </param>
        /// <param name="databaseObjects">
        /// The database Objects.
        /// </param>
        /// <param name="systemParameters">
        /// The system Parameters.
        /// </param>
        public static async void BeginImport(IList<string> processId, string initiatorId, IList<MobileSecurityRoleDependency> roleList, IList<MobileSecurityBusinessUnitDependency> businessUnitList, IList<string> databaseObjects, IList<string> systemParameters)
        {
            using (new ImportContext())
            {
                _initiatorId = initiatorId;

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Connecting, "Success", _initiatorId));

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Preparing, "InProgress", _initiatorId));

                _report = new ImportReport();

                using (new ThreadLocalBypassPropertyCheckContext())
                {
                    foreach (var role in roleList.Where(x => x.NewRole == -1))
                    {
                        var editableRoot = DynamicTypeManager.Instance.NewEditableRoot<IEditableRoot>(Constants.BaseRoleProcessName) as IRole;
                        if (editableRoot != null)
                        {
                            editableRoot.Name = role.OldRoleName;

                            var saveItem = editableRoot as ISavable;
                            if (saveItem != null)
                            {
                                var savedItem = saveItem.Save() as IRole;

                                if (savedItem != null)
                                {
                                    role.NewRole = savedItem.Id;
                                }
                            }
                        }
                    }

                    foreach (var bu in businessUnitList.Where(x => x.NewBusinessUnit == -1))
                    {
                        var editableRoot = DynamicTypeManager.Instance.NewEditableRoot<IEditableRoot>(Constants.BaseBusinessUnitProcessName) as IBusinessUnit;
                        if (editableRoot != null)
                        {
                            editableRoot.Name = bu.OldBusinessUnitName;

                            var saveItem = editableRoot as ISavable;
                            if (saveItem != null)
                            {
                                var savedItem = saveItem.Save() as IBusinessUnit;

                                if (savedItem != null)
                                {
                                    bu.NewBusinessUnit = savedItem.Id;
                                }
                            }
                        }
                    }
                }

                _additionalFields = new List<AdditionalFieldInfo>();
                _additionalRCRFields = new List<AdditionalFieldInfo>();
                _moreAdditionalFields = new List<AdditionalFieldInfo>();
                _additionalExpressionFields = new List<FieldExpressionInfo>();
                _additionalRuleExpressions = new List<RuleExpressionInfo>();
                _additionalTriggerExpressions = new List<TriggerExpressionInfo>();
                _additionalTriggerFieldExpressions = new List<TriggerFieldExpressionInfo>();
                _missingBaseProcessList = new List<MissingBaseProcessInfo>();
                _linkFieldSystemNameList = new List<LinkFieldSystemNameInfo>();

                ImportProcessHelper.RoleList = roleList;
                ImportProcessHelper.BusinessUnitList = businessUnitList;

                var procList = processId.Select(XElement.Parse).ToList();

                ImportProcessHelper.ImportSystemParameters(systemParameters.Select(XElement.Parse).ToList());

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Preparing, "Success", _initiatorId));

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage1, "InProgress", _initiatorId));

                foreach (var proc in procList.Where(proc => proc != null))
                {
                    _currentProcess = proc.Element("SystemName").Value;
                    _currentProcessName = proc.Element("Name").Value;

                    _report.Processes.Add(new ProcessImportReport(_currentProcessName));

                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage1, "InProgress", _currentProcessName, _initiatorId));

                    ImportStage1(proc);
                }

                if (_missingBaseProcessList.Any())
                {
                    foreach (var baseProc in _missingBaseProcessList)
                    {
                        var xElement = PublishedProcesses.GetPublishedProcesses().FirstOrDefault(x => x.SystemName == baseProc.ProcessSystemName);
                        if (xElement == null)
                        {
                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).OtherErrors.Add("Base process with SystemName \"" + baseProc.MissingProcessSystemName + "\" missing");

                            continue;
                        }

                        var procInfo1 = ProcessList.GetProcessList().FirstOrDefault(x => x.SystemName == baseProc.MissingProcessSystemName);

                        if (procInfo1 == null)
                        {
                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).OtherErrors.Add("Base process with SystemName \"" + baseProc.MissingProcessSystemName + "\" missing");

                            continue;
                        }

                        var procEdit1 = ProcessEdit.GetProcess(procInfo1.Id);

                        try
                        {
                            ImportProcessHelper.FillRegularValue(procEdit1.GetType().GetProperty("BaseProcessId"), xElement.Id, procEdit1);
                        }
                        catch (Exception ex)
                        {
                            Log4NetLogger.Instance.Log(LogSeverity.Error, "Import Process", ex);

                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).OtherErrors.Add(ex.Message);
                        }

                        ProcessEdit procAfterSave1;

                        try
                        {
                            procAfterSave1 = procEdit1.Save();
                        }
                        catch (Exception ex)
                        {
                            Log4NetLogger.Instance.Log(LogSeverity.Error, "Import Process", ex);

                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).ImportStatus = "Process imported with errors";
                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).OtherErrors.Add(ex.Message);

                            continue;
                        }

                        try
                        {
                            PublishSingleLibraryCommand.BeginExecute(procAfterSave1.Id, false, false, Guid.NewGuid(), 0, false, true);
                        }
                        catch (Exception ex)
                        {
                            Log4NetLogger.Instance.Log(LogSeverity.Error, "Import Process", ex);

                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).ImportStatus = "Process imported with errors";
                            _report.Processes.First(x => x.ProcessName == baseProc.ProcessName).OtherErrors.Add(ex.Message);
                        }
                    }
                }

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage1, "Success", _initiatorId));

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage2, "InProgress", _initiatorId));

                foreach (var proc in procList.Where(proc => proc != null))
                {
                    _currentProcess = proc.Element("SystemName").Value;
                    _currentProcessName = proc.Element("Name").Value;

                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage2, "InProgress", _currentProcessName, _initiatorId));

                    ImportStage2(proc);
                }

                foreach (var proc in procList.Where(proc => proc != null))
                {
                    _currentProcess = proc.Element("SystemName").Value;
                    _currentProcessName = proc.Element("Name").Value;

                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage2, "InProgress", _currentProcessName + " - Additional", _initiatorId));

                    ImportStage2(proc, true);
                }

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage2, "Success", _initiatorId));

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage3, "InProgress", _initiatorId));

                foreach (var proc in procList.Where(proc => proc != null))
                {
                    _currentProcess = proc.Element("SystemName").Value;
                    _currentProcessName = proc.Element("Name").Value;

                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage3, "InProgress", _currentProcessName, _initiatorId));

                    ImportStage3(proc);
                }

                foreach (var nameValue in databaseObjects)
                {
                    try
                    {
                        (new DatabaseObjectsExportImport()).SetDatabaseObject(nameValue);
                    }
                    catch (Exception ex)
                    {
                        Log4NetLogger.Instance.Log(LogSeverity.Warning, "Import Process", ex);
                    }
                }

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Importing_Stage3, "Success", _initiatorId));

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Building, "InProgress", _initiatorId));

                try
                {
                    await GenerateProcessLibraryCommand.BeginExecuteAsync(false, LibraryTypes.System | LibraryTypes.Custom, false);
                }
                catch (Exception ex)
                {
                    Log4NetLogger.Instance.Log(LogSeverity.Warning, "Import Process", ex);

                    HubCommunicator.SendImportReport(_initiatorId, _report);

                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Building, "Failure", _initiatorId));
                    HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Finishing, "Failure", _initiatorId));

                    return;
                }

                Log4NetLogger.Instance.Log(LogSeverity.Information, "Import Report", ImportReportConverter.ConvertReport(_report));
                HubCommunicator.SendImportReport(_initiatorId, _report);

                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Building, "Success", _initiatorId));
                HubCommunicator.SendImportStatus(new ImportStatus(ImportStages.Finishing, "Success", "You should check report to see if there were any problems", _initiatorId));
            }
        }
Esempio n. 14
0
        private void DoImportFinish(UInt64 tankId)
        {
            var selTank = (from _tank in CollecTank
                           where _tank.TankId == (long)tankId
                           select _tank).FirstOrDefault() as TankModel;
            DateTime _now = DateTime.Now;

            try
            {
                if (App.Demo != 1)
                {
                    if (MessageBox.Show(String.Format(@"Kết thúc nhập bồn {0}", selTank.Description), @"Nhập nhiên liệu", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                    BusinessHelper.SaveTankData(selTank.TankId, selTank.Capacity, selTank.Thermometer, selTank.WaterCapacity, (Byte)SaveDataStatus.SAVE, _now);

                    DataTable dt = BusinessHelper.GetTankList(selTank.TankId);
                    foreach (DataRow _dr in dt.Rows)
                    {
                        long tankid = Convert.ToInt64(_dr["tankid"]);
                        //BusinessHelper.UpdateTankStatus(tankid);
                        BusinessHelper.UpdatePumpStatus(tankid);
                    }
                }


                DataTable    _dtReport     = BusinessHelper.FindLastTicketByTankId(selTank.TankId);
                ImportReport _importReport = new ImportReport();
                long         _ticketId     = -1;
                long         _tankId       = -1;
                if (_dtReport != null)
                {
                    DataRow _dr = _dtReport.Rows[0];
                    _ticketId = Convert.ToInt64(_dr["ticket_id"]);
                    _tankId   = Convert.ToInt64(_dr["tank_id"]);
                    _importReport.StationName    = selTank.StationName;
                    _importReport.ReportDate     = Convert.ToDateTime(_dr["ticketdate"]);
                    _importReport.DriverName     = Convert.ToString(_dr["drivername"]);
                    _importReport.CarPlate       = Convert.ToString(_dr["carplate"]);
                    _importReport.StaffName      = Convert.ToString(_dr["staffname"]);
                    _importReport.StaffPos       = Convert.ToString(_dr["staffpos"]);
                    _importReport.TemplateBottle = Convert.ToString(_dr["templatebottle"]);
                    _importReport.ImportCapacity = Convert.ToDouble(_dr["importcapacity"]);
                    long fuelId = Convert.ToInt64(_dr["fuel_id"]);
                    _importReport.Fuel = BusinessHelper.FindFuelById(fuelId);

                    _importReport.BeginCapacity  = Convert.ToDouble(_dr["capacity"]);
                    _importReport.BeginLevel     = Convert.ToDouble(_dr["level"]);
                    _importReport.BeginTotalPump = Convert.ToUInt64(_dr["pumptotal"]);
                    _importReport.ExStore        = Convert.ToString(_dr["exstore"]);
                    _importReport.SealId         = Convert.ToString(_dr["sealid"]);
                    _importReport.SealStatus     = Convert.ToBoolean(_dr["sealstatus"]);
                }
                else
                {
                    System.Windows.MessageBox.Show(@"Phiếu không tồn tại!!!", @"Kết thúc nhập bồn", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    return;
                }
                _importReport.EndTotalPump = BusinessHelper.FindPumpTotalByTankId(selTank.TankId);
                _importReport.EndCapacity  = selTank.Capacity;
                _importReport.EndLevel     = selTank.FuelLevel;
                _importReport.RealCapacity = _importReport.EndCapacity - _importReport.BeginCapacity;

                if (!BusinessHelper.UpdateImportTicket(_ticketId, _importReport.EndTotalPump, _importReport.EndCapacity, _importReport.EndLevel))
                {
                    App.Log.LogInfoMessage(String.Format("Update ticket {0} failed", _ticketId));
                    System.Windows.MessageBox.Show(@"Lỗi trong quá trình cập nhật phiếu!!!", @"Kết thúc nhập bồn", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    return;
                }
                else
                {
                    String _pubTopic = String.Format(@"importticket/{0}", _tankId);
                    String _pubData  = String.Format(@"{{""ticketId"": {0} }}", _ticketId);
                    if ((ClientPub != null) && (!ClientPub.IsConnected))
                    {
                        string pubClientId = Guid.NewGuid().ToString();


                        ClientPub.Connect(pubClientId, _MqttUser, _MqttPwd);
                    }
                    ClientPub.Publish(_pubTopic, Encoding.UTF8.GetBytes(_pubData), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);

                    selTank.IsImportFinished = true;

                    App.Log.LogDebugMessage("Topic: " + _pubTopic + "\t Data:" + _pubData);
                }



                ImportReportWindow    importReportWnd = new ImportReportWindow();
                ViewModelImportReport vmImportReport;
                if (App.Demo == 1)
                {
                    vmImportReport = new ViewModelImportReport();
                }
                else
                {
                    vmImportReport = new ViewModelImportReport(_importReport);
                }


                importReportWnd.DataContext = vmImportReport;
                importReportWnd.ShowDialog();
            }
            catch (Exception ex)
            {
                App.Log.LogException(ex);
            }
        }