/// <summary> /// Handles the specified request. All behaviors will be called first. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public override async Task <CommandResponse <TResponse> > Handle(TRequest request, CancellationToken cancellationToken) { foreach (var behavior in this.behaviors.Safe()) { var behaviorResult = await behavior.ExecuteAsync(request).AnyContext(); if (behaviorResult.Cancelled) // abort if this behavior did not succeed { // TODO: log reason return(new CommandResponse <TResponse>(behaviorResult.CancelledReason)); } } var commandName = typeof(TRequest).Name.SubstringTill("Command"); this.Logger.LogJournal(LogKeys.AppCommand, $"[{request.Identifier}] handle {commandName}", LogEventPropertyKeys.TrackHandleCommand); this.Logger.LogTraceEvent(LogKeys.AppCommand, request.Id, commandName, LogTraceEventNames.Command); using (var timer = new Common.Timer()) { var result = await this.HandleRequest(request, cancellationToken).AnyContext(); timer.Stop(); this.Logger.LogTraceEvent(LogKeys.AppCommand, request.Id, commandName, LogTraceEventNames.Command, timer.Elapsed); return(result); } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var correlationId = request.GetCorrelationId(); var requestId = request.GetRequestId(); await this.LogHttpRequest(request, correlationId, requestId); using (var timer = new Common.Timer()) { var response = await base.SendAsync(request, cancellationToken).AnyContext(); timer.Stop(); await this.LogHttpResponse(response, requestId, timer.Elapsed); return(response); } }
public void SurfaceMeshByBoundary() { Document adoc = Application.DocumentManager.MdiActiveDocument; if (adoc == null) { return; } Database db = adoc.Database; DB = db; Editor ed = adoc.Editor; ED = ed; CivilDocument cdok = CivilDocument.GetCivilDocument(adoc.Database); try { Color currColor = db.Cecolor; if (!currColor.IsByLayer)//Если текущий слой не по слою, то расчитать более темный цвет для границ участков { Color dimmerColor = Utils.GetDimmerColor(currColor, BORDER_DIM_MULTIPLIER); ColorForBorder = dimmerColor; } else { ColorForBorder = Color.FromColorIndex(ColorMethod.ByAci, 256); } if (!TinSurfIdIsValid()) { //Выбрать поверхность if (!PickTinSurf(ed)) { return;//Если выбор не успешен, прервать выполнение } } //Подсветить поверхность HighlightTinSurf(true); //Запрос ключевых слов while (true) { const string kw1 = "ПОВерхность"; const string kw2 = "ВОЗвышение"; const string kw3 = "ОТКлонкниеОтДуг"; const string kw4 = "СОЗдаватьГраницы"; PromptKeywordOptions pko = new PromptKeywordOptions("\nЗадайте параметры или пустой ввод для продолжения"); pko.Keywords.Add(kw1); pko.Keywords.Add(kw2); pko.Keywords.Add(kw3); pko.Keywords.Add(kw4); pko.AllowNone = true; PromptResult pr = ed.GetKeywords(pko); if (pr.Status == PromptStatus.Cancel) { return; } if (String.IsNullOrEmpty(pr.StringResult)) { break; } switch (pr.StringResult) { case kw1: if (!PickTinSurf(ed)) { return; } break; case kw2: if (!GetMeshElevation(ed)) { return; } break; case kw3: if (!GetApproxParam(ed)) { return; } break; case kw4: if (!GetCreateBorders(ed)) { return; } break; } } //Проверка текущего набора выбора acSSet = null; PromptSelectionResult acSSPrompt; acSSPrompt = ed.SelectImplied(); if (acSSPrompt.Status == PromptStatus.OK) { acSSet = acSSPrompt.Value; } else { //Множественный выбор блоков TypedValue[] tv = new TypedValue[] { new TypedValue(0, "INSERT") }; SelectionFilter flt = new SelectionFilter(tv); PromptSelectionOptions pso = new PromptSelectionOptions(); pso.MessageForAdding = "\nВыберите блоки участков"; acSSPrompt = adoc.Editor.GetSelection(pso, flt); if (acSSPrompt.Status == PromptStatus.OK) { acSSet = acSSPrompt.Value; } } if (acSSet != null) { Common.Timer timerMain = new Common.Timer(); timerMain.Start(); foreach (SelectedObject acSSObj in acSSet) { string blockName = null; Common.Timer timer = new Common.Timer(); timer.Start(); try { if (acSSObj != null) { //полилинии внутри блока List <ObjectId> polylines = new List <ObjectId>(); BlockReference blockReference = null; ObjectId btrId = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) { //блок внутри набора выбора blockReference = tr.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as BlockReference; tr.Commit(); } Matrix3d transform = Matrix3d.Identity; if (blockReference != null) { //трансформация из системы координат блока в мировую систему координат transform = blockReference.BlockTransform; //Перебор всех объектов внутри блока //Найти все правильные полилинии в блоке using (Transaction tr = db.TransactionManager.StartTransaction()) { btrId = blockReference.BlockTableRecord; BlockTableRecord blockTableRecord = tr.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord; if (blockTableRecord.XrefStatus == XrefStatus.NotAnXref) { blockName = blockTableRecord.Name; foreach (ObjectId id in blockTableRecord) { using (Polyline poly = tr.GetObject(id, OpenMode.ForRead) as Polyline) { if (poly != null && (poly.Closed || poly.GetPoint2dAt(0).Equals(poly.GetPoint2dAt(poly.NumberOfVertices - 1))) &&//Полилиния замкнута !Utils.PolylineIsSelfIntersecting(poly) &&//Не имеет самопересечений poly.Visible == true &&//Учет многовидовых блоков poly.Bounds != null ) { polylines.Add(id); } } AcadDb.Entity ent = tr.GetObject(id, OpenMode.ForRead) as AcadDb.Entity; if (ent is Polyline) { Polyline poly = ent as Polyline; } } if (polylines.Count > 0) { //Проверить все линии на пересечение друг с другом. Удалить из списка те, которые имеют пересечения HashSet <ObjectId> polylinesWithNoIntersections = new HashSet <ObjectId>(polylines); //Сделать RBush для всех полилиний RBush <SpatialEntity> polylinesTree = new RBush <SpatialEntity>(); List <SpatialEntity> spatialEntities = new List <SpatialEntity>(); foreach (ObjectId polyId in polylines) { spatialEntities.Add(new SpatialEntity(polyId)); } polylinesTree.BulkLoad(spatialEntities); foreach (SpatialEntity se in spatialEntities) { //Нахождение всех объектов, расположенных в пределах BoundingBox для этой полилинии IReadOnlyList <SpatialEntity> nearestNeighbors = polylinesTree.Search(se.Envelope); if (nearestNeighbors.Count > 1) { Polyline thisPoly = tr.GetObject(se.ObjectId, OpenMode.ForRead) as Polyline; foreach (SpatialEntity n in nearestNeighbors) { if (!n.Equals(se))//Всегда будет находиться та же самая полилиния { Polyline otherPoly = tr.GetObject(n.ObjectId, OpenMode.ForRead) as Polyline; Point3dCollection pts = new Point3dCollection(); thisPoly.IntersectWith(otherPoly, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); if (pts.Count > 0) { polylinesWithNoIntersections.Remove(thisPoly.Id); polylinesWithNoIntersections.Remove(otherPoly.Id); break; } } } } } //Аппроксимация всех полилиний, которые имеют кривизну List <Polyline> polylinesToProcess = new List <Polyline>(); foreach (ObjectId polyId in polylinesWithNoIntersections) { using (Polyline poly = tr.GetObject(polyId, OpenMode.ForRead) as Polyline) { polylinesToProcess.Add(ApproximatePolyBulges(poly, approxParam));//Какой допуск оптимален? } } //Удалить все повторяющиеся подряд точки полилинии foreach (Polyline poly in polylinesToProcess) { for (int i = 0; i < poly.NumberOfVertices;) { Point2d curr = poly.GetPoint2dAt(i); int nextIndex = (i + 1) % poly.NumberOfVertices; Point2d next = poly.GetPoint2dAt(nextIndex); if (next.IsEqualTo(curr, new Tolerance(0.001, 0.001)))//Прореживать точки, расположенные слишком близко//TODO: Учесть масштабирование блока { poly.RemoveVertexAt(nextIndex); } else { i++; } } } //Построение дерева вложенности полилиний using (TinSurface tinSurf = tr.GetObject(tinSurfId, OpenMode.ForRead) as TinSurface) { using (PolylineNesting polylineNesting = new PolylineNesting(tinSurf)) { foreach (Polyline poly in polylinesToProcess) { poly.TransformBy(transform); polylineNesting.Insert(poly); } //Расчет полигонов polylineNesting.CalculatePoligons(); //Построение сети using (SubDMesh sdm = polylineNesting.CreateSubDMesh()) { List <Line> lines = new List <Line>(); if (createBorders) { //Создание 3d линий по границе lines = polylineNesting.CreateBorderLines(); } //Объекты постоены в координатах пространства модели if (sdm != null) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForWrite); if (btr.GetBlockReferenceIds(true, false).Count > 1) { //Если у блока несколько вхождений, то создавать объекты в пространстве модели BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ms.AppendEntity(sdm); tr.AddNewlyCreatedDBObject(sdm, true); foreach (Line line in lines) { ms.AppendEntity(line); tr.AddNewlyCreatedDBObject(line, true); } } else { //Если у блока только одно вхождение, то создавать сеть внутри блока sdm.TransformBy(transform.Inverse()); btr.AppendEntity(sdm); tr.AddNewlyCreatedDBObject(sdm, true); foreach (Line line in lines) { line.TransformBy(transform.Inverse()); btr.AppendEntity(line); tr.AddNewlyCreatedDBObject(line, true); } } } foreach (Line line in lines) { line.Dispose(); } } } } } } tr.Commit(); } } } } catch (System.Exception ex) { string message = "Возникла ошибка при обработке одного из выбранных объектов"; if (!String.IsNullOrEmpty(blockName)) { message = "Возникла ошибка при обработке вхождения блока " + blockName; } Utils.ErrorToCommandLine(ed, message, ex); } timer.TimeOutput(blockName); } ed.WriteMessage("\n" + timerMain.TimeOutput("Затрачено времени (параметр аппроксимации - " + approxParam + ")") ); ed.Regen(); } } catch (System.Exception ex) { CommonException(ex, "Ошибка при создании сетей по участкам поверхности"); } finally { HighlightTinSurf(false); } }
private async Task ExecuteJobAsync(JobRegistration registration, IJob job, CancellationToken cancellationToken, string[] args = null) { if (registration?.Key.IsNullOrEmpty() == false && job != null) { try { async Task Execute() { using (var timer = new Common.Timer()) using (this.logger.BeginScope(new Dictionary <string, object> { [LogEventPropertyKeys.CorrelationId] = IdGenerator.Instance.Next })) { // TODO: publish domain event (job started) var span = IdGenerator.Instance.Next; this.logger.LogJournal(LogKeys.JobScheduling, $"job started (key={{JobKey}}, id={registration.Identifier}, type={job.GetType().PrettyName()}, isReentrant={registration.IsReentrant}, timeout={registration.Timeout.ToString("c")})", LogEventPropertyKeys.TrackStartJob, args: new[] { registration.Key }); this.logger.LogTraceEvent(LogKeys.JobScheduling, span, registration.Key, LogTraceEventNames.Job); await job.ExecuteAsync(cancellationToken, args).AnyContext(); await Run.DelayedAsync(new TimeSpan(0, 0, 1), () => { timer.Stop(); this.logger.LogJournal(LogKeys.JobScheduling, $"job finished (key={{JobKey}}, id={registration.Identifier}, type={job.GetType().PrettyName()})", LogEventPropertyKeys.TrackFinishJob, args: new[] { LogKeys.JobScheduling, registration.Key }); this.logger.LogTraceEvent(LogKeys.JobScheduling, span, registration.Key, LogTraceEventNames.Job, timer.Elapsed); return(Task.CompletedTask); }); // TODO: publish domain event (job finished) } } if (!registration.IsReentrant) { if (this.mutex.TryAcquireLock(registration.Key)) { try { await Execute(); } finally { this.mutex.ReleaseLock(registration.Key); } } else { this.logger.LogWarning($"{{LogKey:l}} already executing (key={{JobKey}}, type={job.GetType().PrettyName()})", LogKeys.JobScheduling, registration.Key); } } else { await Execute(); } } catch (OperationCanceledException ex) { // TODO: publish domain event (job failed) this.logger.LogWarning(ex, $"{{LogKey:l}} canceled (key={{JobKey}}), type={job.GetType().PrettyName()})", LogKeys.JobScheduling, registration.Key); //this.errorHandler?.Invoke(ex); } catch (Exception ex) { // TODO: publish domain event (job failed) this.logger.LogError(ex.InnerException ?? ex, $"{{LogKey:l}} failed (key={{JobKey}}), type={job.GetType().PrettyName()})", LogKeys.JobScheduling, registration.Key); this.errorHandler?.Invoke(ex.InnerException ?? ex); } } }
public override int Execute(params string[] parameters) { SetPropsByExcelWindow setPropsByExcelWindow = null; try { Document doc = Application.ActiveDocument; ModelItemCollection selection = doc.CurrentSelection.SelectedItems; if (selection.Count != 1) { Win.MessageBox.Show("Перед вызовом этой команды нужно выбрать 1 из элементов модели, " + "к которым должны быть привязаны данные из Excel", "Подсказка"); return(0); } ModelItem sampleItem = selection.First; string initialPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string docFileName = doc.FileName; if (!String.IsNullOrEmpty(docFileName)) { initialPath = Path.GetDirectoryName(docFileName); } setPropsByExcelWindow = new SetPropsByExcelWindow(sampleItem, initialPath); bool?result = null; result = setPropsByExcelWindow.ShowDialog(); if (result != null && result.Value) { Common.Timer timer = new Common.Timer(); timer.Start(); PropertyCategory propertyCategory = setPropsByExcelWindow.SelectedPropertyCategory; /*NamedConstant*/ string keyCatName = propertyCategory.DisplayName; //.CombinedName;//.DisplayName; DataProperty dataProperty = setPropsByExcelWindow.SelectedDataProperty; /*NamedConstant*/ string keyPropName = dataProperty.DisplayName; //.CombinedName;// Excel._Worksheet worksheet = setPropsByExcelWindow.SelectedWorkSheet; Common.ExcelInterop.CellValue excelColumn = setPropsByExcelWindow.SelectedColumn; //Перенести все значения из столбца в словарь - не ускоряет работу //Dictionary<string, int> keyValues // = Common.ExcelInterop.Utils.GetColumnValues(worksheet, excelColumn.ColumnNum); Excel.Range columns = worksheet.Columns; Excel.Range keyColumn = columns[excelColumn.ColumnNum]; string tabName = setPropsByExcelWindow.TabName; bool ignoreNonVisible = setPropsByExcelWindow.IgnoreNonVisible; SortedDictionary <int, Common.ExcelInterop.CellValue> tableHeader = setPropsByExcelWindow.TabelHeader; Dictionary <string, int> columnHeaderLookup = new Dictionary <string, int>(); foreach (KeyValuePair <int, Common.ExcelInterop.CellValue> kvp in tableHeader) { string columnName = kvp.Value.DisplayString; try { columnHeaderLookup.Add(columnName, kvp.Key); } catch (ArgumentException) { Win.MessageBox.Show( "Строка с названиями столбцов содрежит одинаковые названия. Повторяется \"" + columnName + "\".", "Одинаковые названия столбцов"); return(0); } } //get state object of COM API ComApi.InwOpState3 oState = ComApiBridge.ComApiBridge.State; //Поиск всех объектов, у которых есть указанное свойство //http://adndevblog.typepad.com/aec/2012/05/navisworks-net-api-find-item.html Search search = new Search(); search.Selection.SelectAll(); search.PruneBelowMatch = true;//В наборе не будет вложенных элементов search.SearchConditions .Add(SearchCondition.HasPropertyByDisplayName/*.HasPropertyByCombinedName*/ (keyCatName, keyPropName)); ModelItemCollection items = search.FindAll(doc, false); matchCount = 0; SearchForExcelTableMatches(doc, items, ignoreNonVisible, keyColumn, //keyValues, keyCatName, keyPropName, oState, worksheet, tableHeader, tabName ); //System.Runtime.InteropServices.Marshal.ReleaseComObject(columns); //System.Runtime.InteropServices.Marshal.ReleaseComObject(keyColumn); Win.MessageBox.Show(timer.TimeOutput("Общее время") + "\nНайдено совпадений - " + matchCount, "Готово", Win.MessageBoxButton.OK, Win.MessageBoxImage.Information); } } catch (Exception ex) { CommonException(ex, "Ошибка при заполнении атрибутов в Navis из таблицы Excel"); } finally { //Закрыть Excel if (setPropsByExcelWindow != null) { setPropsByExcelWindow.CloseUsingExcel(); } } return(0); }