public TransactionImport(TransactionImportContext transactionImportContext, Account source) { _context = transactionImportContext; Credit = source; Result = new ImportResult(); }
protected static ImportResult ImportPaypal(string contents) { string[] lines = contents.Split('\n'); ImportResult result = new ImportResult(); List<ImportedRow> rows = new List<ImportedRow>(); foreach (string line in lines) { string[] parts = line.Split('\t'); if (parts.Length < 30) { continue; } if (StripQuotes(parts[6]) != "SEK") { continue; // HACK: Need to fix currency support at some time } // Get current balance from the first line in the file if (result.CurrentBalance == 0.0) { result.CurrentBalance = Double.Parse(StripQuotes(parts[34]), CultureInfo.InvariantCulture); } ImportedRow row = new ImportedRow(); // DEBUG -- REMOVE WHEN DEPLOYING if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("New Row -----"); Console.WriteLine("- SuppliedTxId: {0}", parts[12]); Console.WriteLine("- Comment: {0}", parts[4]); Console.WriteLine("- DateTime: {0} {1}", parts[0], parts[1]); Console.WriteLine("- AmountGross: {0}", parts[7]); Console.WriteLine("- Fee: {0}", parts[8]); Console.WriteLine("- AmountNet: {0}", parts[9]); } row.SuppliedTransactionId = StripQuotes(parts[12]); row.Comment = StripQuotes(parts[4]); row.DateTime = DateTime.Parse(StripQuotes(parts[0]) + " " + StripQuotes(parts[1]), CultureInfo.InvariantCulture); row.AmountCentsGross = Int64.Parse(StripQuotes(parts[7]).Replace(".", "").Replace(",","")); row.FeeCents = Int64.Parse(StripQuotes(parts[8]).Replace(".", "").Replace(",", "")); row.AmountCentsNet = Int64.Parse(StripQuotes(parts[9]).Replace(".", "").Replace(",", "")); rows.Add(row); } result.Rows = rows; return result; }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); // The trackpoints List<RouteSegment> routeSegments = new List<RouteSegment>(); bool lastTrackpointWasInvalid = false; bool thisTrackpointIsInvalid = false; RouteSegment rs = new RouteSegment(); int current = 0; int total = sessionToImport.Trackpoints.Count; foreach (D303_Trk_Point_Type tp in sessionToImport.Trackpoints) { Waypoint waypoint = new Waypoint(); waypoint.Time = tp.TimeAsDateTime; waypoint.LongLat = new LongLat(tp.Position.LongitudeAsDegrees, tp.Position.LatitudeAsDegrees); waypoint.Altitude = (double)tp.Altitude; waypoint.HeartRate = (double)tp.HeartRate; thisTrackpointIsInvalid = (tp.Position.Latitude == 2147483647 && tp.Position.Longitude == 2147483647); if (!thisTrackpointIsInvalid) rs.Waypoints.Add(waypoint); if (thisTrackpointIsInvalid && lastTrackpointWasInvalid && rs.Waypoints.Count > 0) { routeSegments.Add(rs); rs = new RouteSegment(); } lastTrackpointWasInvalid = thisTrackpointIsInvalid; current++; if (WorkProgress != null && current % 10 == 0) { WorkProgress(this, new WorkProgressEventArgs((double)current / total)); } } if (rs.Waypoints.Count > 0) { routeSegments.Add(rs); } // The laps List<double> elapsedTimes = new List<double>(); double elapsedTime = 0; DateTime startTime = DateTime.MinValue; foreach (D1001_Lap_Type xLap in sessionToImport.Laps) { if (startTime == DateTime.MinValue) startTime = xLap.StartTimeAsDateTime; elapsedTimes.Add(elapsedTime); elapsedTime += (double)xLap.TotalTime / 100; } LapCollection laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments); importResult.Route = new Route(routeSegments); importResult.Laps = laps; importResult.Succeeded = true; if (EndWork != null) EndWork(this, new EventArgs()); }
public void AddImportedFile_AddsFileResult() { var result = new ImportResult(); var file = new ImportFileResult("1.txt", 123); result.AddImportedFile(file); Assert.AreEqual(1, result.Files.Count(), "Expected 1 file in Files" ); Assert.That(result.Files.Any(f => f == file), "Expected file not found"); }
public void Import() { ImportResult = new ImportResult(); var tcxImporter = new TCXImporter { FileName = itemToImport.FileInfo.FullName, IdToImport = DateTime.Parse(itemToImport.Id).ToString("yyyy-MM-dd HH:mm:ss") }; tcxImporter.Import(); ImportResult = tcxImporter.ImportResult; }
public CreateImportTests(ImportRepository repository) { _repository = repository; var import = new ImportResult { Date = DateTime.Now, ImportType = "", Name = "Import", }; var transaction = new Transaction { Date = new DateTime(2010, 1, 1), Amount = 100, Reference = "ABCD", Description = "Transaction" }; transaction.Credit.Add(new Amount(TestData.Bank, EntryType.Credit, 100)); transaction.Debit.Add(new Amount(TestData.Expenses, EntryType.Debit, 100)); var transactions = new[] { transaction }; _repository.Save(import, transactions); }
public void AddImportedFile_ThrowsForNullFile() { var result = new ImportResult(); try { result.AddImportedFile(null); } catch (ArgumentNullException exception) { Assert.AreEqual("file", exception.ParamName); throw; } }
public void Import() { ImportResult = new ImportResult(); var document = Document.Open(FileName); if (document != null && document.Sessions.Count > 0) { ImportResult.Succeeded = true; ImportResult.Route = document.Sessions[0].Route; ImportResult.Laps = document.Sessions[0].Laps; } else { ImportResult.Succeeded = false; } }
public int Save(ImportResult result, IEnumerable<Transaction> transactions) { using (var session = _repository.DocumentStore.OpenSession()) { var document = _mappingEngine.Map<Documents.ImportResult>(result); document.Transactions = ( from t in transactions select _mappingEngine.Map<ImportedTransaction>(t) ).ToArray(); session.Store(document); session.SaveChanges(); return result.Id; } }
public void Import() { _importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); // The trackpoints var routeSegments = new List<RouteSegment>(); var rs = new RouteSegment(); var current = 0; var total = _trackToImport.GetTrackInfo().NumbetOfTrackPoints; var elapsedTimes = new List<double>(); DateTime startTime = DateTime.MinValue; foreach (var tp in _trackToImport.GetTrackPoints()) { var waypoint = new Waypoint { Time = tp.Time, LongLat = new LongLat((double)tp.Longitude, (double)tp.Latitude), Altitude = tp.Altitude }; if (tp.HasMark(RegSEPointType.WayPoint)) { elapsedTimes.Add((tp.Time - startTime).TotalSeconds); } rs.Waypoints.Add(waypoint); current++; if (WorkProgress != null && current % 10 == 0) { WorkProgress(this, new WorkProgressEventArgs((double)current / total)); } } if (rs.Waypoints.Count > 0) { routeSegments.Add(rs); } _importResult.Route = new Route(routeSegments); // create one lap (from start to finish) LapCollection laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments); _importResult.Laps = laps; _importResult.Succeeded = true; if (EndWork != null) EndWork(this, new EventArgs()); }
public HmacImportDataController() { var result = new ImportResult(66412, "Invalid start date"); var bookingResults = new ImportResult(55827, "Invalid start date"); bookingResults.InnerResults = new ImportResult[] { new ImportResult(1223, "Missing Insertion Rate for Bill / Pay"), new ImportResult(1224), new ImportResult(1225), new ImportResult(1226), new ImportResult(1227), new ImportResult(1228, "Missing Insertion Rate for Bill / Pay") }; result.InnerResults = new []{bookingResults}; exceptionToThrow.ImportResult = result; }
public void Import() { _importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); // The trackpoints var routeSegments = new List<RouteSegment>(); var rs = new RouteSegment(); var current = 0; var total = _trackToImport.TrackPointsCount; var track = _gsGH615MReader.GetTrack(_trackToImport); foreach (var tp in track.GetTrackPoints()) { var waypoint = new Waypoint { Time = tp.Time, LongLat = new LongLat((double) tp.Longitude, (double) tp.Latitude), Altitude = tp.Altitude, HeartRate = tp.Pulse }; rs.Waypoints.Add(waypoint); current++; if (WorkProgress != null && current % 10 == 0) { WorkProgress(this, new WorkProgressEventArgs((double)current / total)); } } if (rs.Waypoints.Count > 0) { routeSegments.Add(rs); } _importResult.Route = new Route(routeSegments); // create one lap (from start to finish) DateTime startTime = DateTime.MinValue; LapCollection laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, new List<double>(), routeSegments); _importResult.Laps = laps; _importResult.Succeeded = true; if (EndWork != null) EndWork(this, new EventArgs()); }
public int Save(ImportResult result, IEnumerable<Transaction> transactions) { using (var transaction = new TransactionScope()) { var model = result.Map<Models.ImportResult>(); var transactionRecords = new List<Models.Transaction>(); var transactionComponents = new List<Models.TransactionComponent>(); foreach (var item in transactions) { var record = item.Map<Models.Transaction>(); transactionRecords.Add(record); transactionComponents.AddRange(item.Credit.Select(amount => amount.Map(new Models.TransactionComponent {TransactionId = record.Id, EntryTypeName = EntryType.Credit.ToString() }))); transactionComponents.AddRange(item.Debit.Select(amount => amount.Map(new Models.TransactionComponent {TransactionId = record.Id, EntryTypeName = EntryType.Debit.ToString() }))); } _database.Execute( @"INSERT INTO [Transaction] (Id, Date, Amount, Reference, Description) VALUES (@id, @date, @amount, @reference, @description)", transactionRecords); _database.Execute( @"INSERT INTO [TransactionComponent] (TransactionId, AccountId, EntryTypeName, Amount, Annotation, AppliedByRuleId) VALUES (@transactionId, @accountId, @entryTypeName, @amount, ISNULL(@annotation, ''), @appliedByRuleId)", transactionComponents); var importId = _database.ExecuteScalar<int>( @"INSERT INTO ImportResult (Name, ImportTypeName, Date) OUTPUT inserted.id VALUES (@name, @importType, @date)", model); _database.Execute( @"INSERT INTO ImportedTransaction (Id, ImportId, Unclassified, Amount) VALUES (@id, @importId, @unclassified, @amount)", transactionRecords .MapAll<Models.ImportedTransaction>() .Select(t => new {t.Id, importId, t.Unclassified, t.Amount})); transaction.Complete(); return importId; } }
protected static ImportStats ProcessImportedData(ImportResult import, Organization organization, Person importingPerson) { FinancialAccount payPalAccount = organization.FinancialAccounts.AssetsPaypal; FinancialAccount bankFees = organization.FinancialAccounts.CostsBankFees; FinancialAccount donations = organization.FinancialAccounts.IncomeDonations; int autoDepositLimit = 1000; // TODO: Get from organization parameters int autoWithdrawalLimit = 0; ImportStats result = new ImportStats(); foreach (ImportedRow row in import.Rows) { // Each row is at least a stub, probably more. // If too old, ignore. if (row.DateTime < new DateTime(2008, 12, 4)) { continue; } string importKey = row.SuppliedTransactionId; // If importKey is empty, construct a hash from the data fields. if (string.IsNullOrEmpty(importKey)) { string hashKey = row.HashBase + row.Comment + (row.AmountCentsNet / 100.0).ToString(CultureInfo.InvariantCulture) + row.CurrentBalance.ToString(CultureInfo.InvariantCulture) + row.DateTime.ToString("yyyy-MM-dd-hh-mm-ss"); importKey = SHA1.Hash(hashKey).Replace(" ", ""); } if (importKey.Length > 30) { importKey = importKey.Substring(0, 30); } Int64 amountCents = row.AmountCentsNet; if (amountCents == 0) { amountCents = row.AmountCentsGross; } Dictionary<int, long> nominalTransaction = new Dictionary<int, long>(); FinancialTransaction transaction = null; try { transaction = FinancialTransaction.FromImportKey(organization, importKey); } catch (Exception) { // if we get here, that means the transaction did not yet exist transaction = FinancialTransaction.ImportWithStub(organization.Identity, row.DateTime, payPalAccount.Identity, amountCents, row.Comment, importKey, importingPerson.Identity); result.ImportedTransactionCount++; if (transaction == null) { // No transaction was created. This is an error condition as it should have been created if it didn't // exist, and the "exist" case is handled in the FromImportKey attempt above. Abort with error. // Throw new exception? continue; } } result.ProcessedTransactionCount++; nominalTransaction[payPalAccount.Identity] = amountCents; // The transaction was created. Examine if the autobook criteria are true. if (amountCents < 0) { if ((-amountCents) < autoWithdrawalLimit * 100) { // Book against autoWithdrawal account. nominalTransaction[bankFees.Identity] = -amountCents; } } else if (amountCents > 0) { if (row.FeeCents < 0) { // This is always an autodeposit, if there is a fee (which is never > 0.0) nominalTransaction[bankFees.Identity] = -row.FeeCents; nominalTransaction[donations.Identity] = -row.AmountCentsGross; } else if (amountCents < autoDepositLimit * 100) { // Book against autoDeposit account. nominalTransaction[donations.Identity] = -amountCents; } } if (transaction.Rows.AmountCentsTotal != 0) // If transaction is unbalanced, balance it { if (transaction.RecalculateTransaction(nominalTransaction, importingPerson)) { result.ModifiedTransactionCount++; } } } return result; }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual ImportResult ImportProductsFromExcel( Stream stream, CancellationToken cancellationToken, IProgress <ImportProgressInfo> progress = null) { Guard.ArgumentNotNull(() => stream); var result = new ImportResult(); int saved = 0; if (progress != null) { progress.Report(new ImportProgressInfo { ElapsedTime = TimeSpan.Zero }); } using (var scope = new DbContextScope(ctx: _rsProduct.Context, autoDetectChanges: false, proxyCreation: false, validateOnSave: false)) { try { using (var segmenter = new DataSegmenter <Product>(stream)) { result.TotalRecords = segmenter.TotalRows; while (segmenter.ReadNextBatch() && !cancellationToken.IsCancellationRequested) { var batch = segmenter.CurrentBatch; // Perf: detach all entities _rsProduct.Context.DetachAll(); // Update progress for calling thread if (progress != null) { progress.Report(new ImportProgressInfo { TotalRecords = result.TotalRecords, TotalProcessed = segmenter.CurrentSegmentFirstRowIndex - 1, NewRecords = result.NewRecords, ModifiedRecords = result.ModifiedRecords, ElapsedTime = DateTime.UtcNow - result.StartDateUtc, TotalWarnings = result.Messages.Count(x => x.MessageType == ImportMessageType.Warning), TotalErrors = result.Messages.Count(x => x.MessageType == ImportMessageType.Error), }); } // =========================================================================== // 1.) Import products // =========================================================================== try { saved = ProcessProducts(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessProducts"); } // reduce batch to saved (valid) products. // No need to perform import operations on errored products. batch = batch.Where(x => x.Entity != null && !x.IsTransient).AsReadOnly(); // update result object result.NewRecords += batch.Count(x => x.IsNew && !x.IsTransient); result.ModifiedRecords += batch.Count(x => !x.IsNew && !x.IsTransient); // =========================================================================== // 2.) Import SEO Slugs // IMPORTANT: Unlike with Products AutoCommitEnabled must be TRUE, // as Slugs are going to be validated against existing ones in DB. // =========================================================================== if (batch.Any(x => x.IsNew || (x.ContainsKey("SeName") || x.NameChanged))) { try { _rsProduct.Context.AutoDetectChangesEnabled = true; ProcessSlugs(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessSeoSlugs"); } finally { _rsProduct.Context.AutoDetectChangesEnabled = false; } } // =========================================================================== // 3.) Import Localizations // =========================================================================== try { ProcessLocalizations(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessLocalizations"); } // =========================================================================== // 4.) Import product category mappings // =========================================================================== if (batch.Any(x => x.ContainsKey("CategoryIds"))) { try { ProcessProductCategories(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessProductCategories"); } } // =========================================================================== // 5.) Import product manufacturer mappings // =========================================================================== if (batch.Any(x => x.ContainsKey("ManufacturerIds"))) { try { ProcessProductManufacturers(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessProductManufacturers"); } } // =========================================================================== // 6.) Import product picture mappings // =========================================================================== if (batch.Any(x => x.ContainsKey("Picture1") || x.ContainsKey("Picture2") || x.ContainsKey("Picture3"))) { try { ProcessProductPictures(batch, result); } catch (Exception ex) { result.AddError(ex, segmenter.CurrentSegment, "ProcessProductPictures"); } } } } } catch (Exception ex) { result.AddError(ex, null, "ReadFile"); } } result.EndDateUtc = DateTime.UtcNow; if (cancellationToken.IsCancellationRequested) { result.Cancelled = true; result.AddInfo("Import task was cancelled by user"); } return(result); }
public ImportResult Import(GLTFAccessor.ImportResult[] accessors, GLTFNode.ImportResult[] nodes, ImportSettings importSettings) { bool multiRoots = nodes.Where(x => x.IsRoot).Count() > 1; ImportResult result = new ImportResult(); result.clip = new AnimationClip(); result.clip.name = name; result.clip.legacy = importSettings.useLegacyClips; for (int i = 0; i < channels.Length; i++) { Channel channel = channels[i]; if (samplers.Length <= channel.sampler) { Debug.LogWarning($"GLTFUtility: Animation channel points to sampler at index {channel.sampler} which doesn't exist. Skipping animation clip."); continue; } Sampler sampler = samplers[channel.sampler]; // Get interpolation mode InterpolationMode interpolationMode = importSettings.interpolationMode; if (interpolationMode == InterpolationMode.ImportFromFile) { interpolationMode = sampler.interpolation; } if (interpolationMode == InterpolationMode.CUBICSPLINE) { Debug.LogWarning("Animation interpolation mode CUBICSPLINE not fully supported, result might look different."); } string relativePath = ""; GLTFNode.ImportResult node = nodes[channel.target.node.Value]; while (node != null && !node.IsRoot) { if (string.IsNullOrEmpty(relativePath)) { relativePath = node.transform.name; } else { relativePath = node.transform.name + "/" + relativePath; } if (node.parent.HasValue) { node = nodes[node.parent.Value]; } else { node = null; } } // If file has multiple root nodes, a new parent will be created for them as a final step of the import process. This parent f***s up the curve relative paths. // Add node.transform.name to path if there are multiple roots. This is not the most elegant fix but it works. // See GLTFNodeExtensions.GetRoot if (multiRoots) { relativePath = node.transform.name + "/" + relativePath; } System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; float[] keyframeInput = accessors[sampler.input].ReadFloat().ToArray(); switch (channel.target.path) { case "translation": Vector3[] pos = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve posX = new AnimationCurve(); AnimationCurve posY = new AnimationCurve(); AnimationCurve posZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { posX.AddKey(CreateKeyframe(k, keyframeInput, pos, x => - x.x, interpolationMode)); posY.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.y, interpolationMode)); posZ.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.z, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ); break; case "rotation": Vector4[] rot = accessors[sampler.output].ReadVec4().ToArray(); AnimationCurve rotX = new AnimationCurve(); AnimationCurve rotY = new AnimationCurve(); AnimationCurve rotZ = new AnimationCurve(); AnimationCurve rotW = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { // The Animation window in Unity shows keyframes incorrectly converted to euler. This is only to deceive you. The quaternions underneath work correctly rotX.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.x, interpolationMode)); rotY.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.y, interpolationMode)); rotZ.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.z, interpolationMode)); rotW.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.w, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW); break; case "scale": Vector3[] scale = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve scaleX = new AnimationCurve(); AnimationCurve scaleY = new AnimationCurve(); AnimationCurve scaleZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { scaleX.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.x, interpolationMode)); scaleY.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.y, interpolationMode)); scaleZ.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.z, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localScale.x", scaleX); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.y", scaleY); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.z", scaleZ); break; case "weights": Debug.LogWarning("GLTFUtility: Morph weights in animation is not supported"); break; } } return(result); }
//private void CreatePointDataset(string tableName) //{ // Workspace workspace = new Workspace(); // DatasourceConnectionInfo info = new DatasourceConnectionInfo(); // Datasource datasource = GetDbDatasource(workspace, info); // var datasetVector = (DatasetVector)datasource.Datasets[tableName]; // if (datasetVector == null) // { // CreateDataset(datasource, DatasetType.Point, tableName); // } // //只取了数据结构,没有取数据 // var recordset = datasetVector.GetRecordset(true, SuperMap.Data.CursorType.Dynamic); // recordset.Edit(); // recordset.fi //} private void InsertRecordSetToDb(string shapeFieldName, string tableName) { Workspace workspace = new Workspace(); DatasourceConnectionInfo info = new DatasourceConnectionInfo(); var filePath = $"{Directory.GetCurrentDirectory()}\\{Guid.NewGuid().ToString()}"; var files = new List <string> { $"{filePath}.udb", $"{filePath}.udd" }; Datasource datasource = GetDbDatasource(workspace, info); if (datasource != null) { //临时数据源 DatasourceConnectionInfo tempInfo = new DatasourceConnectionInfo(); //设置数据源连接的引擎类型 tempInfo.EngineType = EngineType.UDB; tempInfo.Alias = tableName; tempInfo.Server = filePath; // 创建/打开数据库数据源 Datasource tempDatasource = workspace.Datasources.Create(tempInfo); Recordset recordset = null, tempRecordset = null; if (tempDatasource != null) { ImportResult result = ImportShpToTemp(shapeFieldName, tempDatasource, tableName); if (result.FailedSettings.Length == 0) { Console.WriteLine($"导入{shapeFieldName}成功!"); try { for (int index = 0; index < tempDatasource.Datasets.Count; index++) { DatasetVector tempDatasetVector = (DatasetVector)tempDatasource.Datasets[index]; tempRecordset = tempDatasetVector.GetRecordset(false, SuperMap.Data.CursorType.Dynamic); //没有数据 if (tempRecordset.RecordCount == 0) { continue; } var tempFieldInfos = tempDatasetVector.FieldInfos; //注意:数据集是手工录入的,不是超图sdk生成的,所以不能删除数据集 //如果更新数据集中的记录,则应该操纵记录集(删除、修改、新增) var datasetVector = (DatasetVector)datasource.Datasets[tableName]; if (datasetVector == null) { CreateDataset(datasource, DatasetType.Point, tableName); //throw new Exception($"不存在数据集名称为{tableName}的数据集!"); } //删去之前的所有记录 //datasetVector.GetRecordset(false, SuperMap.Data.CursorType.Dynamic).DeleteAll(); //只取了数据结构,没有取数据 recordset = datasetVector.GetRecordset(true, SuperMap.Data.CursorType.Dynamic); //设置批量提交 // 设置批量更新的限度为5000,注意一定要在开始批量更新前设置MaxRecordCount! recordset.Batch.MaxRecordCount = 500; // 开始批量更新,当添加到设置的MaxRecordCount的下一条记录时,将会将MaxRecordCount条记录自动提交到数据库中。 recordset.Batch.Begin(); tempRecordset.MoveFirst(); //遍历临时记录集 for (Int32 i = 0; i < tempRecordset.RecordCount; i++) { //往mysql新增记录 SuperMap.Data.Geometry geoPoint = tempRecordset.GetGeometry(); recordset.AddNew(geoPoint); //SeekID:在记录中搜索指定 ID 号的记录,并定位该记录为当前记录。 recordset.MoveLast(); foreach (SuperMap.Data.FieldInfo fileInfo in tempFieldInfos) { if (!fileInfo.IsSystemField && IsHaveField(datasetVector.FieldInfos, fileInfo.Name)) { recordset.Edit(); recordset.SetFieldValue(fileInfo.Name, tempRecordset.GetFieldValue(fileInfo.Name)); Object valueID = recordset.GetFieldValue(fileInfo.Name); } } //处理业务数据 tempRecordset.MoveNext(); //recordset.Update(); } // 使用批量更新的Update,提交没有自动提交的记录 recordset.Batch.Update(); } } catch (Exception ex) { throw ex; } finally { //示例程序BatchAdd说明要释放记录集 if (recordset != null) { recordset.Dispose(); } if (tempRecordset != null) { tempRecordset.Dispose(); } } } else { throw new Exception($"导入{shapeFieldName}失败!"); } } else { throw new Exception($"创建临时数据源{filePath}失败!"); } } // 释放工作空间资源 info.Dispose(); workspace.Dispose(); foreach (var file in files) { if (File.Exists(file)) { File.Delete(file); } } MessageBox.Show("成功!"); }
/* private void ImportGPX10() { if (BeginWork != null) BeginWork(this, new EventArgs()); NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; XmlTextReader sr = new XmlTextReader(fileName); XmlSerializer xSerializer = new XmlSerializer(typeof(gpx10Type)); gpx10Type gpx = (gpx10Type)xSerializer.Deserialize(sr); sr.Close(); XmlNamespaceManager nsManager = new XmlNamespaceManager(sr.NameTable); nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); importResult = new ImportResult(); // route List<RouteSegment> routeSegments = new List<RouteSegment>(); foreach (gpxTrk trk in gpx.trk) { for (int i = trk.trkseg.GetLowerBound(0); i <= trk.trkseg.GetUpperBound(0); i++) { RouteSegment routeSegment = new RouteSegment(); for (int j = trk.trkseg.GetLowerBound(1); j <= trk.trkseg.GetUpperBound(1); j++) { gpxTrkTrksegTrkpt wpt = trk.trkseg[i][j]; double lat = (double)wpt.lat; double lon = (double)wpt.lon; DateTime time = wpt.time; double? heartRate = null; double? altitude = null; routeSegment.Waypoints.Add(new Waypoint(time, new LongLat(lon, lat), altitude, heartRate)); } routeSegments.Add(routeSegment); } } importResult.Route = new Route(routeSegments); // laps LapCollection laps = new LapCollection(); importResult.Laps = laps; if (EndWork != null) EndWork(this, new EventArgs()); } */ private void ImportGPX11() { ImportResult = new ImportResult(); var isGPX10 = (GPXUtil.GetGPXVersion(fileName) == GPXVersion.GPX10); string gpx10convertedFileName = null; string polarConvertedFileName = null; var originalFileName = fileName; if (BeginWork != null) BeginWork(this, new EventArgs()); // check if the file is in gpx 1.0 format and convert it to gpx 1.1 if necessary if (isGPX10) { gpx10convertedFileName = Path.GetTempFileName(); GPXUtil.ConvertGPX10ToGPX11(fileName, gpx10convertedFileName); fileName = gpx10convertedFileName; } // check if the file is an invalid Polar ProTrainer file and correct if necessary if (PolarProTrainerUtil.IsPolarProTrainerGPXFile(fileName)) { polarConvertedFileName = Path.GetTempFileName(); PolarProTrainerUtil.CorrectPolarProTrainerGPXFile(fileName, polarConvertedFileName); fileName = polarConvertedFileName; } var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." }; var sr = new XmlTextReader(fileName); var xSerializer = new XmlSerializer(typeof(gpx11Type)); var gpx11 = (gpx11Type)xSerializer.Deserialize(sr); sr.Close(); var nsManager = new XmlNamespaceManager(sr.NameTable); // add namespace for split times and heart rates (from SportsTracks software) nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); // add namespace for map reading information (QuickRoute native) nsManager.AddNamespace("mr", "http://www.matstroeng.se/quickroute/map-reading"); // pre-store heart rates in dictionary (if present) var heartRates = new Dictionary<DateTime, double>(); // pre-store map-readings in map reading collection (if present) var mapReadings = new List<DateTime>(); if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:heartRateTrack/st:heartRate[@time and @bpm]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { DateTime time; double bpm; if (DateTime.TryParse(node.Attributes["time"].Value, out time) && double.TryParse(node.Attributes["bpm"].Value, NumberStyles.Any, nfi, out bpm)) { time = time.ToUniversalTime(); if(!heartRates.ContainsKey(time)) heartRates.Add(time, bpm); } } } } if(element.Name == "mr:map-reading") { DateTime start, end; if (DateTime.TryParse(element.Attributes["start"].Value, out start) && DateTime.TryParse(element.Attributes["end"].Value, out end)) { mapReadings.Add(start.ToUniversalTime()); mapReadings.Add(end.ToUniversalTime()); } } } } mapReadings = FilterMapReadings(mapReadings); // QuickRoute route var noOfWaypoints = 0; var noOfWaypointsWithTimes = 0; var routeSegments = new List<RouteSegment>(); // first use GPX track if (gpx11.trk != null) { foreach (var trk in gpx11.trk) { // Garmin Training Center exports each lap as a separate trkseg with end time of trkseg n equal to start time of trkseg n+1 // handle this issue foreach (var trkseg in trk.trkseg) { var routeSegment = new RouteSegment(); wptType lastWpt = null; if (trkseg.trkpt != null) { foreach (var wpt in trkseg.trkpt) { if (lastWpt == null || wpt.time != lastWpt.time) { if (wpt.extensions != null && wpt.extensions.Any != null && wpt.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double)wpt.lat; var lon = (double)wpt.lon; double? heartRate = null; double? altitude = null; // check for heartrate in SportsTracks extensions if (heartRates.ContainsKey(wpt.time)) heartRate = heartRates[wpt.time]; // check for heartrate in Garmin Trackpoint Extensions heartRate = GetGarminHeartRateFromWaypoint(wpt) ?? heartRate; if (wpt.eleSpecified) { altitude = (double?)wpt.ele; } if (wpt.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(wpt.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; lastWpt = wpt; } } noOfWaypoints++; } } } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } } // if no GPX track - use GPX route if (noOfWaypointsWithTimes == 0 && gpx11.rte != null) { foreach (var route in gpx11.rte) { var routeSegment = new RouteSegment(); foreach (var rtept in route.rtept) { if (rtept.extensions != null && rtept.extensions.Any != null && rtept.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double) rtept.lat; var lon = (double) rtept.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(rtept.time)) heartRate = heartRates[rtept.time]; if (rtept.eleSpecified) { altitude = (double?) rtept.ele; } if (rtept.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(rtept.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; } } noOfWaypoints++; } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } // add map reading waypoints routeSegments = Route.AddMapReadingWaypoints(routeSegments, mapReadings); // concat route segments if they are close enough (oddly enough, Garmin Training Center v2 seems to create a trkseg for each lap) var lapsFromConcatenatedRouteSegments = new List<Lap>(); if (routeSegments.Count > 0) { var concatenatedRouteSegments = new List<RouteSegment>() { routeSegments[0] }; for (var i = 1; i < routeSegments.Count; i++) { if (concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].LastWaypoint.Time.AddSeconds(10) > routeSegments[i].FirstWaypoint.Time) { lapsFromConcatenatedRouteSegments.Add(new Lap(concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].LastWaypoint.Time, LapType.Lap)); concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].Waypoints.AddRange(routeSegments[i].Waypoints); } } routeSegments = concatenatedRouteSegments; } importResult.Succeeded = (noOfWaypointsWithTimes > 0); if (ImportResult.Succeeded) { importResult.Route = new Route(routeSegments); // laps var laps = new LapCollection(); var startTime = ImportResult.Route.FirstWaypoint.Time; // from GPX st:split if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:splits/st:split[@time]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { var elapsedTime = double.Parse(node.Attributes["time"].Value, nfi); var lap = new Lap(startTime.AddSeconds(elapsedTime), LapType.Lap); laps.Add(lap); } } } } } // from GPX waypoints if (gpx11.wpt != null && laps.Count == 0) { foreach (var waypoint in gpx11.wpt) { if (waypoint.timeSpecified) { laps.Add(new Lap(waypoint.time, LapType.Lap)); } } } laps.AddRange(lapsFromConcatenatedRouteSegments); foreach (var rs in routeSegments) { laps.Add(new Lap(rs.FirstWaypoint.Time, LapType.Start)); laps.Add(new Lap(rs.LastWaypoint.Time, LapType.Stop)); } importResult.Laps = laps; } else { if (noOfWaypoints == 0) { importResult.Error = ImportError.NoWaypoints; } else if (noOfWaypointsWithTimes == 0) { importResult.Error = ImportError.NoWaypointTimes; } } if (gpx10convertedFileName != null) { File.Delete(gpx10convertedFileName); fileName = originalFileName; } if (polarConvertedFileName != null) { File.Delete(polarConvertedFileName); fileName = originalFileName; } // import Polar HRM file with same base file name as the gpx file, if existing var extension = new FileInfo(fileName).Extension; if(extension != "") { string hrmFileName = new FileInfo(fileName).FullName.Replace(extension, ".hrm"); if(File.Exists(hrmFileName)) { new PolarHRMImporter().AddLapsAndHRData(hrmFileName, importResult); } } if (EndWork != null) EndWork(this, new EventArgs()); }
protected ImportResult ImportPaypal (string contents) { string[] lines = contents.Split('\n'); ImportResult result = new ImportResult(); List<ImportedRow> rows = new List<ImportedRow>(); foreach (string line in lines) { string[] parts = line.Split('\t'); if (parts.Length < 30) { continue; } if (StripQuotes(parts[6]) != "SEK") { continue; // HACK: Need to fix currency support at some time } // Get current balance from the first line in the file if (result.CurrentBalance == 0.0) { result.CurrentBalance = Double.Parse(StripQuotes(parts[34]), CultureInfo.InvariantCulture); } ImportedRow row = new ImportedRow(); row.SuppliedTransactionId = StripQuotes(parts[12]); row.Comment = StripQuotes(parts[4]); row.DateTime = DateTime.Parse(StripQuotes(parts[0]) + " " + StripQuotes(parts[1]), CultureInfo.InvariantCulture); row.AmountCentsGross = Int64.Parse(StripQuotes(parts[7]).Replace(".", "")); row.Fee = Double.Parse(StripQuotes(parts[8]), CultureInfo.InvariantCulture); row.AmountCentsNet = Int64.Parse(StripQuotes(parts[9]).Replace(".", "")); rows.Add(row); } result.Rows = rows; return result; }
public void WhenTheFolderIsImported() { var factory = new MusicFolderFactory(_fileSystem); _result = factory.Import(_path); }
public ImportResult ImportApp() { var result = new ImportResult(); var request = HttpContext.Current.Request; //var appId = int.Parse(request["AppId"]); var zoneId = int.Parse(request["ZoneId"]); if (request.Files.Count > 0) { var zipImport = new ZipImport(zoneId, null, PortalSettings.UserInfo.IsSuperUser); result.Succeeded = zipImport.ImportApp(request.Files[0].InputStream, HttpContext.Current.Server, PortalSettings, result.Messages); } return result; }
/* private void ImportGPX10() { if (BeginWork != null) BeginWork(this, new EventArgs()); NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; XmlTextReader sr = new XmlTextReader(fileName); XmlSerializer xSerializer = new XmlSerializer(typeof(gpx10Type)); gpx10Type gpx = (gpx10Type)xSerializer.Deserialize(sr); sr.Close(); XmlNamespaceManager nsManager = new XmlNamespaceManager(sr.NameTable); nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); importResult = new ImportResult(); // route List<RouteSegment> routeSegments = new List<RouteSegment>(); foreach (gpxTrk trk in gpx.trk) { for (int i = trk.trkseg.GetLowerBound(0); i <= trk.trkseg.GetUpperBound(0); i++) { RouteSegment routeSegment = new RouteSegment(); for (int j = trk.trkseg.GetLowerBound(1); j <= trk.trkseg.GetUpperBound(1); j++) { gpxTrkTrksegTrkpt wpt = trk.trkseg[i][j]; double lat = (double)wpt.lat; double lon = (double)wpt.lon; DateTime time = wpt.time; double? heartRate = null; double? altitude = null; routeSegment.Waypoints.Add(new Waypoint(time, new LongLat(lon, lat), altitude, heartRate)); } routeSegments.Add(routeSegment); } } importResult.Route = new Route(routeSegments); // laps LapCollection laps = new LapCollection(); importResult.Laps = laps; if (EndWork != null) EndWork(this, new EventArgs()); } */ private void ImportGPX11() { ImportResult = new ImportResult(); var isGPX10 = (GPXUtil.GetGPXVersion(fileName) == GPXVersion.GPX10); string gpx10convertedFileName = null; string polarConvertedFileName = null; var originalFileName = fileName; if (BeginWork != null) BeginWork(this, new EventArgs()); // check if the file is in gpx 1.0 format and convert it to gpx 1.1 if necessary if (isGPX10) { gpx10convertedFileName = Path.GetTempFileName(); GPXUtil.ConvertGPX10ToGPX11(fileName, gpx10convertedFileName); fileName = gpx10convertedFileName; } // check if the file is an invalid Polar ProTrainer file and correct if necessary if (PolarProTrainerUtil.IsPolarProTrainerGPXFile(fileName)) { polarConvertedFileName = Path.GetTempFileName(); PolarProTrainerUtil.CorrectPolarProTrainerGPXFile(fileName, polarConvertedFileName); fileName = polarConvertedFileName; } var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." }; var sr = new XmlTextReader(fileName); var xSerializer = new XmlSerializer(typeof(gpx11Type)); var gpx11 = (gpx11Type)xSerializer.Deserialize(sr); sr.Close(); var nsManager = new XmlNamespaceManager(sr.NameTable); // add namespace for split times and heart rates (from SportsTracks software) nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); // add namespace for map reading information (QuickRoute native) nsManager.AddNamespace("mr", "http://www.matstroeng.se/quickroute/map-reading"); // pre-store heart rates in dictionary (if present) var heartRates = new Dictionary<DateTime, double>(); // pre-store map-readings in map reading collection (if present) var mapReadings = new List<DateTime>(); if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:heartRateTrack/st:heartRate[@time and @bpm]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { DateTime time; double bpm; if (DateTime.TryParse(node.Attributes["time"].Value, out time) && double.TryParse(node.Attributes["bpm"].Value, NumberStyles.Any, nfi, out bpm)) { time = time.ToUniversalTime(); if(!heartRates.ContainsKey(time)) heartRates.Add(time, bpm); } } } } if(element.Name == "mr:map-reading") { DateTime start, end; if (DateTime.TryParse(element.Attributes["start"].Value, out start) && DateTime.TryParse(element.Attributes["end"].Value, out end)) { mapReadings.Add(start.ToUniversalTime()); mapReadings.Add(end.ToUniversalTime()); } } } } mapReadings = FilterMapReadings(mapReadings); // QuickRoute route var noOfWaypoints = 0; var noOfWaypointsWithTimes = 0; var routeSegments = new List<RouteSegment>(); // first use GPX track if (gpx11.trk != null) { foreach (var trk in gpx11.trk) { foreach (var trkseg in trk.trkseg) { var routeSegment = new RouteSegment(); wptType lastWpt = null; if (trkseg.trkpt != null) { foreach (var wpt in trkseg.trkpt) { if (lastWpt == null || wpt.time != lastWpt.time) { if (wpt.extensions != null && wpt.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double)wpt.lat; var lon = (double)wpt.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(wpt.time)) heartRate = heartRates[wpt.time]; if (wpt.eleSpecified) { altitude = (double?)wpt.ele; } if (wpt.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(wpt.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; lastWpt = wpt; } } noOfWaypoints++; } } } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } } // if no GPX track - use GPX route if (noOfWaypointsWithTimes == 0 && gpx11.rte != null) { foreach (var route in gpx11.rte) { var routeSegment = new RouteSegment(); foreach (var rtept in route.rtept) { if (rtept.extensions != null && rtept.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double) rtept.lat; var lon = (double) rtept.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(rtept.time)) heartRate = heartRates[rtept.time]; if (rtept.eleSpecified) { altitude = (double?) rtept.ele; } if (rtept.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(rtept.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; } } noOfWaypoints++; } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } // add map reading waypoints routeSegments = Route.AddMapReadingWaypoints(routeSegments, mapReadings); importResult.Succeeded = (noOfWaypointsWithTimes > 0); if (ImportResult.Succeeded) { importResult.Route = new Route(routeSegments); // laps var laps = new LapCollection(); var startTime = ImportResult.Route.FirstWaypoint.Time; // from GPX st:split if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:splits/st:split[@time]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { var elapsedTime = double.Parse(node.Attributes["time"].Value, nfi); var lap = new Lap(startTime.AddSeconds(elapsedTime), LapType.Lap); laps.Add(lap); } } } } } // from GPX waypoints if (gpx11.wpt != null && laps.Count == 0) { foreach (var waypoint in gpx11.wpt) { if (waypoint.timeSpecified) { laps.Add(new Lap(waypoint.time, LapType.Lap)); } } } foreach (var rs in routeSegments) { laps.Add(new Lap(rs.FirstWaypoint.Time, LapType.Start)); laps.Add(new Lap(rs.LastWaypoint.Time, LapType.Stop)); } importResult.Laps = laps; } else { if (noOfWaypoints == 0) { importResult.Error = ImportError.NoWaypoints; } else if (noOfWaypointsWithTimes == 0) { importResult.Error = ImportError.NoWaypointTimes; } } if (gpx10convertedFileName != null) { File.Delete(gpx10convertedFileName); fileName = originalFileName; } if (polarConvertedFileName != null) { File.Delete(polarConvertedFileName); fileName = originalFileName; } // import Polar HRM file with same base file name as the gpx file, if existing string hrmFileName = new FileInfo(fileName).FullName.Replace(new FileInfo(fileName).Extension, ".hrm"); if(File.Exists(hrmFileName)) { new PolarHRMImporter().AddLapsAndHRData(hrmFileName, importResult); } if (EndWork != null) EndWork(this, new EventArgs()); }
private void ImportResultsToFile(ImportResult result) { Serializer.WriteToFile(result.Ignored, IGNORED_ITEMS_FILENAME); Serializer.WriteToFile(result.Failed, FAILED_ITEMS_FILENAME); Serializer.WriteToFile(result.Imported, IMPORTED_ITEMS_FILENAME); }
protected ImportResult ImportSeb (string contents) { string patternRows = @"<tr class=""[a-z]+?"">\s*<td style=""white-space: nowrap;"">(?<datetime>[0-9\-]+)</td>\s*<td style=""white-space: nowrap;"">[0-9\-]+</td>\s*<td>(?<transactionid>.+?)</td>\s*<td>(?<comment>.*?)</td>\s*<td class=""numeric"">(?<linkdummy><a href="".*?"">)?.*?(?<amount>[0-9\.,\-]+).*?</td>\s*<td class=""numeric"">(?<balance>[0-9\.,\-]+)</td>\s*</tr>"; string patternBalance = @"<tbody>\s*<tr class=""[a-z]+"">\s*<td>[0-9\s]+</td>\s*<td class=""numeric"">(?<balance>[0-9\.\-,]+)</td>\s*<td class=""numeric"">[0-9\.\-,]+</td>\s*<td class=""numeric"">[0-9\.\-,]+</td>\s*</tr>\s*</tbody>"; List<ImportedRow> rows = new List<ImportedRow>(); ImportResult result = new ImportResult(); Regex regexBalance = new Regex(patternBalance, RegexOptions.Singleline); Regex regexRows = new Regex(patternRows, RegexOptions.Singleline | RegexOptions.Compiled); Match matchBalance = regexBalance.Match(contents); if (!matchBalance.Success) { throw new ArgumentException("Unable to find balance"); } string stringBalance = matchBalance.Groups["balance"].Value.Replace(".", "").Replace(",", "."); result.CurrentBalance = Double.Parse(stringBalance, CultureInfo.InvariantCulture); Match matchRow = regexRows.Match(contents); while (matchRow.Success) { string amountString = matchRow.Groups["amount"].Value; amountString = amountString.Replace(".", "").Replace(",", ""); ImportedRow row = new ImportedRow(); row.DateTime = DateTime.Parse(matchRow.Groups["datetime"].Value); row.Comment = StripHtml(matchRow.Groups["comment"].Value); row.CurrentBalance = Double.Parse(matchRow.Groups["balance"].Value.Replace(".", "").Replace(",", "."), CultureInfo.InvariantCulture); row.AmountCentsNet = Int64.Parse(amountString); row.HashBase = matchRow.Groups["transactionid"].Value; rows.Add(row); matchRow = matchRow.NextMatch(); } result.Rows = rows; if (rows.Count < 20 && rows.Count > 0) { // A serious error has occurred. Dev assistance is necessary. Person.FromIdentity(1).SendNotice("Contents for bank parsing (I see " + rows.Count.ToString() + " rows)", contents, 1); Person.FromIdentity(1).SendPhoneMessage("Bank import failed - " + rows.Count.ToString() + " rows parsed - see mail"); throw new ArgumentException("PirateWeb is unable to parse the page. Developer assistance has been called in."); } return result; }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) { BeginWork(this, new EventArgs()); } XmlTextReader reader = new XmlTextReader(FileName); XPathDocument doc = new XPathDocument(reader); XPathNavigator nav = doc.CreateNavigator(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nav.NameTable); nsManager.AddNamespace("ns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"); XPathNodeIterator activities = nav.Select("//ns:Activity", nsManager); while (activities.MoveNext()) { XPathNavigator id = activities.Current.SelectSingleNode("ns:Id", nsManager); if (id != null && DateTime.Parse(id.Value).ToString("yyyy-MM-dd HH:mm:ss") == IdToImport) { // the activity was found // the laps XPathNodeIterator lapNodes = activities.Current.Select("ns:Lap", nsManager); List <RouteSegment> routeSegments = new List <RouteSegment>(); RouteSegment routeSegment = new RouteSegment(); while (lapNodes.MoveNext()) { // the tracks XPathNodeIterator trackNodes = lapNodes.Current.Select("ns:Track", nsManager); int trackCount = 0; while (trackNodes.MoveNext()) { if (trackCount > 0) { if (routeSegment.Waypoints.Count > 1) { routeSegments.Add(routeSegment); } routeSegment = new RouteSegment(); } XPathNodeIterator trackpointNodes = trackNodes.Current.Select("ns:Trackpoint", nsManager); DateTime lastTime = DateTime.MinValue; LongLat lastLongLat = null; int trackpointCount = 0; while (trackpointNodes.MoveNext()) { Waypoint waypoint = new Waypoint(); waypoint.Time = DateTime.Parse(trackpointNodes.Current.SelectSingleNode("ns:Time", nsManager).Value).ToUniversalTime(); XPathNavigator position = trackpointNodes.Current.SelectSingleNode("ns:Position", nsManager); if (position != null) { waypoint.LongLat = new LongLat( position.SelectSingleNode("ns:LongitudeDegrees", nsManager).ValueAsDouble, position.SelectSingleNode("ns:LatitudeDegrees", nsManager).ValueAsDouble); } if (trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager) != null) { waypoint.Altitude = trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager).ValueAsDouble; } if (trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager) != null) { waypoint.HeartRate = trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager).ValueAsDouble; } // do not add waypoint if it has the same location or time as the previous one if (waypoint.LongLat != null && !waypoint.LongLat.Equals(lastLongLat) && waypoint.Time != lastTime) { // special handling for positionless trackpoint in the beginning, use its time together with next position if (trackpointCount == 1 && lastLongLat == null && routeSegment.Waypoints.Count == 0) { waypoint.Time = lastTime; } routeSegment.Waypoints.Add(waypoint); } lastLongLat = waypoint.LongLat; lastTime = waypoint.Time; trackpointCount++; } if (lastLongLat == null && routeSegment.Waypoints.Count > 1) { // special handling for positionless trackpoint in the end, use its time together with previous position routeSegment.Waypoints[routeSegment.Waypoints.Count - 1].Time = lastTime; } trackCount++; } } // add last route segment if (routeSegment.Waypoints.Count > 1) { routeSegments.Add(routeSegment); } // set position of all start and end waypoints of the route segments if they are null foreach (RouteSegment rs in routeSegments) { if (rs.FirstWaypoint.LongLat == null && rs.Waypoints.Count > 1) { rs.Waypoints[1] = rs.Waypoints[1].Clone(); } if (rs.LastWaypoint.LongLat == null && rs.Waypoints.Count > 1) { rs.Waypoints[rs.Waypoints.Count - 1] = rs.Waypoints[rs.Waypoints.Count - 2].Clone(); } } // the laps lapNodes = activities.Current.Select("ns:Lap", nsManager); // first store all elapsed times List <double> elapsedTimes = new List <double>(); LapCollection laps = new LapCollection(); if (lapNodes.MoveNext()) { DateTime startTime = DateTime.Parse(lapNodes.Current.GetAttribute("StartTime", "")); double elapsedTime = 0; do { elapsedTimes.Add(elapsedTime); elapsedTime += lapNodes.Current.SelectSingleNode("ns:TotalTimeSeconds", nsManager).ValueAsDouble; } while (lapNodes.MoveNext()); laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments); } importResult.Route = new Route(routeSegments); importResult.Laps = laps; importResult.Succeeded = importResult.Route.Segments.Count > 0; if (importResult.Route.Segments.Count == 0) { importResult.Error = ImportError.NoWaypoints; } break; } } reader.Close(); if (EndWork != null) { EndWork(this, new EventArgs()); } }
public virtual void Import() { //根据视图名读取ExcelConfig信息。 MDataRow excelInfo = null; int index = 0, headCrossRowNum = 0; string sheetName = null; try { excelInfo = ExcelConfig.GetExcelRow(ObjName); if (excelInfo != null) { index = excelInfo.Get <int>(Config_Excel.StartIndex, 0); headCrossRowNum = excelInfo.Get <int>(Config_Excel.HeadCrossRowNum, 0); sheetName = excelInfo.Get <string>(Config_Excel.Description); } } catch (Exception err) { Log.WriteLogToTxt(err);//避免其它地方没有升级数据库表脚本。 } MDataTable dt = ExcelHelper.ReadExcel(null, sheetName, index, headCrossRowNum, excelInfo != null); if (!dt.Columns.Contains(LangConst.ErrorInfo)) { dt.Columns.Add(LangConst.ErrorInfo, System.Data.SqlDbType.NVarChar); } dt.TableName = excelInfo != null ? ObjName : TableName; bool result = false; string msg = string.Empty; ImportResult iResult = BeforeImport(dt, excelInfo, out msg); if (iResult == ImportResult.Continue) { result = FormatExcel(dt, excelInfo); if (result) { dt.Columns.Remove(LangConst.ErrorInfo); result = ExcelConfig.AcceptChanges(dt, excelInfo, ObjName);// dt.AcceptChanges(AcceptOp.Auto); } } else { result = iResult == ImportResult.True; } if (!result) { if (dt.DynamicData != null && dt.DynamicData is Exception) { msg = ((Exception)dt.DynamicData).Message; msg += LangConst.ImportTemplateNotMatch; } if (excelStream == null) { excelStream = ExcelHelper.SetError(dt); } if (string.IsNullOrEmpty(msg)) { msg = LangConst.ImportError + (excelStream != null ? LangConst.ImportCheckErrorInfo : LangConst.ImportCheckTemplateIsRight); } } else if (string.IsNullOrEmpty(msg)) { msg = LangConst.ImportSuccess; } dt.DynamicData = null; dt = null; GC.Collect(); jsonResult = JsonHelper.OutResult(result, msg); }
private int ProcessProductManufacturers(ICollection <ImportRow <Product> > batch, ImportResult result) { _rsProductManufacturer.AutoCommitEnabled = false; ProductManufacturer lastInserted = null; foreach (var row in batch) { string manufacturerIds = row.GetValue <string>("ManufacturerIds"); if (manufacturerIds.HasValue()) { try { foreach (var id in manufacturerIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (_rsProductManufacturer.TableUntracked.Where(x => x.ProductId == row.Entity.Id && x.ManufacturerId == id).FirstOrDefault() == null) { // ensure that manufacturer exists var manufacturer = _manufacturerService.GetManufacturerById(id); if (manufacturer != null) { var productManufacturer = new ProductManufacturer() { ProductId = row.Entity.Id, ManufacturerId = manufacturer.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _rsProductManufacturer.Insert(productManufacturer); lastInserted = productManufacturer; } } } } catch (Exception ex) { result.AddWarning(ex.Message, row.GetRowInfo(), "ManufacturerIds"); } } } // commit whole batch at once var num = _rsProductManufacturer.Context.SaveChanges(); // Perf: notify only about LAST insertion and update if (lastInserted != null) { _eventPublisher.EntityInserted(lastInserted); } return(num); }
/// <summary> /// Funzione per la restituzione del report /// </summary> /// <returns></returns> public ResultsContainer GetReport() { // Viene risvegliato il thread //waitReading.Set(); // Numero di documenti non importati ed importati con // warning int importedWithWarningOrNotImported = 0; // Calcolo del numero di documenti importati con warning importedWithWarningOrNotImported += this.report.Attachment != null? this.report.Attachment.Where(e => e.Outcome == OutcomeEnumeration.Warnings || e.Outcome == OutcomeEnumeration.KO).Count() : 0; importedWithWarningOrNotImported += this.report.GrayDocument != null? this.report.GrayDocument.Where(e => e.Outcome == OutcomeEnumeration.Warnings || e.Outcome == OutcomeEnumeration.KO).Count() : 0; importedWithWarningOrNotImported += this.report.InDocument != null? this.report.InDocument.Where(e => e.Outcome == OutcomeEnumeration.Warnings || e.Outcome == OutcomeEnumeration.KO).Count() : 0; importedWithWarningOrNotImported += this.report.OutDocument != null? this.report.OutDocument.Where(e => e.Outcome == OutcomeEnumeration.Warnings || e.Outcome == OutcomeEnumeration.KO).Count() : 0; importedWithWarningOrNotImported += this.report.OwnDocument != null? this.report.OwnDocument.Where(e => e.Outcome == OutcomeEnumeration.Warnings || e.Outcome == OutcomeEnumeration.KO).Count() : 0; ImportResult importResult = new ImportResult(); // Aggiunta di un messaggio nel report generale // Se non ci sono documenti importati con warning o non importati, // viene aggiunto un messaggio positivo altrimenti viene aggiunto un // messaggio di warning if (this.totalNumberOfDocumentToImport == 0) { importResult.Outcome = OutcomeEnumeration.Warnings; importResult.Message = "Non è stato rilevato nessun documento da importare."; } else if (importedWithWarningOrNotImported == 0) { importResult.Message = "Nessun messaggio generale da mostrare."; } else { importResult.Message = String.Format("Attenzione! {0} documenti hanno presentato problemi durante l'importazione. Controllare gli altri tab per maggiori informazioni.", importedWithWarningOrNotImported); importResult.Outcome = OutcomeEnumeration.KO; } this.report.General = new ImportResult[] { importResult }; // Viene restituito il report return(this.report); }
public async Task <ImportResult> Import(DocumentsOperationContext context, Stream stream, Action <IOperationProgress> onProgress = null) { var result = new ImportResult(); var progress = new IndeterminateProgress(); var state = new JsonParserState(); JsonOperationContext.ManagedPinnedBuffer buffer; using (context.GetManagedBuffer(out buffer)) using (var parser = new UnmanagedJsonParser(context, state, "fileName")) { var operateOnType = "__top_start_object"; var buildVersion = 0L; var identities = new Dictionary <string, long>(); VersioningStorage versioningStorage = null; while (true) { if (parser.Read() == false) { var read = await stream.ReadAsync(buffer.Buffer.Array, buffer.Buffer.Offset, buffer.Length); if (read == 0) { if (state.CurrentTokenType != JsonParserToken.EndObject) { throw new EndOfStreamException("Stream ended without reaching end of json content"); } break; } parser.SetBuffer(buffer, read); continue; } switch (state.CurrentTokenType) { case JsonParserToken.String: unsafe { operateOnType = new LazyStringValue(null, state.StringBuffer, state.StringSize, context).ToString(); } break; case JsonParserToken.Integer: switch (operateOnType) { case "BuildVersion": buildVersion = state.Long; break; } break; case JsonParserToken.StartObject: if (operateOnType == "__top_start_object") { operateOnType = null; break; } context.CachedProperties.NewDocument(); var builder = new BlittableJsonDocumentBuilder(_batchPutCommand.Context, BlittableJsonDocumentBuilder.UsageMode.ToDisk, "ImportObject", parser, state); builder.ReadNestedObject(); while (builder.Read() == false) { var read = await stream.ReadAsync(buffer.Buffer.Array, buffer.Buffer.Offset, buffer.Length); if (read == 0) { throw new EndOfStreamException("Stream ended without reaching end of json content"); } parser.SetBuffer(buffer, read); } builder.FinalizeDocument(); if (operateOnType == "Docs" && Options.OperateOnTypes.HasFlag(DatabaseItemType.Documents)) { progress.Progress = "Importing Documents"; onProgress?.Invoke(progress); PatchDocument patch = null; PatchRequest patchRequest = null; if (string.IsNullOrWhiteSpace(Options.TransformScript) == false) { patch = new PatchDocument(context.DocumentDatabase); patchRequest = new PatchRequest { Script = Options.TransformScript }; } result.DocumentsCount++; var reader = builder.CreateReader(); var document = new Document { Data = reader, }; if (Options.IncludeExpired == false && document.Expired(_database.Time.GetUtcNow())) { continue; } TransformScriptOrDisableVersioningIfNeeded(context, patch, reader, document, patchRequest); _batchPutCommand.Add(document.Data); if (result.DocumentsCount % 1000 == 0) { progress.Progress = $"Imported {result.DocumentsCount} documents"; onProgress?.Invoke(progress); } await HandleBatchOfDocuments(context, parser, buildVersion).ConfigureAwait(false); } else if (operateOnType == "RevisionDocuments" && Options.OperateOnTypes.HasFlag(DatabaseItemType.RevisionDocuments)) { if (versioningStorage == null) { break; } result.RevisionDocumentsCount++; var reader = builder.CreateReader(); _batchPutCommand.Add(reader); await HandleBatchOfDocuments(context, parser, buildVersion).ConfigureAwait(false);; } else { using (builder) { switch (operateOnType) { case "Attachments": result.Warnings.Add("Attachments are not supported anymore. Use RavenFS isntead. Skipping."); break; case "Indexes": if (Options.OperateOnTypes.HasFlag(DatabaseItemType.Indexes) == false) { continue; } result.IndexesCount++; progress.Progress = "importing Indexes"; onProgress?.Invoke(progress); try { IndexProcessor.Import(builder, _database, buildVersion, Options.RemoveAnalyzers); } catch (Exception e) { result.Warnings.Add($"Could not import index. Message: {e.Message}"); } break; case "Transformers": if (Options.OperateOnTypes.HasFlag(DatabaseItemType.Transformers) == false) { continue; } result.TransformersCount++; progress.Progress = "Importing Transformers"; onProgress?.Invoke(progress); try { TransformerProcessor.Import(builder, _database, buildVersion); } catch (Exception e) { result.Warnings.Add($"Could not import transformer. Message: {e.Message}"); } break; case "Identities": if (Options.OperateOnTypes.HasFlag(DatabaseItemType.Identities)) { result.IdentitiesCount++; progress.Progress = "Importing Identities"; onProgress?.Invoke(progress); using (var reader = builder.CreateReader()) { try { string identityKey, identityValueString; long identityValue; if (reader.TryGet("Key", out identityKey) == false || reader.TryGet("Value", out identityValueString) == false || long.TryParse(identityValueString, out identityValue) == false) { result.Warnings.Add($"Cannot import the following identity: '{reader}'. Skipping."); } else { identities[identityKey] = identityValue; } } catch (Exception e) { result.Warnings.Add($"Cannot import the following identity: '{reader}'. Error: {e}. Skipping."); } } } break; default: result.Warnings.Add( $"The following type is not recognized: '{operateOnType}'. Skipping."); break; } } } break; case JsonParserToken.StartArray: switch (operateOnType) { case "RevisionDocuments": // We are taking a reference here since the documents import can activate or disable the versioning. // We hold a local copy because the user can disable the bundle during the import process, exteranly. // In this case we want to continue to import the revisions documents. versioningStorage = _database.BundleLoader.VersioningStorage; _batchPutCommand.IsRevision = true; break; } break; case JsonParserToken.EndArray: switch (operateOnType) { case "Docs": await FinishBatchOfDocuments(); _batchPutCommand = new MergedBatchPutCommand(_database, buildVersion); break; case "RevisionDocuments": await FinishBatchOfDocuments(); break; case "Identities": if (identities.Count > 0) { using (var tx = context.OpenWriteTransaction()) { _database.DocumentsStorage.UpdateIdentities(context, identities); tx.Commit(); } } identities = null; break; } break; } } } return(result); }
private void InitializeHandlers() { OutputErrorLog = (path, errorInfo, sourceFilePath) => { var exists = File.Exists(path); using (var stream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read)) using (var writer = new StreamWriter(stream, Encoding.GetEncoding(932))) { if (exists) { writer.WriteLine(); } var now = DateTime.Now; writer.WriteLine($"{now:yyyy年MM月dd日 HH時mm分ss秒}"); writer.WriteLine($"得意先データ:{Path.GetFileName(sourceFilePath)}"); foreach (var error in errorInfo) { writer.WriteLine(error); } } }; ImportCustomerAsync = async(InsertList, UpdateList, DeleteList) => { ImportResult result = null; try { await ServiceProxyFactory.DoAsync <CustomerMasterClient>(async client => result = await client.ImportAsync(SessionKey, InsertList.ToArray(), UpdateList.ToArray(), DeleteList.ToArray())); } catch (Exception ex) { Debug.Fail(ex.ToString()); NLogHandler.WriteErrorLog(this, ex, SessionKey); } return(result ?? new ImportResult()); }; GetCollectCategoryAsync = async() => await ServiceProxyFactory.DoAsync(async (CategoryMasterClient client) => { var result = await client.GetItemsAsync(SessionKey, new CategorySearch { CompanyId = CompanyId, CategoryType = CollectCategoryType, }); if (result.ProcessResult.Result) { return(result.Categories); } return(new List <Category>()); }); GetStaffAsync = async() => await ServiceProxyFactory.DoAsync(async (StaffMasterClient client) => { var result = await client.GetItemsAsync(SessionKey, new StaffSearch { CompanyId = CompanyId }); if (result.ProcessResult.Result) { return(result.Staffs); } return(new List <Staff>()); }); GetCustomerAsync = async() => await ServiceProxyFactory.DoAsync(async (CustomerMasterClient client) => { var result = await client.GetItemsAsync(SessionKey, CompanyId, new CustomerSearch { CompanyId = CompanyId }); if (result.ProcessResult.Result) { return(result.Customers); } return(new List <Customer>()); }); GetLeagalPersonaritiesAsync = async() => await ServiceProxyFactory.DoAsync(async (JuridicalPersonalityMasterClient client) => { var result = await client.GetItemsAsync(SessionKey, CompanyId); if (result.ProcessResult.Result) { return(result.JuridicalPersonalities.Select(x => x.Kana)); } return(Enumerable.Empty <string>()); }); GetImporterSettingAsync = async(int formatId, string code) => await ServiceProxyFactory.DoAsync(async (ImporterSettingServiceClient client) => { var result = await client.GetHeaderByCodeAsync(SessionKey, CompanyId, formatId, code); if (result.ProcessResult.Result) { return(result.ImporterSetting); } return(null); }); GetImporterSettingDetailAsync = async(int formatId, string code) => await ServiceProxyFactory.DoAsync(async (ImporterSettingServiceClient client) => { var result = await client.GetDetailByCodeAsync(SessionKey, CompanyId, formatId, code); if (result.ProcessResult.Result) { return(result.ImporterSettingDetails); } return(new List <ImporterSettingDetail>()); }); GetRoundingTypeAsync = async() => { var res = await Util.GetGeneralSettingAsync(Login, "取込時端数処理"); if (!Enum.TryParse(res.Value, out roundingType)) { throw new Exception("取込時端数処理"); } return(roundingType); }; GetMasterDataForCustomerGroupParentAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForCustomerGroupParentAsync(SessionKey, CompanyId, codes)); GetMasterDataForCustomerGroupChildAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForCustomerGroupChildAsync(SessionKey, CompanyId, codes)); GetMasterDataForKanaHistoryAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForKanaHistoryAsync(SessionKey, CompanyId, codes)); GetMasterDataForBillingAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForBillingAsync(SessionKey, CompanyId, codes)); GetMasterDataForReceiptAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForReceiptAsync(SessionKey, CompanyId, codes)); GetMasterDataForNettingAsync = async(string[] codes) => await GetMasterDataAsync(async client => await client.GetImportItemsForNettingAsync(SessionKey, CompanyId, codes)); LogError = ex => NLogHandler.WriteErrorLog(this, ex, SessionKey); }
public void Import() { //根据视图名读取ExcelConfig信息。 MDataRow excelInfo = null; int index = 0, headCrossRowNum = 0; string sheetName = null; try { excelInfo = ExcelConfig.GetExcelRow(ObjName); if (excelInfo != null) { index = excelInfo.Get <int>(Config_Excel.StartIndex, 0); headCrossRowNum = excelInfo.Get <int>(Config_Excel.HeadCrossRowNum, 0); sheetName = excelInfo.Get <string>(Config_Excel.Description); } } catch (Exception err) { Log.WriteLogToTxt(err);//避免其它地方没有升级数据库表脚本。 } MDataTable dt = ExcelHelper.ReadExcel(null, sheetName, index, headCrossRowNum, excelInfo != null); if (!dt.Columns.Contains("错误信息")) { dt.Columns.Add("错误信息", System.Data.SqlDbType.NVarChar); } dt.TableName = excelInfo != null ? ObjName : TableName; bool result = false; string msg = string.Empty; ImportResult iResult = BeforeImport(dt, excelInfo, out msg); if (iResult == ImportResult.Continue) { result = FormatExcel(dt, excelInfo); if (result) { result = ExcelConfig.AcceptChanges(dt, excelInfo, ObjName);// dt.AcceptChanges(AcceptOp.Auto); } } else { result = iResult == ImportResult.True; } if (!result) { if (dt.DynamicData != null && dt.DynamicData is Exception) { msg = ((Exception)dt.DynamicData).Message; msg += "(PS:可能模板不匹配)"; } if (excelStream == null) { excelStream = ExcelHelper.SetError(dt); } if (string.IsNullOrEmpty(msg)) { msg = "导入失败" + (excelStream != null ? "(请查看输出的Excel错误信息)" : "(请检测是否模板错误)"); } } else if (string.IsNullOrEmpty(msg)) { msg = "导入成功"; } dt.DynamicData = null; dt = null; GC.Collect(); jsonResult = JsonHelper.OutResult(result, msg); }
public async Task <IActionResult> Reimport(Guid commissionStatementId, [FromQuery] Guid commissionStatementTemplateId, [FromQuery] Guid?userId) { var scope = AuthenticationService.GetScope(User); var statement = await CommissionStatementService.GetCommissionStatement(scope, commissionStatementId); if (statement == null) { return(NotFound()); } var path = new CommissionStatementDirectoryPath(scope.OrganisationId, commissionStatementId); var fileInfoList = await FileStorageService.GetFileInfoListAsync(path); if (!fileInfoList.Any()) { return(this.BadRequestMessage("Reimport failed as there are no existing statement files.")); } var queryOptions = new CommissionStatementTemplateQueryOptions("", "", 0, 0); queryOptions.CompanyId.Add(statement.CompanyId.Value); queryOptions.Date = statement.Date; var templates = (await CommissionStatementTemplateService.GetTemplates(queryOptions)).Items; if (!templates.Any(t => t.Id == commissionStatementTemplateId)) { return(this.BadRequestMessage("Reimport failed as the commissionStatementTemplateId is not valid.")); } var template = await CommissionStatementTemplateService.GetTemplate(commissionStatementTemplateId); string brokerFullName = null; if (template.BrokerSpecific) { if (!userId.HasValue) { return(this.BadRequestMessage("UserId required for broker specific templates.")); } var user = await UserService.GetUser(scope, userId.Value); if (user == null) { return(this.BadRequestMessage("Invalid UserId.")); } brokerFullName = $"{user.FirstName} {user.LastName}"; } await CommissionStatementService.DeleteCommissions(scope, commissionStatementId); var result = new ImportResult(); foreach (var fileInfo in fileInfoList) { using (var stream = new MemoryStream()) { await FileStorageService.GetFile(fileInfo.Url, stream); var vatRate = await DirectoryLookupService.GetVATRate(statement.Date ?? DateTime.Now); var reader = new CommissionImportReader(template.Config, vatRate, brokerFullName); var items = reader.Read(stream); result = await CommissionImportService.ImportCommissions(scope, commissionStatementId, items); if (result.UnknownCommissionTypeValues.Any()) { stream.Position = 0; using (var copy = new MemoryStream()) { await stream.CopyToAsync(copy); copy.Position = 0; var attachment = GetEmailAttachmentFromCloud(fileInfo, copy); await SendUnkownCommissionTypesEmail(result, scope, commissionStatementId, template, attachment); } } if (!result.Results.Any(r => r.Success)) { stream.Position = 0; using (var copy = new MemoryStream()) { await stream.CopyToAsync(copy); copy.Position = 0; var attachment = GetEmailAttachmentFromCloud(fileInfo, copy); await SendZeroEntriesEmail(scope, commissionStatementId, template, attachment); } } } } return(Ok(result)); }
public void Constructor_DefaultsImportedFilesToEmptyArray() { var result = new ImportResult(); Assert.IsEmpty(result.Files); }
public async Task <IActionResult> Import(Guid commissionStatementId, [FromQuery] Guid commissionStatementTemplateId, [FromQuery] Guid?userId) { var scope = AuthenticationService.GetScope(User); var file = Request.Form.Files.FirstOrDefault(); if (file == null) { return(BadRequest()); } var statement = await CommissionStatementService.GetCommissionStatement(scope, commissionStatementId); var template = await CommissionStatementTemplateService.GetTemplate(commissionStatementTemplateId); string brokerFullName = null; if (template.BrokerSpecific) { if (!userId.HasValue) { return(this.BadRequestMessage("UserId required for broker specific templates.")); } var user = await UserService.GetUser(scope, userId.Value); if (user == null) { return(this.BadRequestMessage("Invalid UserId.")); } brokerFullName = $"{user.FirstName} {user.LastName}"; } var config = template.Config; var result = new ImportResult(); using (var stream = file.OpenReadStream()) { var vatRate = await DirectoryLookupService.GetVATRate(statement.Date ?? DateTime.Now); var reader = new CommissionImportReader(config, vatRate, brokerFullName); var items = reader.Read(stream); result = await CommissionImportService.ImportCommissions(scope, commissionStatementId, items); } if (result.UnknownCommissionTypeValues.Any()) { using (var stream = file.OpenReadStream()) { var attachment = GetEmailAttachment(file, stream); await SendUnkownCommissionTypesEmail(result, scope, commissionStatementId, template, attachment); } } if (!result.Results.Any(r => r.Success)) { using (var stream = file.OpenReadStream()) { var attachment = GetEmailAttachment(file, stream); await SendZeroEntriesEmail(scope, commissionStatementId, template, attachment); } } if (result.Results.Any()) { using (var stream = file.OpenReadStream()) { var path = new CommissionStatementFilePath(scope.OrganisationId, commissionStatementId, file.FileName); await FileStorageService.AddFileAsync(path, stream); } } return(Ok(result)); }
public void Import() { ImportResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); try { using (var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { var header = new Header(reader); var data = new Data(reader, header.DataSize); // route var routeSegment = new RouteSegment(); foreach(var w in data.Waypoints) { if(routeSegment.Waypoints.Count == 0 || routeSegment.LastWaypoint.Time < w.Time) { routeSegment.Waypoints.Add(new Waypoint(w.Time, new LongLat(w.Longitude, w.Latitude), w.Altitude, w.HeartRate, null, w.Cadence, w.Power)); } } ImportResult.Route = new Route(new List<RouteSegment>() { routeSegment }); // laps if (routeSegment.Waypoints.Count > 1) { ImportResult.Laps = new LapCollection(); ImportResult.Laps.Add(new Lap(routeSegment.FirstWaypoint.Time, LapType.Start)); foreach (var l in data.Laps) { if (l.Time > routeSegment.FirstWaypoint.Time && l.Time < routeSegment.LastWaypoint.Time) ImportResult.Laps.Add(new Lap(l.Time, LapType.Lap)); } ImportResult.Laps.Add(new Lap(routeSegment.LastWaypoint.Time, LapType.Stop)); } ImportResult.Succeeded = true; } } } catch (Exception ex) { ImportResult.Exception = ex; } if (EndWork != null) EndWork(this, new EventArgs()); }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); XmlTextReader reader = new XmlTextReader(FileName); XPathDocument doc = new XPathDocument(reader); XPathNavigator nav = doc.CreateNavigator(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nav.NameTable); nsManager.AddNamespace("ns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"); XPathNodeIterator activities = nav.Select("//ns:Activity", nsManager); while (activities.MoveNext()) { XPathNavigator id = activities.Current.SelectSingleNode("ns:Id", nsManager); if (id != null && DateTime.Parse(id.Value).ToString("yyyy-MM-dd HH:mm:ss") == IdToImport) { // the activity was found // the laps XPathNodeIterator lapNodes = activities.Current.Select("ns:Lap", nsManager); List<RouteSegment> routeSegments = new List<RouteSegment>(); RouteSegment routeSegment = new RouteSegment(); while (lapNodes.MoveNext()) { // the tracks XPathNodeIterator trackNodes = lapNodes.Current.Select("ns:Track", nsManager); int trackCount = 0; while (trackNodes.MoveNext()) { if (trackCount > 0) { if (routeSegment.Waypoints.Count > 1) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } XPathNodeIterator trackpointNodes = trackNodes.Current.Select("ns:Trackpoint", nsManager); DateTime lastTime = DateTime.MinValue; LongLat lastLongLat = null; int trackpointCount = 0; while (trackpointNodes.MoveNext()) { Waypoint waypoint = new Waypoint(); waypoint.Time = DateTime.Parse(trackpointNodes.Current.SelectSingleNode("ns:Time", nsManager).Value).ToUniversalTime(); XPathNavigator position = trackpointNodes.Current.SelectSingleNode("ns:Position", nsManager); if (position != null) { waypoint.LongLat = new LongLat( position.SelectSingleNode("ns:LongitudeDegrees", nsManager).ValueAsDouble, position.SelectSingleNode("ns:LatitudeDegrees", nsManager).ValueAsDouble); } if (trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager) != null) { waypoint.Altitude = trackpointNodes.Current.SelectSingleNode("ns:AltitudeMeters", nsManager).ValueAsDouble; } if (trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager) != null) { waypoint.HeartRate = trackpointNodes.Current.SelectSingleNode("ns:HeartRateBpm/ns:Value", nsManager).ValueAsDouble; } if (waypoint.HeartRate == null && routeSegment.LastWaypoint != null) { // sometimes heart rates are only present at some nodes, so use last valid heart rate waypoint.HeartRate = routeSegment.LastWaypoint.HeartRate; } // do not add waypoint if it has the same location or time as the previous one if (waypoint.LongLat != null && !waypoint.LongLat.Equals(lastLongLat) && waypoint.Time != lastTime) { // special handling for positionless trackpoint in the beginning, use its time together with next position if (trackpointCount == 1 && lastLongLat == null && routeSegment.Waypoints.Count == 0) waypoint.Time = lastTime; routeSegment.Waypoints.Add(waypoint); } lastLongLat = waypoint.LongLat; lastTime = waypoint.Time; trackpointCount++; } if (lastLongLat == null && routeSegment.Waypoints.Count > 1) { // special handling for positionless trackpoint in the end, use its time together with previous position routeSegment.Waypoints[routeSegment.Waypoints.Count - 1].Time = lastTime; } trackCount++; } } // add last route segment if (routeSegment.Waypoints.Count > 1) routeSegments.Add(routeSegment); // set position of all start and end waypoints of the route segments if they are null foreach (RouteSegment rs in routeSegments) { if (rs.FirstWaypoint.LongLat == null && rs.Waypoints.Count > 1) rs.Waypoints[1] = rs.Waypoints[1].Clone(); if (rs.LastWaypoint.LongLat == null && rs.Waypoints.Count > 1) rs.Waypoints[rs.Waypoints.Count - 1] = rs.Waypoints[rs.Waypoints.Count - 2].Clone(); } // the laps lapNodes = activities.Current.Select("ns:Lap", nsManager); // first store all elapsed times List<double> elapsedTimes = new List<double>(); LapCollection laps = new LapCollection(); if (lapNodes.MoveNext()) { DateTime startTime = DateTime.Parse(lapNodes.Current.GetAttribute("StartTime", "")).ToUniversalTime(); double elapsedTime = 0; do { elapsedTimes.Add(elapsedTime); elapsedTime += lapNodes.Current.SelectSingleNode("ns:TotalTimeSeconds", nsManager).ValueAsDouble; } while (lapNodes.MoveNext()); laps = RouteImporterUtil.CreateLapsFromElapsedTimes(startTime, elapsedTimes, routeSegments); } importResult.Route = new Route(routeSegments); importResult.Laps = laps; importResult.Succeeded = importResult.Route.Segments.Count > 0; if(importResult.Route.Segments.Count == 0) importResult.Error = ImportError.NoWaypoints; break; } } reader.Close(); if (EndWork != null) EndWork(this, new EventArgs()); }
public ImportResult Import(Guid account, dynamic rows, bool execute) { List <ReceiptOrPayment> existingPayments = GetPayments(); //List<BankReceipt> existingReceipts=GetReceipts(); ImportResult importResult = new ImportResult { exists = 0, done = 0, failed = 0 }; List <Manager.Model.Object> newObjs = new List <Manager.Model.Object>(); foreach (dynamic row in rows) { Decimal amount; DateTime dateTime = DateTime.Now; if (!Decimal.TryParse(row.Amount, out amount) || !DateTime.TryParse(row.Date, out dateTime) ) { ++importResult.failed; continue; } String description = row.Description; if (hasTransaction(account, existingPayments, dateTime, amount, description) != null) { ++importResult.exists; continue; } Manager.Model.Object mObj; /* * if(amount > 0) { * BankReceipt receipt = new BankReceipt() { * Date = dateTime, * Description = description, * BankAccount=account * }; * //receipt.DebitAccount; * //receipt.Description; * //Amount = 0 - amount; * TransactionLine line = new TransactionLine() { * Amount = amount * }; * receipt.Lines = new TransactionLine[1] { line }; * mObj = receipt; * } else { */ ReceiptOrPayment payment = new ReceiptOrPayment() { Date = dateTime, BankAccount = account, Description = description }; TransactionLine line = new TransactionLine() { Amount = amount }; payment.Lines = new TransactionLine[1] { line }; mObj = payment; mObj.Key = Guid.NewGuid(); newObjs.Add(mObj); ++importResult.done; } PreChangeEvents(); if (execute) { foreach (var obj in newObjs) { InsertObject(obj); } } return(importResult); }
public ImportResult Import(GLTFAccessor.ImportResult[] accessors, GLTFNode.ImportResult[] nodes, ImportSettings importSettings) { ImportResult result = new ImportResult(); result.clip = new AnimationClip(); result.clip.name = name; if (importSettings.useLegacyClips) { result.clip.legacy = true; } for (int i = 0; i < channels.Length; i++) { Channel channel = channels[i]; if (samplers.Length <= channel.sampler) { Debug.LogWarning("Animation channel points to sampler at index " + channel.sampler + " which doesn't exist. Skipping animation clip."); continue; } Sampler sampler = samplers[channel.sampler]; string relativePath = ""; GLTFNode.ImportResult node = nodes[channel.target.node.Value]; while (node != null && !node.IsRoot) { if (string.IsNullOrEmpty(relativePath)) { relativePath = node.transform.name; } else { relativePath = node.transform.name + "/" + relativePath; } if (node.parent.HasValue) { node = nodes[node.parent.Value]; } else { node = null; } } float[] keyframeInput = accessors[sampler.input].ReadFloat().ToArray(); switch (channel.target.path) { case "translation": Vector3[] pos = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve posX = new AnimationCurve(); AnimationCurve posY = new AnimationCurve(); AnimationCurve posZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { posX.AddKey(keyframeInput[k], pos[k].x); posY.AddKey(keyframeInput[k], pos[k].y); posZ.AddKey(keyframeInput[k], -pos[k].z); } result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ); break; case "rotation": Vector4[] rot = accessors[sampler.output].ReadVec4().ToArray(); AnimationCurve rotX = new AnimationCurve(); AnimationCurve rotY = new AnimationCurve(); AnimationCurve rotZ = new AnimationCurve(); AnimationCurve rotW = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { rotX.AddKey(keyframeInput[k], rot[k].x); rotY.AddKey(keyframeInput[k], rot[k].y); rotZ.AddKey(keyframeInput[k], -rot[k].z); rotW.AddKey(keyframeInput[k], -rot[k].w); } result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW); break; case "scale": Vector3[] scale = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve scaleX = new AnimationCurve(); AnimationCurve scaleY = new AnimationCurve(); AnimationCurve scaleZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { scaleX.AddKey(keyframeInput[k], scale[k].x); scaleY.AddKey(keyframeInput[k], scale[k].y); scaleZ.AddKey(keyframeInput[k], scale[k].z); } result.clip.SetCurve(relativePath, typeof(Transform), "localScale.x", scaleX); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.y", scaleY); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.z", scaleZ); break; case "weights": Debug.LogWarning("morph weights in animation is not supported"); break; } } return(result); }
private void ImportShpByMemory(string filePath) { //https://blog.csdn.net/tane_e/article/details/89393493 //https://www.supermap.com/EN/online/Deskpro%206.0/SDMain/html/R_Dataset_Import.htm //https://www.supermap.com/EN/online/Deskpro%206.0/SDTechTheme/ExpressHtml/ImEx_ArcGIS_Shape.htm Workspace workspace = new Workspace(); DatasourceConnectionInfo info = new DatasourceConnectionInfo(); //mysql数据源 //设置数据源连接的引擎类型 info.EngineType = EngineType.MySQL; //设置数据库连接字符串 info.Server = server; info.Database = database; info.User = userName; info.Password = password; info.Driver = driver; info.IsAutoConnect = true; info.Alias = "MySQL"; //不能为空 // 打开数据库数据源 //超图sdk不能直接连接空数据库,需要使用Create方法新建数据库,才有超图“系统表” Datasource datasource = workspace.Datasources.Open(info); ////udb数据源 //DatasourceConnectionInfo udbInfo = new DatasourceConnectionInfo(); ////设置数据源连接的引擎类型 //udbInfo.EngineType = EngineType.UDB; ////设置文件位置 //udbInfo.Server = @"D:\MicroDesktop\Temp\test"; //// 创建/打开数据库数据源 //Datasource udbDatasource = workspace.Datasources.Create(udbInfo); //Datasource udbDatasource = workspace.Datasources.Open(udbInfo); //Memory数据源 DatasourceConnectionInfo memInfo = new DatasourceConnectionInfo(); //设置数据源连接的引擎类型 memInfo.EngineType = EngineType.Memory; memInfo.Alias = "fdgdfgd"; memInfo.Server = "tyjyutjyu"; // 创建/打开数据库数据源 Datasource memDatasource = workspace.Datasources.Create(memInfo); //svc-矢量数据 //DatasourceConnectionInfo scvInfo = new DatasourceConnectionInfo(); ////设置数据源连接的引擎类型 //scvInfo.EngineType = EngineType.VectorFile; ////设置文件位置 //scvInfo.Server = @"D:\MicroDesktop\Temp\test2"; //// 创建/打开数据库数据源 //Datasource scvDatasource = workspace.Datasources.Create(scvInfo); if (datasource != null) { ImportResult result = ImportShpToMemory(filePath, memDatasource); if (result.FailedSettings.Length == 0) { Console.WriteLine($"导入{filePath}成功!"); //for (int i = 0; i < memDatasource.Datasets.Count; i++) //{ // DatasetVector datasetVector = (DatasetVector)memDatasource.Datasets[i]; // Dataset newDataset = datasource.CopyDataset(datasetVector, datasetVector.Name, EncodeType.None); //} DatasetVector datasetVector = (DatasetVector)memDatasource.Datasets[0]; //datasource.Datasets.CreateFromTemplate(datasetVector.Name, datasetVector); //var t1=datasource.Datasets.CreateFromTemplate(datasetVector.Name, memDatasource.Datasets[0]); //var t2= datasource.CopyDataset(datasetVector, datasetVector.Name, EncodeType.None); //datasource.Flush(datasetVector.Name); var re = datasetVector.GetRecordset(false, SuperMap.Data.CursorType.Dynamic); //re.AddNew( var v3 = datasource.Datasets.CreateAndAppendWithSmid(targetTableName, re); var v4 = datasource.Datasets.CreateFromTemplate(targetTableName, memDatasource.Datasets[0]); var v5 = datasource.CopyDataset(datasetVector, targetTableName, datasetVector.EncodeType); //datasource.Datasets.Create(datasetVector); var dataset = datasource.Datasets[targetTableName]; var ve = dataset as DatasetVector; var record = ve?.GetRecordset(false, SuperMap.Data.CursorType.Dynamic); //record.AddNew(...); //var v2= datasource.RecordsetToDataset(re, targetTableName); datasource.Refresh(); //String name = datasource.Datasets.GetAvailableDatasetName(targetTableName); // 设置矢量数据集的信息 //DatasetVectorInfo datasetVectorInfo = new DatasetVectorInfo(); //datasetVectorInfo.Type = DatasetType.Line; //datasetVectorInfo.IsFileCache = true; //datasetVectorInfo.Name = name; //datasetVectorInfo.Bounds = new Rectangle2D(new Point2D(0, 0), new Point2D(10, 10)); //Console.WriteLine("矢量数据集的信息为:" + datasetVectorInfo.ToString()); //// 创建矢量数据集 //datasource.Datasets.Create(datasetVectorInfo); //datasource.Flush(name); //var d2= datasource.CopyDatasetWithSmID(udbDatasource.Datasets[0], targetTableName, EncodeType.None); //var d = datasource.CopyDataset(udbDatasource.Datasets[0], targetTableName, EncodeType.None); } else { Console.WriteLine($"导入{filePath}失败!"); } } // 释放工作空间资源 info.Dispose(); workspace.Dispose(); }
public ExcelModule() : base("Excel") { //任务列表 Post["/GridExport"] = r => { string excelParam = Request.Form["excelParam"]; if (string.IsNullOrEmpty(excelParam)) { return(""); } ExcelInfo info = JsonConvert.DeserializeObject <ExcelInfo>(excelParam); if (string.IsNullOrEmpty(info.FileName)) { info.FileName = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls"; } else { if (!info.FileName.EndsWith(".xls")) { info.FileName = info.FileName + ".xls"; } } MemoryStream ms = info.ExportExeclStream(); byte[] msbyte = ms.GetBuffer(); ms.Dispose(); ms = null; return(new Response() { Contents = stream => { stream.Write(msbyte, 0, msbyte.Length); }, ContentType = "application/msexcel", StatusCode = HttpStatusCode.OK, Headers = new Dictionary <string, string> { { "Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlPathEncode(info.FileName)) }, { "Content-Length", msbyte.Length.ToString() } } }); }; /// <summary> /// 导出Excel模版 /// </summary> /// <param name="type">业务类型</param> /// <param name="FunctionCode">对应功能模块Code</param> /// <returns></returns> Get["/DownLoadTemplate"] = r => { if (AllImports == null) { AllImports = MefConfig.ResolveMany <ExcelImport>(); } string strType = Request.Query["type"]; ExcelImportType type = EnumHelper.StringToEnum <ExcelImportType>(strType); var handler = AllImports.FirstOrDefault(e => e.Type == type); if (handler == null) { throw new Exception("未找到“" + type.ToString() + "”相应处理模块"); } string path = ExcelImporMapper.GetTemplatePath(type); if (File.Exists(path)) { try { string FileName = Path.GetFileName(path); return(new Response() { Contents = stream => { handler.GetExportTemplate(path, stream); }, ContentType = MimeHelper.GetMineType(path), StatusCode = HttpStatusCode.OK, Headers = new Dictionary <string, string> { { "Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlPathEncode(FileName)) } } }); } catch (Exception ex) { throw ex; } } else { throw new Exception("未找到“" + type.ToString() + "”对应模版文件"); } }; /// <summary> /// 导入Excel模版 /// </summary> /// <returns></returns> Post["/ImportTemplate"] = r => { ImportResult result = new ImportResult(); try { if (AllImports == null) { AllImports = MefConfig.ResolveMany <ExcelImport>(); } string ywType = Request.Query["type"]; if (string.IsNullOrEmpty(ywType)) { throw new ArgumentNullException("ywType"); } //业务类型 ExcelImportType type = EnumHelper.StringToEnum <ExcelImportType>(ywType); //文件 HttpFile file = Request.Files.First(); var handler = AllImports.FirstOrDefault(e => e.Type == type); if (handler == null) { throw new Exception("未找到“" + type.ToString() + "”相应处理模块"); } result = handler.ImportTemplate(file.Value, file.Name, null); if (result.IsSuccess) { //是否获取详细数据,决定后台是否返回 result.ExtraInfo string ReturnDetailData = Request.Query["ReturnDetailData"]; if (string.IsNullOrEmpty(ReturnDetailData) || ReturnDetailData != "1") { result.ExtraInfo = null; } } else { //设置错误模版http路径 result.Message = Request.Url.SiteBase + result.Message; } } catch (Exception ex) { result.IsSuccess = false; result.Message = ex.Message; LogHelper.Error("Excel导入异常", ex); } return(Response.AsJson(result)); }; }
public ImportResult ImportContent() { var result = new ImportResult(); var request = HttpContext.Current.Request; var allowSystemChanges = UserInfo.IsSuperUser; var appId = int.Parse(request["AppId"]); var zoneId = int.Parse(request["ZoneId"]); if (request.Files.Count > 0) { var file = request.Files[0]; if (file.FileName.EndsWith(".zip")) { // ZIP var zipImport = new ZipImport(zoneId, appId, PortalSettings.UserInfo.IsSuperUser); result.Succeeded = zipImport.ImportZip(file.InputStream, HttpContext.Current.Server, PortalSettings, result.Messages); } else { // XML using (var fileStreamReader = new StreamReader(file.InputStream)) { var xmlImport = new XmlImport(PortalSettings.DefaultLanguage, UserIdentity.CurrentUserIdentityToken, allowSystemChanges); var xmlDocument = XDocument.Parse(fileStreamReader.ReadToEnd()); result.Succeeded = xmlImport.ImportXml(zoneId, appId, xmlDocument); result.Messages = xmlImport.ImportLog; } } } return result; }
protected void ProcessImportedData (ImportResult import) { FinancialAccount assetAccount = FinancialAccount.FromIdentity(Int32.Parse(this.DropAssetAccount.SelectedValue)); FinancialAccount autoDepositAccount = FinancialAccount.FromIdentity(Int32.Parse(this.DropAutoDeposits.SelectedValue)); FinancialAccount autoWithdrawalAccount = FinancialAccount.FromIdentity(Int32.Parse(this.DropAutoWithdrawals.SelectedValue)); int autoDepositLimit = Int32.Parse(this.TextDepositLimit.Text); int autoWithdrawalLimit = Int32.Parse(this.TextWithdrawalLimit.Text); int organizationId = Int32.Parse(this.DropOrganizations.SelectedValue); Organization organization = Organization.FromIdentity(organizationId); int importedTransactionCount = 0; foreach (ImportedRow row in import.Rows) { // Each row is at least a stub, probably more. // If too old, ignore. if (row.DateTime < new DateTime(2008, 12, 4)) { continue; } string importKey = row.SuppliedTransactionId; // If importKey is empty, construct a hash from the data fields. if (string.IsNullOrEmpty(importKey)) { string hashKey = row.HashBase + row.Comment + (row.AmountCentsNet/100.0).ToString(CultureInfo.InvariantCulture) + row.CurrentBalance.ToString(CultureInfo.InvariantCulture) + row.DateTime.ToString("yyyy-MM-dd-hh-mm-ss"); importKey = SHA1.Hash(hashKey).Replace(" ", ""); } if (importKey.Length > 30) { importKey = importKey.Substring(0, 30); } Int64 amountCents = row.AmountCentsNet; if (amountCents == 0) { amountCents = row.AmountCentsGross; } FinancialTransaction transaction = FinancialTransaction.ImportWithStub(organizationId, row.DateTime, assetAccount.Identity, amountCents, row.Comment, importKey, _currentUser.Identity); if (transaction != null) { // The transaction was created. Examine if the autobook criteria are true. importedTransactionCount++; FinancialAccounts accounts = FinancialAccounts.FromBankTransactionTag(row.Comment); if (accounts.Count == 1) { // This is a labelled local donation. Geography geography = accounts[0].AssignedGeography; FinancialAccount localAccount = accounts[0]; transaction.AddRow(organization.FinancialAccounts.IncomeDonations, -amountCents, _currentUser); transaction.AddRow(organization.FinancialAccounts.CostsLocalDonationTransfers, amountCents, _currentUser); transaction.AddRow(localAccount, -amountCents, _currentUser); Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.LocalDonationReceived, _currentUser.Identity, organizationId, geography.Identity, 0, transaction.Identity, localAccount.Identity.ToString()); } else if (row.Comment.ToLowerInvariant().StartsWith("bg 451-0061 ")) // TODO: Organization.Parameters.FinancialTrackedTransactionPrefix { // Check for previously imported payment group PaymentGroup group = PaymentGroup.FromTag(organization, "SEBGM" + DateTime.Today.Year.ToString() + // TODO: Get tagging from org row.Comment.Substring(11)); if (group != null) { // There was a previously imported and not yet closed payment group matching this transaction // Close the payment group and match the transaction against accounts receivable transaction.Dependency = group; group.Open = false; transaction.AddRow(organization.FinancialAccounts.AssetsOutboundInvoices, -amountCents, _currentUser); } } else if (amountCents < 0) { if ((-amountCents) < autoWithdrawalLimit * 100) { // Book against autoWithdrawal account. transaction.AddRow(autoWithdrawalAccount, -amountCents, _currentUser); } } else if (amountCents > 0) { if (row.Fee < 0) { // This is always an autodeposit, if there is a fee (which is never > 0.0) transaction.AddRow(organization.FinancialAccounts.CostsBankFees, -row.Fee, _currentUser); transaction.AddRow(autoDepositAccount, -row.AmountCentsGross, _currentUser); } else if (amountCents < autoDepositLimit * 100) { // Book against autoDeposit account. transaction.AddRow(autoDepositAccount, -amountCents, _currentUser); } } } } // Import complete. Examine if we expect more transactions -- if the imported balance differs from // the database balance: double databaseAccountBalance = assetAccount.BalanceTotal; bool mismatch = false; if (databaseAccountBalance != import.CurrentBalance) { mismatch = true; } string message = importedTransactionCount.ToString() + " transactions were imported."; if (importedTransactionCount == 0) { message = "No transactions were imported. "; } else if (importedTransactionCount == 1) { message = "One transaction was imported. "; } if (import.CurrentBalance > 0) { if (mismatch) { message += " Transactions are missing from the database. Import more transactions."; } else { message += " The account balance is up to date. No further import is necessary."; ScriptManager.RegisterStartupScript(this, Page.GetType(), "alldone", "alert ('The account balance is up to date. No further import is necessary.');", true); // Auto-match open payouts against new transactions Payouts.AutomatchAgainstUnbalancedTransactions(organization); } } this.LabelImportResultText.Text = message; }
private int ProcessProducts(ICollection <ImportRow <Product> > batch, ImportResult result) { _rsProduct.AutoCommitEnabled = true; Product lastInserted = null; Product lastUpdated = null; foreach (var row in batch) { if (row.Count == 0) { continue; } Product product = null; object key; // try get by int ID if (row.TryGetValue("Id", out key) && key.ToString().ToInt() > 0) { product = _productService.GetProductById(key.ToString().ToInt()); } // try get by SKU if (product == null && row.TryGetValue("SKU", out key)) { product = _productService.GetProductBySku(key.ToString()); } // try get by GTIN if (product == null && row.TryGetValue("Gtin", out key)) { product = _productService.GetProductByGtin(key.ToString()); } if (product == null) { // a Name is required with new products. if (!row.ContainsKey("Name")) { result.AddError("The 'Name' field is required for new products. Skipping row.", row.GetRowInfo(), "Name"); continue; } product = new Product(); } row.Initialize(product, row["Name"].ToString()); if (!row.IsNew) { if (!product.Name.Equals(row["Name"].ToString(), StringComparison.OrdinalIgnoreCase)) { // Perf: use this later for SeName updates. row.NameChanged = true; } } row.SetProperty(result, product, (x) => x.Sku); row.SetProperty(result, product, (x) => x.Gtin); row.SetProperty(result, product, (x) => x.ManufacturerPartNumber); row.SetProperty(result, product, (x) => x.ProductTypeId, (int)ProductType.SimpleProduct); row.SetProperty(result, product, (x) => x.ParentGroupedProductId); row.SetProperty(result, product, (x) => x.VisibleIndividually, true); row.SetProperty(result, product, (x) => x.Name); row.SetProperty(result, product, (x) => x.ShortDescription); row.SetProperty(result, product, (x) => x.FullDescription); row.SetProperty(result, product, (x) => x.ProductTemplateId); row.SetProperty(result, product, (x) => x.ShowOnHomePage); row.SetProperty(result, product, (x) => x.MetaKeywords); row.SetProperty(result, product, (x) => x.MetaDescription); row.SetProperty(result, product, (x) => x.MetaTitle); row.SetProperty(result, product, (x) => x.AllowCustomerReviews, true); row.SetProperty(result, product, (x) => x.Published, true); row.SetProperty(result, product, (x) => x.IsGiftCard); row.SetProperty(result, product, (x) => x.GiftCardTypeId); row.SetProperty(result, product, (x) => x.RequireOtherProducts); row.SetProperty(result, product, (x) => x.RequiredProductIds); row.SetProperty(result, product, (x) => x.AutomaticallyAddRequiredProducts); row.SetProperty(result, product, (x) => x.IsDownload); row.SetProperty(result, product, (x) => x.DownloadId); row.SetProperty(result, product, (x) => x.UnlimitedDownloads, true); row.SetProperty(result, product, (x) => x.MaxNumberOfDownloads, 10); row.SetProperty(result, product, (x) => x.DownloadActivationTypeId, 1); row.SetProperty(result, product, (x) => x.HasSampleDownload); row.SetProperty(result, product, (x) => x.SampleDownloadId, (int?)null, ZeroToNull); row.SetProperty(result, product, (x) => x.HasUserAgreement); row.SetProperty(result, product, (x) => x.UserAgreementText); row.SetProperty(result, product, (x) => x.IsRecurring); row.SetProperty(result, product, (x) => x.RecurringCycleLength, 100); row.SetProperty(result, product, (x) => x.RecurringCyclePeriodId); row.SetProperty(result, product, (x) => x.RecurringTotalCycles, 10); row.SetProperty(result, product, (x) => x.IsShipEnabled, true); row.SetProperty(result, product, (x) => x.IsFreeShipping); row.SetProperty(result, product, (x) => x.AdditionalShippingCharge); row.SetProperty(result, product, (x) => x.IsEsd); row.SetProperty(result, product, (x) => x.IsTaxExempt); row.SetProperty(result, product, (x) => x.TaxCategoryId, 1); row.SetProperty(result, product, (x) => x.ManageInventoryMethodId); row.SetProperty(result, product, (x) => x.StockQuantity, 10000); row.SetProperty(result, product, (x) => x.DisplayStockAvailability); row.SetProperty(result, product, (x) => x.DisplayStockQuantity); row.SetProperty(result, product, (x) => x.MinStockQuantity); row.SetProperty(result, product, (x) => x.LowStockActivityId); row.SetProperty(result, product, (x) => x.NotifyAdminForQuantityBelow, 1); row.SetProperty(result, product, (x) => x.BackorderModeId); row.SetProperty(result, product, (x) => x.AllowBackInStockSubscriptions); row.SetProperty(result, product, (x) => x.OrderMinimumQuantity, 1); row.SetProperty(result, product, (x) => x.OrderMaximumQuantity, 10000); row.SetProperty(result, product, (x) => x.AllowedQuantities); row.SetProperty(result, product, (x) => x.DisableBuyButton); row.SetProperty(result, product, (x) => x.DisableWishlistButton); row.SetProperty(result, product, (x) => x.AvailableForPreOrder); row.SetProperty(result, product, (x) => x.CallForPrice); row.SetProperty(result, product, (x) => x.Price); row.SetProperty(result, product, (x) => x.OldPrice); row.SetProperty(result, product, (x) => x.ProductCost); row.SetProperty(result, product, (x) => x.SpecialPrice); row.SetProperty(result, product, (x) => x.SpecialPriceStartDateTimeUtc, null, OADateToUtcDate); row.SetProperty(result, product, (x) => x.SpecialPriceEndDateTimeUtc, null, OADateToUtcDate); row.SetProperty(result, product, (x) => x.CustomerEntersPrice); row.SetProperty(result, product, (x) => x.MinimumCustomerEnteredPrice); row.SetProperty(result, product, (x) => x.MaximumCustomerEnteredPrice, 1000); row.SetProperty(result, product, (x) => x.Weight); row.SetProperty(result, product, (x) => x.Length); row.SetProperty(result, product, (x) => x.Width); row.SetProperty(result, product, (x) => x.Height); row.SetProperty(result, product, (x) => x.DeliveryTimeId); row.SetProperty(result, product, (x) => x.QuantityUnitId); row.SetProperty(result, product, (x) => x.BasePriceEnabled); row.SetProperty(result, product, (x) => x.BasePriceMeasureUnit); row.SetProperty(result, product, (x) => x.BasePriceAmount); row.SetProperty(result, product, (x) => x.BasePriceBaseAmount); row.SetProperty(result, product, (x) => x.BundlePerItemPricing); row.SetProperty(result, product, (x) => x.BundlePerItemShipping); row.SetProperty(result, product, (x) => x.BundlePerItemShoppingCart); row.SetProperty(result, product, (x) => x.BundleTitleText); row.SetProperty(result, product, (x) => x.AvailableStartDateTimeUtc, null, OADateToUtcDate); row.SetProperty(result, product, (x) => x.AvailableEndDateTimeUtc, null, OADateToUtcDate); row.SetProperty(result, product, (x) => x.LimitedToStores); string storeIds = row.GetValue <string>("StoreIds"); if (storeIds.HasValue()) { _storeMappingService.SaveStoreMappings(product, row["StoreIds"].ToString() .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())).ToArray()); } row.SetProperty(result, product, (x) => x.CreatedOnUtc, DateTime.UtcNow, OADateToUtcDate); product.UpdatedOnUtc = DateTime.UtcNow; if (row.IsTransient) { _rsProduct.Insert(product); lastInserted = product; } else { _rsProduct.Update(product); lastUpdated = product; } } // commit whole batch at once var num = _rsProduct.Context.SaveChanges(); // Perf: notify only about LAST insertion and update if (lastInserted != null) { _eventPublisher.EntityInserted(lastInserted); } if (lastUpdated != null) { _eventPublisher.EntityUpdated(lastUpdated); } return(num); }
public void RunImportJob(string jobId, string csvFileName) { ImportJob job = ImportJobs.First(x => x.ImportJobId == jobId); if (job != null) { ImportResult result = new ImportResult(); _importResults[jobId] = result; using (var data = GetCsvContent(csvFileName)) { result.Length = data.BaseStream.Length; CsvReader csvReader = new CsvReader(data, job.ColumnDelimiter); try { result.IsRunning = true; result.Started = DateTime.Now; Import(job, csvReader, result); } finally { result.Stopped = DateTime.Now; result.IsRunning = false; } } } }
private void ProcessProductPictures(ICollection <ImportRow <Product> > batch, ImportResult result) { // true, cause pictures must be saved and assigned an id // prior adding a mapping. _rsProductPicture.AutoCommitEnabled = true; ProductPicture lastInserted = null; int equalPictureId = 0; foreach (var row in batch) { var pictures = new string[] { row.GetValue <string>("Picture1"), row.GetValue <string>("Picture2"), row.GetValue <string>("Picture3") }; int i = 0; try { for (i = 0; i < pictures.Length; i++) { var picture = pictures[i]; if (picture.IsEmpty() || !File.Exists(picture)) { continue; } var currentPictures = _rsProductPicture.TableUntracked.Expand(x => x.Picture).Where(x => x.ProductId == row.Entity.Id).Select(x => x.Picture).ToList(); var pictureBinary = _pictureService.FindEqualPicture(picture, currentPictures, out equalPictureId); if (pictureBinary != null && pictureBinary.Length > 0) { // no equal picture found in sequence var newPicture = _pictureService.InsertPicture(pictureBinary, "image/jpeg", _pictureService.GetPictureSeName(row.EntityDisplayName), true, true); if (newPicture != null) { var mapping = new ProductPicture() { ProductId = row.Entity.Id, PictureId = newPicture.Id, DisplayOrder = 1, }; _rsProductPicture.Insert(mapping); lastInserted = mapping; } } else { result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "Picture" + (i + 1).ToString()); } } } catch (Exception ex) { result.AddWarning(ex.Message, row.GetRowInfo(), "Picture" + (i + 1).ToString()); } } // Perf: notify only about LAST insertion and update if (lastInserted != null) { _eventPublisher.EntityInserted(lastInserted); } }
/// <summary> /// Adds laps and heart rate and altitude data from a Polar HRM file. GPS locations and other data are split into two files, GPX and HRM. /// </summary> /// <param name="fileName">The file name of the HRM file</param> /// <param name="importResult">The object where e g the route and laps collection are stored</param> public void AddLapsAndHRData(string fileName, ImportResult importResult) { using (StreamReader sr = new StreamReader(fileName)) { HRMSection currentSection = HRMSection.None; DateTime startTime = importResult.Route.FirstWaypoint.Time; List<double> heartRates = new List<double>(); List<double> altitudes = new List<double>(); int intTimesRowCount = 0; while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.StartsWith("[")) { // new section of file currentSection = StringToHRMSection(line); } else { string[] atoms; switch (currentSection) { case HRMSection.IntTimes: if (line != "") { atoms = line.Split("\t".ToCharArray()); if (intTimesRowCount % 5 == 0 && atoms.Length == 5) { double lapTimeInSeconds = TimeStringToSeconds(atoms[0]); DateTime lapTime = startTime.AddSeconds(lapTimeInSeconds); // only add lap if it is within the time span of the session if (lapTimeInSeconds != 0 && lapTime > importResult.Laps[0].Time && lapTime < importResult.Laps[importResult.Laps.Count - 1].Time) { importResult.Laps.Add(new Lap(lapTime, LapType.Lap)); } } intTimesRowCount += 1; } break; case HRMSection.HRData: atoms = line.Split("\t".ToCharArray()); if (atoms.Length == 3) { heartRates.Add(Convert.ToDouble(atoms[0])); altitudes.Add(Convert.ToDouble(atoms[2])); } break; } } } // add heart rates and altitudes int count = 0; foreach (var segment in importResult.Route.Segments) { foreach (var waypoint in segment.Waypoints) { if (count < heartRates.Count) { waypoint.HeartRate = heartRates[count]; waypoint.Altitude = altitudes[count]; count++; } } } sr.Close(); } }
public ImportResult ImportData(string codeFile) { ImportResult result2; try { string[] strArray = File.ReadAllLines(codeFile, ToolUtil.GetEncoding()); if (strArray.Length == 0) { throw new CustomException("此文件没有内容"); } string str = ""; int index = 0; bool flag = true; while (flag) { if (strArray[index].StartsWith("{销货单位编码}") || strArray[index].StartsWith("{发货人编码}")) { string str2 = strArray[index]; if (!str2.Contains("\"")) { throw new CustomException("此文件首行销货单位编码没有指定分隔符,分隔符使用双引号标注"); } str = str2.Substring(str2.IndexOf("\"")).Trim().Trim(new char[] { '"' }); flag = false; index++; } else { index++; if (index == strArray.Length) { throw new CustomException("此文件不符合销货单位编码文本格式"); } } } ImportResult result = new ImportResult(); Stack <lastBMJG> stack = new Stack <lastBMJG>(); string str4 = this.TuiJianBM(""); string str5 = ""; bool flag2 = false; for (int i = index; i < strArray.Length; i++) { BMXHDWModel model; string lineText = strArray[i].Trim(); if (((lineText.Length == 0) || lineText.StartsWith("//")) || !lineText.Contains(str)) { continue; } string[] strArray2 = GetSafeData.Split(lineText, str); if (strArray2.Length < 3) { throw new CustomException("文本首行指定的分隔符与实际分隔符不一致,\n格式不正确等原因导致不能导入此文件!"); } model = new BMXHDWModel { BM = strArray2[0], MC = strArray2[1], JM = strArray2[2], }; model.KJM = CommonFunc.GenerateKJM(model.MC); string str7 = ""; string str8 = ""; ResultType none = ResultType.None; if (strArray2.Length > 3) { if (strArray2.Length < 7) { continue; } model.SH = strArray2[3].ToUpper(); model.WJ = 1; string str9 = ""; if (str == "~~") { str9 = strArray2[4].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str9 = strArray2[4].Replace("#|#", "\r\n"); } else { str9 = strArray2[4]; } model.DZDH = str9; string str10 = ""; if (str == "~~") { str10 = strArray2[5].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str10 = strArray2[5].Replace("#|#", "\r\n"); } else { str10 = strArray2[5]; } model.YHZH = str10; string str11 = ""; if (str == "~~") { str11 = strArray2[6].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str11 = strArray2[6].Replace("#|#", "\r\n"); } else { str11 = strArray2[6]; } model.YZBM = str11; } while (stack.Count > 0) { flag2 = false; if (model.BM.Length > stack.Peek().BM.Length) { if (!model.BM.StartsWith(stack.Peek().BM)) { goto Label_0430; } model.SJBM = stack.Peek().BM; if (stack.Peek().Result == ResultType.Invalid) { str7 = "无效"; str8 = "上级编码无效"; none = ResultType.Invalid; result.Invalid++; } else if (stack.Peek().Result == ResultType.Failed) { str7 = "失败"; str8 = "上级编码失败"; none = ResultType.Failed; result.Failed++; } else { if (stack.Peek().Result != ResultType.Duplicated) { goto Label_0430; } str5 = this.TuiJianBM(stack.Peek().BM); if (model.BM.Length == str5.Length) { goto Label_0430; } str7 = "无效"; str8 = "编码长度必须与原有同级编码长度一致"; result.Invalid++; none = ResultType.Invalid; } goto Label_06AF; } stack.Pop(); } flag2 = true; Label_0430: if ((flag2 && (str4 != "001")) && (model.BM.Length != str4.Length)) { str7 = "无效"; str8 = "编码长度必须与原有同级编码长度一致"; result.Invalid++; none = ResultType.Invalid; } else if ("0" != this.CheckCustomer(model)) { str7 = "无效"; str8 = "编码或名称为空"; result.Invalid++; none = ResultType.Invalid; } else if (!Regex.IsMatch(model.BM, "^[0-9a-z]{1,16}$")) { str7 = "无效"; str8 = "编码需小于16位,且仅由数字和小写字母组成"; result.Invalid++; none = ResultType.Invalid; } if (this.bmsfhrDAL.ExistCusMC(model.BM, model.MC, model.SJBM)) { str7 = "失败"; str8 = "同级同族已存在同名销货单位" + model.SH; result.Failed++; none = ResultType.Failed; } else if (this.bmsfhrDAL.ExistCustomer(model)) { if (str7.Length == 0) { str7 = "重复"; result.Duplicated++; } if (str8.Length == 0) { str8 = "编码重复"; none = ResultType.Duplicated; } else { str8 = str8 + "且编码重复"; none = ResultType.Invalid; } } else if (((model.SH != null) && (model.SH.Length != 0)) && (((model.SH.Length < 6) || (model.SH.Length > 20)) || (((model.WJ == 1) && (model.SH.Length != 0)) && ("0000" != this.jyCustomer.CheckTaxCode(model.SH, (FPLX)12))))) { str7 = "失败"; str8 = "销货单位税号错误" + model.SH; result.Failed++; none = ResultType.Failed; } else { string[] spellCode = StringUtils.GetSpellCode(model.MC); for (int j = 0; j < spellCode.Length; j++) { string text1 = spellCode[j]; } if (this.bmsfhrDAL.AddCustomer(model) == "0") { str7 = "正确传入"; result.Correct++; none = ResultType.Correct; } else { str7 = "失败"; result.Failed++; none = ResultType.Failed; } } Label_06AF :; result.DtResult.Rows.Add(new object[] { model.BM, model.MC, str7, str8 }); stack.Push(new lastBMJG(model.BM, none)); } result.ImportTable = "销货单位编码.DB"; result2 = result; } catch { throw; } return(result2); }
public ImportResult ImportGoodsTax(string codeFile) { ImportResult result2; try { string[] strArray = File.ReadAllLines(codeFile, ToolUtil.GetEncoding()); if (strArray.Length == 0) { throw new CustomException("此文件没有内容"); } string str = ""; int index = 0; bool flag = true; while (flag) { if (strArray[index].StartsWith("{商品税目编码}")) { string str2 = strArray[index]; if (!str2.Contains("\"")) { throw new CustomException("此文件首行商品税目编码没有指定分隔符,分隔符使用双引号标注"); } str = str2.Substring(str2.IndexOf("\"")).Trim().Trim(new char[] { '"' }); flag = false; index++; } else { index++; if (index == strArray.Length) { throw new CustomException("此文件不符合商品税目编码文本格式"); } } } ImportResult result = new ImportResult(); Stack <lastBMJG> stack = new Stack <lastBMJG>(); this.TuiJianBM(""); for (int i = index; i < strArray.Length; i++) { string lineText = strArray[i].Trim(); if (((lineText.Length != 0) && !lineText.StartsWith("//")) && lineText.Contains(str)) { string[] strArray2 = GetSafeData.Split(lineText, str); if (strArray2.Length < 3) { throw new CustomException("文本首行指定的分隔符与实际分隔符不一致,\n格式不正确等原因导致不能导入此文件!"); } string str5 = ""; string str6 = ""; ResultType none = ResultType.None; BMSPSMModel spsmEntity = new BMSPSMModel { SZ = strArray2[0], BM = strArray2[1], MC = strArray2[2] }; double num3 = 0.0; if (!double.TryParse(strArray2[3], out num3)) { throw new CustomException(string.Format("第{0}行数据格式不正确", i)); } spsmEntity.SLV = num3; if (!double.TryParse(strArray2[4], out num3)) { throw new CustomException(string.Format("第{0}行数据格式不正确", i)); } spsmEntity.ZSL = num3; spsmEntity.SLJS = (strArray2[5] == "false") ? byte.Parse("0") : byte.Parse("1"); spsmEntity.JSDW = strArray2[6]; double num4 = 0.0; if (!double.TryParse(strArray2[7], out num4)) { throw new CustomException(string.Format("第{0}行数据格式不正确", i)); } spsmEntity.SE = num4; bool flag3 = false; if (!bool.TryParse(strArray2[8], out flag3)) { throw new CustomException(string.Format("第{0}行数据格式不正确", i)); } spsmEntity.FHDBZ = flag3; if (this.bmkhDAL.ExistGoodsTax(spsmEntity)) { if (str5.Length == 0) { str5 = "重复"; result.Duplicated++; } if (str6.Length == 0) { str6 = "编码重复"; none = ResultType.Duplicated; } else { str6 = str6 + "且编码重复"; none = ResultType.Invalid; } } else if (this.bmkhDAL.AddGoodsTax(spsmEntity) == "0") { str5 = "正确传入"; result.Correct++; none = ResultType.Correct; } else { str5 = "失败"; result.Failed++; none = ResultType.Failed; } result.DtResult.Rows.Add(new object[] { spsmEntity.BM, spsmEntity.MC, str5, str6 }); stack.Push(new lastBMJG(spsmEntity.BM, none)); } } result.ImportTable = "SPSMBM.DB"; result2 = result; } catch { throw; } return(result2); }
protected static ImportResult ImportPayson(string contents) { string regexPattern = @"<tr>\s+<td>\s*(?<datetime>[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2})\s*</td><td>(?<comment1>[^<]*)</td><td>[^>]*</td><td>(?<txid>[0-9]+)</td>\s*<td>(?<from>[^<]+)</td>\s*<td>(?<to>[^<]+)</td><td class=\""tal\"">(?<gross>[\-0-9,]+)</td><td class=\""tal\"">(?<fee>[\-0-9,]+)</td><td class=\""tal\"">(?<vat>[\-0-9,]+)</td><td class=\""tal\"">(?<net>[\-0-9,]+)</td><td class=\""tal\"">(?<balance>[\-0-9,]+)</td><td>(?<currency>[^<]+)</td><td>(?<reference>[^<]+)</td><td[^>]+?>(?<comment2>[^<]+)</td>"; Regex regex = new Regex(regexPattern, RegexOptions.Singleline); Match match = regex.Match(contents); ImportResult result = new ImportResult(); List<ImportedRow> rows = new List<ImportedRow>(); while (match.Success) { if (match.Groups["currency"].Value != "SEK") { continue; // HACK: Need to fix currency support at some time } // Get current balance from the first line in the file if (result.CurrentBalance == 0.0) { result.CurrentBalance = Int64.Parse(match.Groups["balance"].Value.Replace(",", ""))/10000.0; } ImportedRow row = new ImportedRow(); // DEBUG -- REMOVE WHEN DEPLOYING if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("New Row -----"); Console.WriteLine("- SuppliedTxId: {0}", match.Groups["txid"].Value); Console.WriteLine("- Comment: {0}", HttpUtility.HtmlDecode(match.Groups["comment2"].Value)); Console.WriteLine("- DateTime: {0}", match.Groups["datetime"].Value); Console.WriteLine("- AmountGross: {0}", match.Groups["gross"].Value); Console.WriteLine("- Fee: {0}", match.Groups["fee"].Value); Console.WriteLine("- AmountNet: {0}", match.Groups["net"].Value); } string comment = HttpUtility.HtmlDecode(match.Groups["comment2"].Value.Trim()); if (String.IsNullOrEmpty(comment)) { comment = match.Groups["comment1"].Value.Trim(); } row.SuppliedTransactionId = "Payson-" + match.Groups["txid"].Value; row.Comment = comment; row.DateTime = DateTime.Parse(match.Groups["datetime"].Value, CultureInfo.InvariantCulture); row.AmountCentsGross = Int64.Parse(match.Groups["gross"].Value.Replace(".", "").Replace(",", ""))/100; row.FeeCents = Int64.Parse(match.Groups["fee"].Value.Replace(".", "").Replace(",", ""))/100; row.AmountCentsNet = Int64.Parse(match.Groups["net"].Value.Replace(".", "").Replace(",", ""))/100; rows.Add(row); match = match.NextMatch(); } result.Rows = rows; return result; }
public ImportResult ImportDistrict(string codeFile) { ImportResult result2; try { string[] strArray = File.ReadAllLines(codeFile, ToolUtil.GetEncoding()); if (strArray.Length == 0) { throw new CustomException("此文件没有内容"); } string str = ""; int index = 0; bool flag = true; while (flag) { if (strArray[index].StartsWith("{行政区编码}")) { string str2 = strArray[index]; if (!str2.Contains("\"")) { throw new CustomException("此文件首行行政区编码没有指定分隔符,分隔符使用双引号标注"); } str = str2.Substring(str2.IndexOf("\"")).Trim().Trim(new char[] { '"' }); flag = false; index++; } else { index++; if (index == strArray.Length) { throw new CustomException("此文件不符合行政区编码文本格式"); } } } ImportResult result = new ImportResult(); Stack <lastBMJG> stack = new Stack <lastBMJG>(); this.TuiJianBM(""); for (int i = index; i < strArray.Length; i++) { string lineText = strArray[i].Trim(); if (((lineText.Length != 0) && !lineText.StartsWith("//")) && lineText.Contains(str)) { string[] strArray2 = GetSafeData.Split(lineText, str); if (strArray2.Length < 3) { throw new CustomException("文本首行指定的分隔符与实际分隔符不一致,\n格式不正确等原因导致不能导入此文件!"); } string str5 = ""; string str6 = ""; ResultType none = ResultType.None; BMXZQYModel xzqEntity = new BMXZQYModel { BM = strArray2[0], MC = strArray2[1] }; if (this.bmkhDAL.ExistDistrict(xzqEntity)) { if (str5.Length == 0) { str5 = "重复"; result.Duplicated++; } if (str6.Length == 0) { str6 = "编码重复"; none = ResultType.Duplicated; } else { str6 = str6 + "且编码重复"; none = ResultType.Invalid; } } else if (this.bmkhDAL.AddDistrict(xzqEntity) == "0") { str5 = "正确传入"; result.Correct++; none = ResultType.Correct; } else { str5 = "失败"; result.Failed++; none = ResultType.Failed; } result.DtResult.Rows.Add(new object[] { xzqEntity.BM, xzqEntity.MC, str5, str6 }); stack.Push(new lastBMJG(xzqEntity.BM, none)); } } result.ImportTable = "XZQBM"; result2 = result; } catch { throw; } return(result2); }
// // GET: /amiimport/pois public ActionResult Pois(string jsonFile) { const string basePath = "~/Modules/Laser.Orchard.Maps/Contents/Ami/"; Regex contactsPattern = new Regex("(?<address>.+)Tel:(?<phone>.+)Email:(?<email>.+)Web:(?<website>.+)"); Dictionary <int, int> OutdoorCategoryDictionary = new Dictionary <int, int>(); Dictionary <int, int> SitiCategoryDictionary = new Dictionary <int, int>(); SitiCategoryDictionary.Add(1, 17); // Patrimonio Industriale SitiCategoryDictionary.Add(2, 16); // Arte e storia SitiCategoryDictionary.Add(3, 124); // Parchi e aree naturalistiche SitiCategoryDictionary.Add(4, 121); // Archeologia SitiCategoryDictionary.Add(5, 122); // Beni religiosi SitiCategoryDictionary.Add(6, 123); // Cultura materiale OutdoorCategoryDictionary.Add(7, 132); // Sport montani OutdoorCategoryDictionary.Add(8, 130); // Sport acquatici OutdoorCategoryDictionary.Add(9, 128); // Equitazione OutdoorCategoryDictionary.Add(10, 126); // Ciclismo OutdoorCategoryDictionary.Add(11, 129); // Escursionismo OutdoorCategoryDictionary.Add(12, 125); // Altri sport OutdoorCategoryDictionary.Add(13, 127); // Corsa OutdoorCategoryDictionary.Add(14, 131); // Sport invernali object objPois = DeserializzaDaFileSystemJson(typeof(PoiRootObject), Server.MapPath(basePath + jsonFile)); PoiRootObject pois = (PoiRootObject)objPois; int numContent = 0; int newContent = 0; int totContents = 0; foreach (Point singlePoint in pois.points) { try { totContents++; // Verifico se il POI esiste già. Se esiste lo aggiorno, altrimenti lo creo. var contentId = 0; contentId = _fieldIndexRecord.Fetch( f => f.DecimalFieldIndexRecords.Any <DecimalFieldIndexRecord>( r => r.PropertyName == "POI.ImportId." && r.Value == numContent + 1 ) ).Select(c => c.Id).LastOrDefault(); ContentItem content = null; content = _contentManager.Get(contentId); if (content == null) { newContent++; content = _contentManager.New("POI"); _contentManager.Create(content, VersionOptions.Latest); } // Inserisco i dati di base ((dynamic)content).TitlePart.Title = singlePoint.title; ((dynamic)content).MapPart.Longitude = (float)singlePoint.longitude; ((dynamic)content).MapPart.Latitude = (float)singlePoint.latitude; ((dynamic)content).MapPart.LocationInfo = singlePoint.title; string description = ""; if (!String.IsNullOrWhiteSpace(singlePoint.description)) { description = description + singlePoint.description.Replace("\n", "<br>"); } if (!String.IsNullOrWhiteSpace(singlePoint.timePrices)) { if (description.Length > 0) { description = description + "<br>"; } description = description + singlePoint.timePrices.Replace("\n", "<br>"); } ((dynamic)content).BodyPart.Text = description; ((dynamic)content).POI.Sport.Value = singlePoint.sport; // Genero alias autoroute if (String.IsNullOrWhiteSpace(((dynamic)content).AutoroutePart.DisplayAlias)) { ((dynamic)content).AutoroutePart.DisplayAlias = _autorouteService.Value.GenerateAlias(((dynamic)content).AutoroutePart); _autorouteService.Value.PublishAlias(((dynamic)content).AutoroutePart); } // Assegno ImportId e lo indicizzo (necessario per eseguire ricerche su di esso) ((dynamic)content).POI.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)content).FieldIndexPart, "POI", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); // Aggiungo le categorie e le foto int termId; List <TermPart> termList = new List <TermPart>(); string subFolder = ""; foreach (int category in singlePoint.categories) { termId = 0; if (OutdoorCategoryDictionary.TryGetValue(category, out termId)) { subFolder = "\\Outdoor"; } else if (SitiCategoryDictionary.TryGetValue(category, out termId)) { subFolder = "\\Siti"; } if (termId != 0) { termList.Add(_contentManager.Get <TermPart>(termId)); } } _taxonomyService.UpdateTerms(content, termList, "Categoria"); List <Int32> photoIds = new List <Int32>(); foreach (var photo in singlePoint.photos) { byte[] imageBytes = System.IO.File.ReadAllBytes(Server.MapPath(basePath + "Foto/" + photo)); var mediaPart = _mediaLibraryService.ImportMedia(new MemoryStream(imageBytes), "POI" + subFolder, photo.Replace(" ", "")); _contentManager.Create(mediaPart); photoIds.Add(mediaPart.Id); } ((dynamic)content).POI.Gallery.Ids = photoIds.ToArray(); // Aggiungo contatti var contactContentId = 0; contactContentId = _fieldIndexRecord.Fetch( f => f.DecimalFieldIndexRecords.Any <DecimalFieldIndexRecord>( r => r.PropertyName == "Contatto.ImportId." && r.Value == numContent + 1 ) ).Select(c => c.Id).LastOrDefault(); ContentItem contacts = null; contacts = _contentManager.Get(contactContentId); if (!String.IsNullOrWhiteSpace(singlePoint.contacts)) { Match match = contactsPattern.Match(singlePoint.contacts.Replace("\n", " ")); if (match.Success) { if (contacts == null) { contacts = _contentManager.New("Contatto"); _contentManager.Create(contacts, VersionOptions.Latest); ((dynamic)contacts).Contatto.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)contacts).FieldIndexPart, "Contatto", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); } ((dynamic)contacts).TitlePart.Title = singlePoint.title; ((dynamic)contacts).Contatto.Indirizzo.Value = (match.Groups["address"].Value).Trim(); ((dynamic)contacts).Contatto.Telefono.Value = (match.Groups["phone"].Value).Trim(); ((dynamic)contacts).Contatto.Email.Value = (match.Groups["email"].Value).Trim(); ((dynamic)contacts).Contatto.Note.Value = ""; string websiteUrl = (match.Groups["website"].Value).Trim(); if (!websiteUrl.StartsWith("http://")) { websiteUrl = "http://" + websiteUrl; } ((dynamic)contacts).Contatto.SitoWeb.Value = websiteUrl; ((dynamic)content).POI.Contatti.Ids = new Int32[] { contacts.Id }; _contentManager.Publish(contacts); } else if (singlePoint.contacts.ToLower().StartsWith("per informazion")) { if (contacts == null) { contacts = _contentManager.New("Contatto"); _contentManager.Create(contacts, VersionOptions.Latest); ((dynamic)contacts).Contatto.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)contacts).FieldIndexPart, "Contatto", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); } ((dynamic)contacts).TitlePart.Title = singlePoint.title; ((dynamic)contacts).Contatto.Indirizzo.Value = ""; ((dynamic)contacts).Contatto.Telefono.Value = ""; ((dynamic)contacts).Contatto.Email.Value = ""; ((dynamic)contacts).Contatto.Note.Value = singlePoint.contacts; ((dynamic)contacts).Contatto.SitoWeb.Value = ""; ((dynamic)content).POI.Contatti.Ids = new Int32[] { contacts.Id }; _contentManager.Publish(contacts); } else if (Regex.Match(singlePoint.contacts.Replace("\n", " "), "(?<address>.+)Tel:(?<phone>.+)").Success) { match = Regex.Match(singlePoint.contacts.Replace("\n", " "), "(?<address>.+)Tel:(?<phone>.+)"); if (contacts == null) { contacts = _contentManager.New("Contatto"); _contentManager.Create(contacts, VersionOptions.Latest); ((dynamic)contacts).Contatto.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)contacts).FieldIndexPart, "Contatto", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); } ((dynamic)contacts).TitlePart.Title = singlePoint.title; ((dynamic)contacts).Contatto.Indirizzo.Value = (match.Groups["address"].Value).Trim(); ((dynamic)contacts).Contatto.Telefono.Value = (match.Groups["phone"].Value).Trim(); ((dynamic)contacts).Contatto.Email.Value = ""; ((dynamic)contacts).Contatto.Note.Value = ""; ((dynamic)contacts).Contatto.SitoWeb.Value = ""; ((dynamic)content).POI.Contatti.Ids = new Int32[] { contacts.Id }; _contentManager.Publish(contacts); } else if (Regex.Match(singlePoint.contacts.Replace("\n", " "), "(?<address>.+)Email:(?<email>.+)").Success) { match = Regex.Match(singlePoint.contacts.Replace("\n", " "), "(?<address>.+)Email:(?<email>.+)"); if (contacts == null) { contacts = _contentManager.New("Contatto"); _contentManager.Create(contacts, VersionOptions.Latest); ((dynamic)contacts).Contatto.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)contacts).FieldIndexPart, "Contatto", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); } ((dynamic)contacts).TitlePart.Title = singlePoint.title; ((dynamic)contacts).Contatto.Indirizzo.Value = (match.Groups["address"].Value).Trim(); ((dynamic)contacts).Contatto.Telefono.Value = ""; ((dynamic)contacts).Contatto.Email.Value = (match.Groups["email"].Value).Trim(); ((dynamic)contacts).Contatto.Note.Value = ""; ((dynamic)contacts).Contatto.SitoWeb.Value = ""; ((dynamic)content).POI.Contatti.Ids = new Int32[] { contacts.Id }; _contentManager.Publish(contacts); } else { if (contacts == null) { contacts = _contentManager.New("Contatto"); _contentManager.Create(contacts, VersionOptions.Latest); ((dynamic)contacts).Contatto.ImportId.Value = (Decimal)numContent + 1; _fieldIndexService.Set(((dynamic)contacts).FieldIndexPart, "Contatto", "ImportId", "", (Decimal)numContent + 1, typeof(Decimal)); } ((dynamic)contacts).TitlePart.Title = singlePoint.title; ((dynamic)contacts).Contatto.Indirizzo.Value = singlePoint.contacts.Trim(); ((dynamic)contacts).Contatto.Telefono.Value = ""; ((dynamic)contacts).Contatto.Email.Value = ""; ((dynamic)contacts).Contatto.Note.Value = ""; ((dynamic)contacts).Contatto.SitoWeb.Value = ""; ((dynamic)content).POI.Contatti.Ids = new Int32[] { contacts.Id }; _contentManager.Publish(contacts); } } else if (contacts != null) { _contentManager.Remove(contacts); ((dynamic)content).POI.Contatti.Ids = new Int32[] {}; } _contentManager.Publish(content); numContent++; } catch (Exception ex2) { Log.Error(ex2, "Object Title: " + singlePoint.title); } finally { pois = null; } } pois = null; var model = new ImportResult { TotContents = totContents, NewContents = newContent, ElaboratedContents = numContent }; return(View(model)); }
public override IEnumerator OnCoroutine(Action <float> onProgress = null) { // No nodes if (nodes == null) { if (onProgress != null) { onProgress.Invoke(1f); } IsCompleted = true; yield break; } Result = new ImportResult[nodes.Count]; // Initialize transforms for (int i = 0; i < Result.Length; i++) { Result[i] = new GLTFNode.ImportResult(); Result[i].transform = new GameObject().transform; Result[i].transform.name = nodes[i].name; } // Set up hierarchy for (int i = 0; i < Result.Length; i++) { if (nodes[i].children != null) { int[] children = nodes[i].children; Result[i].children = children; for (int k = 0; k < children.Length; k++) { int childIndex = children[k]; Result[childIndex].parent = i; Result[childIndex].transform.parent = Result[i].transform; } } } // Apply TRS for (int i = 0; i < Result.Length; i++) { nodes[i].ApplyTRS(Result[i].transform); } // Setup components for (int i = 0; i < Result.Length; i++) { // Setup mesh if (nodes[i].mesh.HasValue) { GLTFMesh.ImportResult meshResult = meshTask.Result[nodes[i].mesh.Value]; if (meshResult == null) { continue; } Mesh mesh = meshResult.mesh; Renderer renderer; if (nodes[i].skin.HasValue) { GLTFSkin.ImportResult skin = skinTask.Result[nodes[i].skin.Value]; renderer = skin.SetupSkinnedRenderer(Result[i].transform.gameObject, mesh, Result); } else if (mesh.blendShapeCount > 0) { // Blend shapes require skinned mesh renderer SkinnedMeshRenderer mr = Result[i].transform.gameObject.AddComponent <SkinnedMeshRenderer>(); mr.sharedMesh = mesh; renderer = mr; } else { MeshRenderer mr = Result[i].transform.gameObject.AddComponent <MeshRenderer>(); MeshFilter mf = Result[i].transform.gameObject.AddComponent <MeshFilter>(); renderer = mr; mf.sharedMesh = mesh; } //Materials renderer.materials = meshResult.materials; if (string.IsNullOrEmpty(Result[i].transform.name)) { Result[i].transform.name = "node" + i; } } else { if (string.IsNullOrEmpty(Result[i].transform.name)) { Result[i].transform.name = "node" + i; } } // Setup camera if (nodes[i].camera.HasValue) { GLTFCamera cameraData = cameras[nodes[i].camera.Value]; Camera camera = Result[i].transform.gameObject.AddComponent <Camera>(); Result[i].transform.localRotation = Result[i].transform.localRotation * Quaternion.Euler(0, 180, 0); if (cameraData.type == CameraType.orthographic) { camera.orthographic = true; camera.nearClipPlane = cameraData.orthographic.znear; camera.farClipPlane = cameraData.orthographic.zfar; camera.orthographicSize = cameraData.orthographic.ymag; } else { camera.orthographic = false; camera.nearClipPlane = cameraData.perspective.znear; if (cameraData.perspective.zfar.HasValue) { camera.farClipPlane = cameraData.perspective.zfar.Value; } if (cameraData.perspective.aspectRatio.HasValue) { camera.aspect = cameraData.perspective.aspectRatio.Value; } camera.fieldOfView = Mathf.Rad2Deg * cameraData.perspective.yfov; } } } IsCompleted = true; }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); StreamReader reader = new StreamReader(FileName); RouteSegment rs = new RouteSegment(); LapCollection laps = new LapCollection(); int i; string[] atoms; string line; for (i = 0; i < 3; i++) reader.ReadLine(); // start time atoms = reader.ReadLine().Split("\t".ToCharArray()); DateTime startTime = DateTime.MinValue; int firstColonPosition = atoms[1].IndexOf(":"); int lastColonPosition = atoms[1].LastIndexOf(":"); int length = lastColonPosition + 2 - firstColonPosition + 2 + 1; if (length > 0) { if(DateTime.TryParse(atoms[1].Substring(firstColonPosition - 2, lastColonPosition + 2 - firstColonPosition + 2 + 1), out startTime)) { startTime = startTime.ToUniversalTime(); } } // go to start of coordinates i = 0; while (i < 5 && !reader.EndOfStream) { line = reader.ReadLine(); if (line == "") i++; } reader.ReadLine(); reader.ReadLine(); // read all coordinates while (!reader.EndOfStream) { line = reader.ReadLine(); if (line == "") break; atoms = line.Split("\t".ToCharArray()); Waypoint w = new Waypoint(); w.Time = startTime.AddSeconds(Convert.ToInt32(atoms[0])); w.LongLat = new LongLat(ParseFRWDLongLatString(atoms[5]), ParseFRWDLongLatString(atoms[4])); double altitude; double.TryParse(LocalizeDecimalString(atoms[6]), out altitude); w.Altitude = altitude; double heartRate; double.TryParse(LocalizeDecimalString(atoms[9]), out heartRate); w.HeartRate = heartRate; rs.Waypoints.Add(w); if (atoms[1] != "") { // lap Lap lap = new Lap(); lap.LapType = LapType.Lap; lap.Time = w.Time; laps.Add(lap); } } if (laps.Count > 0) laps[0].LapType = LapType.Start; if (laps.Count > 1) laps[laps.Count - 1].LapType = LapType.Stop; importResult.Laps = laps; List<RouteSegment> routeSegments = new List<RouteSegment>(); if(rs.Waypoints.Count > 0) { routeSegments.Add(rs); importResult.Route = new Route(routeSegments); importResult.Succeeded = true; } else { importResult.Succeeded = false; importResult.Error = ImportError.NoWaypoints; } reader.Close(); if (EndWork != null) EndWork(this, new EventArgs()); }
public ImportResult Import(GLTFAccessor.ImportResult[] accessors, GLTFNode.ImportResult[] nodes, ImportSettings importSettings) { bool multiRoots = nodes.Where(x => x.IsRoot).Count() > 1; ImportResult result = new ImportResult(); result.clip = new AnimationClip(); result.clip.name = name; result.clip.frameRate = importSettings.animationSettings.frameRate; result.clip.legacy = importSettings.animationSettings.useLegacyClips; if (result.clip.legacy && importSettings.animationSettings.looping) { result.clip.wrapMode = WrapMode.Loop; } for (int i = 0; i < channels.Length; i++) { Channel channel = channels[i]; if (samplers.Length <= channel.sampler) { Debug.LogWarning($"GLTFUtility: Animation channel points to sampler at index {channel.sampler} which doesn't exist. Skipping animation clip."); continue; } Sampler sampler = samplers[channel.sampler]; // Get interpolation mode InterpolationMode interpolationMode = importSettings.animationSettings.interpolationMode; if (interpolationMode == InterpolationMode.ImportFromFile) { interpolationMode = sampler.interpolation; } if (interpolationMode == InterpolationMode.CUBICSPLINE) { Debug.LogWarning("Animation interpolation mode CUBICSPLINE not fully supported, result might look different."); } string relativePath = ""; GLTFNode.ImportResult node = nodes[channel.target.node.Value]; while (node != null && !node.IsRoot) { if (string.IsNullOrEmpty(relativePath)) { relativePath = node.transform.name; } else { relativePath = node.transform.name + "/" + relativePath; } if (node.parent.HasValue) { node = nodes[node.parent.Value]; } else { node = null; } } // If file has multiple root nodes, a new parent will be created for them as a final step of the import process. This parent f***s up the curve relative paths. // Add node.transform.name to path if there are multiple roots. This is not the most elegant fix but it works. // See GLTFNodeExtensions.GetRoot if (multiRoots) { relativePath = node.transform.name + "/" + relativePath; } System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; float[] keyframeInput = accessors[sampler.input].ReadFloat().ToArray(); switch (channel.target.path) { case "translation": Vector3[] pos = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve posX = new AnimationCurve(); AnimationCurve posY = new AnimationCurve(); AnimationCurve posZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { posX.AddKey(CreateKeyframe(k, keyframeInput, pos, x => - x.x, interpolationMode)); posY.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.y, interpolationMode)); posZ.AddKey(CreateKeyframe(k, keyframeInput, pos, x => x.z, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY); result.clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ); break; case "rotation": Vector4[] rot = accessors[sampler.output].ReadVec4().ToArray(); AnimationCurve rotX = new AnimationCurve(); AnimationCurve rotY = new AnimationCurve(); AnimationCurve rotZ = new AnimationCurve(); AnimationCurve rotW = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { // The Animation window in Unity shows keyframes incorrectly converted to euler. This is only to deceive you. The quaternions underneath work correctly rotX.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.x, interpolationMode)); rotY.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.y, interpolationMode)); rotZ.AddKey(CreateKeyframe(k, keyframeInput, rot, x => - x.z, interpolationMode)); rotW.AddKey(CreateKeyframe(k, keyframeInput, rot, x => x.w, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ); result.clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW); break; case "scale": Vector3[] scale = accessors[sampler.output].ReadVec3().ToArray(); AnimationCurve scaleX = new AnimationCurve(); AnimationCurve scaleY = new AnimationCurve(); AnimationCurve scaleZ = new AnimationCurve(); for (int k = 0; k < keyframeInput.Length; k++) { scaleX.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.x, interpolationMode)); scaleY.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.y, interpolationMode)); scaleZ.AddKey(CreateKeyframe(k, keyframeInput, scale, x => x.z, interpolationMode)); } result.clip.SetCurve(relativePath, typeof(Transform), "localScale.x", scaleX); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.y", scaleY); result.clip.SetCurve(relativePath, typeof(Transform), "localScale.z", scaleZ); break; case "weights": GLTFNode.ImportResult skinnedMeshNode = nodes[channel.target.node.Value]; SkinnedMeshRenderer skinnedMeshRenderer = skinnedMeshNode.transform.GetComponent <SkinnedMeshRenderer>(); int numberOfBlendShapes = skinnedMeshRenderer.sharedMesh.blendShapeCount; AnimationCurve[] blendShapeCurves = new AnimationCurve[numberOfBlendShapes]; for (int j = 0; j < numberOfBlendShapes; ++j) { blendShapeCurves[j] = new AnimationCurve(); } float[] weights = accessors[sampler.output].ReadFloat().ToArray(); float[] weightValues = new float[keyframeInput.Length]; float[] previouslyKeyedValues = new float[numberOfBlendShapes]; // Reference for my future self: // keyframeInput.Length = number of keyframes // keyframeInput[ k ] = timestamp of keyframe // weights.Length = number of keyframes * number of blendshapes // weights[ j ] = actual animated weight of a specific blend shape // (index into weights[] array accounts for keyframe index and blend shape index) for (int k = 0; k < keyframeInput.Length; ++k) { for (int j = 0; j < numberOfBlendShapes; ++j) { int weightIndex = (k * numberOfBlendShapes) + j; weightValues[k] = weights[weightIndex]; bool addKey = true; if (importSettings.animationSettings.compressBlendShapeKeyFrames) { if (k == 0 || !Mathf.Approximately(weightValues[k], previouslyKeyedValues[j])) { if (k > 0) { weightValues[k - 1] = previouslyKeyedValues[j]; blendShapeCurves[j].AddKey(CreateKeyframe(k - 1, keyframeInput, weightValues, x => x, interpolationMode)); } addKey = true; previouslyKeyedValues[j] = weightValues[k]; } else { addKey = false; } } if (addKey) { blendShapeCurves[j].AddKey(CreateKeyframe(k, keyframeInput, weightValues, x => x, interpolationMode)); } } } for (int j = 0; j < numberOfBlendShapes; ++j) { string propertyName = "blendShape." + skinnedMeshRenderer.sharedMesh.GetBlendShapeName(j); result.clip.SetCurve(relativePath, typeof(SkinnedMeshRenderer), propertyName, blendShapeCurves[j]); } break; } } return(result); }
public ImportResult ImportData(string codeFile) { ImportResult result2; try { string[] strArray = File.ReadAllLines(codeFile, ToolUtil.GetEncoding()); if (strArray.Length == 0) { throw new CustomException("此文件没有内容"); } string str = ""; int index = 0; bool flag = true; while (flag) { if (strArray[index].StartsWith("{车辆编码}")) { string str2 = strArray[index]; if (!str2.Contains("\"")) { throw new CustomException("此文件首行车辆编码没有指定分隔符,分隔符使用双引号标注"); } str = str2.Substring(str2.IndexOf("\"")).Trim().Trim(new char[] { '"' }); flag = false; index++; } else { index++; if (index == strArray.Length) { throw new CustomException("此文件不符合车辆编码文本格式"); } } } ImportResult result = new ImportResult(); Stack <lastBMJG> stack = new Stack <lastBMJG>(); string str4 = this.TuiJianBM(""); string str5 = ""; bool flag2 = false; for (int i = index; i < strArray.Length; i++) { BMCLModel model; string lineText = strArray[i].Trim(); if (((lineText.Length == 0) || lineText.StartsWith("//")) || !lineText.Contains(str)) { continue; } string[] strArray2 = GetSafeData.Split(lineText, str); if (strArray2.Length < 3) { throw new CustomException("文本首行指定的分隔符与实际分隔符不一致,\n格式不正确等原因导致不能导入此文件!"); } model = new BMCLModel { BM = strArray2[0], MC = strArray2[1], JM = strArray2[2], }; model.KJM = CommonFunc.GenerateKJM(model.MC); string str7 = ""; string str8 = ""; ResultType none = ResultType.None; if (strArray2.Length > 3) { if (strArray2.Length < 6) { throw new CustomException(string.Format("第{0}行数据不全", i)); } model.WJ = 1; string str9 = ""; if (str == "~~") { str9 = strArray2[3].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str9 = strArray2[3].Replace("#|#", "\r\n"); } else { str9 = strArray2[3]; } model.CPXH = str9; string str10 = ""; if (str == "~~") { str10 = strArray2[4].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str10 = strArray2[4].Replace("#|#", "\r\n"); } else { str10 = strArray2[4]; } model.CD = str10; string str11 = ""; if (str == "~~") { str11 = strArray2[5].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str11 = strArray2[5].Replace("#|#", "\r\n"); } else { str11 = strArray2[5]; } model.SCCJMC = str11; if (Flbm.IsYM() && (strArray2.Length > 6)) { DAL.BMSPFLManager manager = new DAL.BMSPFLManager(); string bm = ""; if (str == "~~") { bm = strArray2[6].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { bm = strArray2[6].Replace("#|#", "\r\n"); } else { bm = strArray2[6]; } if (strArray2.Length > 7) { string str13 = ""; if (str == "~~") { str13 = strArray2[7].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str13 = strArray2[7].Replace("#|#", "\r\n"); } else { str13 = strArray2[7]; } if (manager.CanUseThisSPFLBM(bm, false, false)) { model.SPFL = bm; model.SPFLMC = manager.GetSPFLMCBYBM(bm); if (manager.CanUseThisYHZC(bm)) { if ((str13.Trim() == "是") || (str13.Trim() == "否")) { model.YHZC = str13; if (model.YHZC == "否") { model.YHZCMC = ""; } } else { model.YHZC = "否"; model.YHZCMC = ""; } if (strArray2.Length > 9) { bool flag3 = false; if (str13.Trim() == "是") { object[] objArray = ServiceFactory.InvokePubService("Aisino.Fwkp.Bmgl.GetSLV_BY_BM", new object[] { model.SPFL }); if ((objArray != null) && (objArray.Length > 0)) { string[] strArray3 = (objArray[0] as DataTable).Rows[0]["ZZSTSGL"].ToString().Split(new char[] { ',', '、', ';', ',', ';' }); if (strArray3.Length > 0) { foreach (string str14 in strArray3) { if (strArray2[9].Trim() == str14) { model.YHZC = "是"; string str15 = ""; if (str == "~~") { str15 = strArray2[9].Replace(",", "\r\n").Replace("#|#", "\r\n"); } else if (str == " ") { str15 = strArray2[9].Replace("#|#", "\r\n"); } else { str15 = strArray2[9]; } model.YHZCMC = str15; flag3 = true; } if (!Flbm.IsDK() && strArray2[9].Trim().Contains("1.5%")) { model.YHZC = "否"; model.YHZCMC = ""; } } } } if (!flag3) { model.YHZC = "否"; model.YHZCMC = ""; } } else if (str13.Trim() == "否") { model.YHZC = "否"; model.YHZCMC = ""; } else { model.YHZC = "否"; model.YHZCMC = ""; } } } else { model.YHZC = "否"; model.YHZCMC = ""; } } } } } while (stack.Count > 0) { flag2 = false; if (model.BM.Length > stack.Peek().BM.Length) { if (!model.BM.StartsWith(stack.Peek().BM)) { goto Label_07AE; } model.SJBM = stack.Peek().BM; if (stack.Peek().Result == ResultType.Invalid) { str7 = "无效"; str8 = "上级编码无效"; none = ResultType.Invalid; result.Invalid++; } else if (stack.Peek().Result == ResultType.Failed) { str7 = "失败"; str8 = "上级编码失败"; none = ResultType.Failed; result.Failed++; } else { if (stack.Peek().Result != ResultType.Duplicated) { goto Label_07AE; } str5 = this.TuiJianBM(stack.Peek().BM); if (model.BM.Length == str5.Length) { goto Label_07AE; } str7 = "无效"; str8 = "编码长度必须与原有同级编码长度一致"; result.Invalid++; none = ResultType.Invalid; } goto Label_0940; } stack.Pop(); } flag2 = true; Label_07AE: if ((flag2 && (str4 != "001")) && (model.BM.Length != str4.Length)) { str7 = "无效"; str8 = "编码长度必须与原有同级编码长度一致"; result.Invalid++; none = ResultType.Invalid; } else if ("0" != this.CheckCustomer(model)) { str7 = "无效"; str8 = "编码或名称为空"; result.Invalid++; none = ResultType.Invalid; } else if (!Regex.IsMatch(model.BM, "^[0-9a-z]{1,16}$")) { str7 = "无效"; str8 = "编码需小于16位,且仅由数字和小写字母组成"; result.Invalid++; none = ResultType.Invalid; } else if (this.bmclDAL.ExistCustomer(model)) { if (str7.Length == 0) { str7 = "重复"; result.Duplicated++; } if (str8.Length == 0) { str8 = "编码重复"; none = ResultType.Duplicated; } else { str8 = str8 + "且编码重复"; none = ResultType.Invalid; } } else { string[] spellCode = StringUtils.GetSpellCode(model.MC); for (int j = 0; j < spellCode.Length; j++) { string text1 = spellCode[j]; } if (this.bmclDAL.AddCustomer(model) == "0") { str7 = "正确传入"; result.Correct++; none = ResultType.Correct; } else { str7 = "失败"; result.Failed++; none = ResultType.Failed; } } Label_0940 :; result.DtResult.Rows.Add(new object[] { model.BM, model.MC, str7, str8 }); stack.Push(new lastBMJG(model.BM, none)); } result.ImportTable = "车辆编码.DB"; result2 = result; } catch { throw; } return(result2); }
protected ImportResult ImportSebText(string contents) { string patternRows = @"^\s(?<datetime>[0-9]{4}\-[0-9]{2}\-[0-9]{2})\s\t[0-9]{4}\-[0-9]{2}\-[0-9]{2}\s\t(?<transactionid>[^\s]+)\s\t(?<comment>[^\t]+)\t(?<amount>[\-,.0-9]+)\s\t(?<balance>[\-,.0-9]+)"; string patternBalance = @"^[0-9\s]+\t[\-0-9\.\,]+\s\t(?<balance>[\-0-9\.\,]+)\s\t[\-0-9\.\,]+"; List<ImportedRow> rows = new List<ImportedRow>(); ImportResult result = new ImportResult(); Regex regexBalance = new Regex(patternBalance, RegexOptions.Multiline | RegexOptions.Compiled); Regex regexRows = new Regex(patternRows, RegexOptions.Multiline | RegexOptions.Compiled); Match matchBalance = regexBalance.Match(contents); if (!matchBalance.Success) { throw new ArgumentException("Unable to find balance"); } string stringBalance = matchBalance.Groups["balance"].Value.Replace(".", "").Replace(",", "."); result.CurrentBalance = Double.Parse(stringBalance, CultureInfo.InvariantCulture); Match matchRow = regexRows.Match(contents); while (matchRow.Success) { string amountString = matchRow.Groups["amount"].Value; amountString = amountString.Replace(".", "").Replace(",", ""); ImportedRow row = new ImportedRow(); row.DateTime = DateTime.Parse(matchRow.Groups["datetime"].Value); row.Comment = matchRow.Groups["comment"].Value.Trim(); row.CurrentBalance = Double.Parse(matchRow.Groups["balance"].Value.Replace(".", "").Replace(",", "."), CultureInfo.InvariantCulture); row.AmountCentsNet = Int64.Parse(amountString); row.HashBase = matchRow.Groups["transactionid"].Value; rows.Add(row); matchRow = matchRow.NextMatch(); } result.Rows = rows; if (rows.Count < 100 && rows.Count > 0) { // A serious error has occurred. Dev assistance is necessary. Person.FromIdentity(1).SendNotice("Contents for bank parsing (I see " + rows.Count.ToString() + " rows)\r\n\r\n", contents, 1); Person.FromIdentity(1).SendPhoneMessage("Bank import failed - " + rows.Count.ToString() + " rows parsed - see mail"); throw new ArgumentException("PirateWeb is unable to parse the page. Developer assistance has been called in."); } return result; }
private void Import(ImportJob job, CsvReader reader, ImportResult result) { Dictionary<string, int> csvNames = GetCsvNamesAndIndexes(reader); ColumnMapping columnMapping = ColumnMappings.First(x => x.ColumnMappingId == job.ColumnMappingId); IEntityImporter importer = _entityImporters.FirstOrDefault(i => i.Name == job.EntityImporter); while (true) { try { string[] csvValues = reader.ReadRow(); if (csvValues == null) break; var systemValues = MapColumns(columnMapping.SystemPropertiesMap, csvNames, csvValues); var customValues = MapColumns(columnMapping.CustomPropertiesMap, csvNames, csvValues); importer.Import(job.ContainerId, columnMapping.PropertySetId, systemValues, customValues, _catalogRepository); result.CurrentProgress = reader.CurrentPosition; result.ProcessedRecordsCount++; } catch(Exception e) { result.ErrorsCount++; if (result.Errors == null) result.Errors = new List<string>(); result.Errors.Add(e.Message); //check if errors amount reached the allowed errors limit if yes do not save made changes. if (result.ErrorsCount >= job.MaxErrorsCount) { _catalogRepository.UnitOfWork.RollbackChanges(); break; } } } if (result.ErrorsCount < job.MaxErrorsCount) { _catalogRepository.UnitOfWork.Commit(); } }
public ImportResult ImportDataZC(string codeFile) { new Dictionary <string, object>(); ImportResult result = new ImportResult(); XmlDocument document = new XmlDocument(); try { try { document.Load(codeFile); } catch { throw new Exception("不符合机动车编码格式"); } XmlNode documentElement = document.DocumentElement; try { if (documentElement.Attributes["TYPE"].Value != "JDCBIANMA") { throw new Exception("不符合机动车编码格式"); } } catch { throw new Exception("不符合机动车编码格式"); } XmlNodeList list = null; list = documentElement.SelectNodes("/Data/CLXX/Row"); List <Dictionary <string, string> > list2 = new List <Dictionary <string, string> >(); foreach (XmlNode node2 in list) { Dictionary <string, string> item = new Dictionary <string, string>(); if (Flbm.IsYM()) { if (node2.Attributes["SPFLBM"] == null) { item.Add("SPFLBM", ""); } else { item.Add(node2.Attributes["SPFLBM"].Name, node2.Attributes["SPFLBM"].Value); } } item.Add(node2.Attributes["SCQYMC"].Name, node2.Attributes["SCQYMC"].Value); item.Add(node2.Attributes["DJ"].Name, node2.Attributes["DJ"].Value); item.Add(node2.Attributes["CDMC"].Name, node2.Attributes["CDMC"].Value); item.Add(node2.Attributes["CPXH"].Name, node2.Attributes["CPXH"].Value); item.Add(node2.Attributes["CLLXMC"].Name, node2.Attributes["CLLXMC"].Value); item.Add(node2.Attributes["CLDLMC"].Name, node2.Attributes["CLDLMC"].Value); item.Add(node2.Attributes["CPBM"].Name, node2.Attributes["CPBM"].Value); list2.Add(item); } DAL.BMSPFLManager manager = new DAL.BMSPFLManager(); foreach (Dictionary <string, string> dictionary2 in list2) { BMCLModel car = new BMCLModel(); string searchid = ""; searchid = this.bmclDAL.AutoNodeLogic(dictionary2["CLDLMC"]); car.SJBM = searchid; car.BM = this.TuiJianBM(searchid); car.MC = dictionary2["CLLXMC"]; car.SCCJMC = dictionary2["SCQYMC"]; car.CPXH = dictionary2["CPXH"]; car.CD = dictionary2["CDMC"]; if (Flbm.IsYM() && manager.CanUseThisSPFLBM(dictionary2["SPFLBM"], false, false)) { car.SPFL = dictionary2["SPFLBM"]; car.SPFLMC = manager.GetSPFLMCBYBM(car.SPFL); if (!manager.CanUseThisYHZC(car.SPFL)) { car.YHZC = "否"; car.YHZCMC = ""; } } car.KJM = CommonFunc.GenerateKJM(car.MC); car.WJ = 1; string str2 = this.AddCustomerToAuto(car, car.SJBM); if ("OverWrite" == str2) { result.Correct++; result.DtResult.Rows.Add(new object[] { car.BM, car.MC, "正确传入", "覆盖记录:" + car.BM }); } else if ("Insert" == str2) { result.Correct++; result.DtResult.Rows.Add(new object[] { car.BM, car.MC, "正确传入", "插入成功:" + car.BM }); } else { result.Failed++; result.DtResult.Rows.Add(new object[] { car.BM, car.MC, "失败", "数据库读写错误" }); } } } catch { throw; } result.ImportTable = "车辆编码.DB"; return(result); }
public int Save(ImportResult result, IEnumerable<Transaction> transactions) { _imports.Add(new Tuple<ImportResult, ImportedTransaction[]>(result, transactions.Select(_mappingEngine.Map<ImportedTransaction>).ToArray())); result.Id = _imports.Count; return result.Id; }
[HttpPost("import"), RequestSizeLimit(5 * 1024 * 1024)] // 5MB public virtual async Task <ActionResult <ImportResult> > Import([FromQuery] ImportArguments args) { Stopwatch watch = new Stopwatch(); watch.Start(); Stopwatch watch2 = new Stopwatch(); watch2.Start(); decimal parsingToEntitiesForSave = 0; decimal attributeValidationInCSharp = 0; decimal validatingAndSaving = 0; return(await ControllerUtilities.InvokeActionImpl(async() => { // Parse the file into Entities + map back to row numbers (The way source code is compiled into machine code + symbols file) var(entities, rowNumberFromErrorKeyMap) = await ParseImplAsync(args); // This should check for primary code consistency! parsingToEntitiesForSave = Math.Round(((decimal)watch2.ElapsedMilliseconds) / 1000, 1); watch2.Restart(); // Validation ObjectValidator.Validate(ControllerContext, null, null, entities); attributeValidationInCSharp = Math.Round(((decimal)watch2.ElapsedMilliseconds) / 1000, 1); watch2.Restart(); if (!ModelState.IsValid) { var mappedModelState = MapModelState(ModelState, rowNumberFromErrorKeyMap); throw new UnprocessableEntityException(mappedModelState); } // Saving try { await SaveImplAsync(entities, new SaveArguments { ReturnEntities = false }); validatingAndSaving = Math.Round(((decimal)watch2.ElapsedMilliseconds) / 1000, 1); watch2.Stop(); } catch (UnprocessableEntityException ex) { var mappedModelState = MapModelState(ex.ModelState, rowNumberFromErrorKeyMap); throw new UnprocessableEntityException(mappedModelState); } var result = new ImportResult { Inserted = entities.Count(e => e.Id?.Equals(default(TKey)) ?? false), Updated = entities.Count(e => !(e.Id?.Equals(default(TKey)) ?? false)), }; // Record the time watch.Stop(); var elapsed = Math.Round(((decimal)watch.ElapsedMilliseconds) / 1000, 1); result.Seconds = elapsed; result.ParsingToDtosForSave = parsingToEntitiesForSave; result.AttributeValidationInCSharp = attributeValidationInCSharp; result.ValidatingAndSaving = validatingAndSaving; return Ok(result); }, _logger)); }