void ISimulationInformationServiceCallback.ReceiveIndividualLocation(LocationPoint point) { if (this.LocationChanged != null) { this.LocationChanged(point); } }
public static GetEventsResult GetEventsAroundPOI(LocationPoint PointOfInterest) { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); EndpointAddress endpointAddress = new EndpointAddress("http://localhost:56071/CaloomMainService.svc"); ICaloomMainService service = new ChannelFactory< ICaloomMainService >(basicHttpBinding, endpointAddress).CreateChannel(); var serviceResponse = service.GetEventsAroundPOI(PointOfInterest); return serviceResponse; }
/* * Initialize beacon object from FamilyInstance and LocationPoint * */ public Beacon(FamilyInstance fi, LocationPoint lp) { this.categoryName = fi.Category.Name; this.beaconType = fi.Name; this.elementId = fi.Id; // Stores as feet internally so convert to meters this.xLoc = Utilities.feetToMeters(lp.Point.X); this.yLoc = Utilities.feetToMeters(lp.Point.Y); this.zLoc = Utilities.feetToMeters(lp.Point.Z); }
/// <summary> /// create the room tags for the rooms which lack room tag /// </summary> public void CreateTags() { try { foreach (Room tmpRoom in m_roomsWithoutTag) { // get the location point of the room LocationPoint locPoint = tmpRoom.Location as LocationPoint; if (null == locPoint) { String roomId = "Room Id: " + tmpRoom.Id.ToString(); String errMsg = roomId + "\r\nFault to create room tag," + "can't get the location point!"; throw new Exception(errMsg); } // create a instance of Autodesk.Revit.DB.UV class Autodesk.Revit.DB.UV point = new Autodesk.Revit.DB.UV(locPoint.Point.X, locPoint.Point.Y); //create room tag RoomTag tmpTag; tmpTag = m_revit.ActiveUIDocument.Document.Create.NewRoomTag(new LinkElementId(tmpRoom.Id), point, null); if (null != tmpTag) { m_roomTags.Add(tmpTag); } } // classify rooms ClassifyRooms(); // display a message box TaskDialog.Show("Revit", "Add room tags complete!"); } catch (Exception exception) { TaskDialog.Show("Revit", exception.Message); } }
public double DistanceToMin(Document doc, FamilyInstance familyInstance, List <PlanarFace> listPlanarFaces, XYZ point, double kl) { XYZ nor = new XYZ(1, 0, 0); double min = 0; var t = familyInstance.Id; Transform transform = familyInstance.GetTransform(); Parameter pa2 = familyInstance.LookupParameter("Flange_Edge_Offset_Right"); double pal2 = pa2.AsDouble(); Parameter pa3 = familyInstance.LookupParameter("Flange_Edge_Offset_Left"); double pal3 = pa3.AsDouble(); Parameter pa4 = familyInstance.LookupParameter("Joint"); double pal4 = pa4.AsDouble(); double sum1 = pal2 - pal4 / 2; double sum2 = pal3 - pal4 / 2; LocationPoint loc = familyInstance.Location as LocationPoint; XYZ pointloc = loc.Point; XYZ point1 = pointloc - transform.BasisX * sum1; XYZ point2 = pointloc + transform.BasisX * sum2; double space1 = point.DistanceTo(point1); double space2 = point.DistanceTo(point2); if (space1 < space2) { Plane plane = Plane.CreateByNormalAndOrigin(transform.BasisX, point1); UV uuv = new UV(); double ii; plane.Project(point, out uuv, out ii); min = ii - kl; } else { Plane plane = Plane.CreateByNormalAndOrigin(transform.BasisX, point2); UV uuv = new UV(); double ii; plane.Project(point, out uuv, out ii); min = ii - kl; } return(min); }
public void OnMakeRoute(object sender, EventArgs e) { if (DemoApp.Navigation == null) { return; } if (pinPoint == null) { return; } targetPoint = pinPoint; targetVenue = null; pinPoint = null; pinPointRect = null; DemoApp.Navigation.SetTarget(targetPoint); backView.Visibility = ViewStates.Visible; Refresh(); }
Stream(ArrayList data, Location loc) { data.Add(new Snoop.Data.ClassSeparator(typeof(Location))); // Nothing at this level yet! LocationPoint locPt = loc as LocationPoint; if (locPt != null) { Stream(data, locPt); return; } LocationCurve locCrv = loc as LocationCurve; if (locCrv != null) { Stream(data, locCrv); return; } }
private void MakePin(PointF P) { if (location == null || currentSubLocationIndex < 0) { return; } SubLocation subLoc = (SubLocation)location.SubLocations[currentSubLocationIndex]; if (subLoc == null) { return; } if (P.X < 0.0f || P.X > subLoc.Width || P.Y < 0.0f || P.Y > subLoc.Height) { // Missing the map return; } if (targetPoint != null || targetVenue != null) { SetErrorMessage("Unable to make route: you must cancel the previous route first!"); return; } if (deviceInfo.ErrorCode != 0) { SetErrorMessage("Unable to make route: navigation is not available!"); return; } pinPoint = new LocationPoint(location.Id, subLoc.Id, P.X, P.Y); pinPointRect = new RectF(); Refresh(); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { // pick object Reference pickedObj = uidoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element); if (pickedObj != null) { //Retrieve Element ElementId eleId = pickedObj.ElementId; Element ele = doc.GetElement(eleId); //Project Ray LocationPoint locp = ele.Location as LocationPoint; XYZ p1 = locp.Point; // Ray XYZ rayd = new XYZ(0, 0, 1); ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Roofs); ReferenceIntersector refi = new ReferenceIntersector(filter, FindReferenceTarget.Face, (View3D)doc.ActiveView); ReferenceWithContext refc = refi.FindNearest(p1, rayd); Reference reference = refc.GetReference(); XYZ intpoing = reference.GlobalPoint; Double dist = p1.DistanceTo(intpoing); TaskDialog.Show("Ray", string.Format("Distance to roof {0}", dist)); } return(Result.Succeeded); } catch (Exception e) { message = e.Message; return(Result.Failed); } }
public override bool Equals(Element other) { DoorElement door2 = other as DoorElement; if (door2 == null) { return(false); } if (ReferenceEquals(this, door2)) { return(true); } var param1 = Parameters.Where(p => !p.Name.Equals(Options.Instance.DoorHostWallParameter, StringComparison.OrdinalIgnoreCase)).ToList(); var param2 = door2.Parameters.Where(p => !p.Name.Equals(Options.Instance.DoorHostWallParameter, StringComparison.OrdinalIgnoreCase)).ToList(); return(FamilyName.Equals(door2.FamilyName, StringComparison.OrdinalIgnoreCase) && FamilySymbolName.Equals(door2.FamilySymbolName, StringComparison.OrdinalIgnoreCase) && Direction.Equals(door2.Direction) && LocationPoint.Equals(door2.LocationPoint) && (HostWall != null && HostWall.Count == door2.HostWall.Count) && Parameter.Equal(param1, param2)); }
/// <summary> /// Auto tag rooms with specified RoomTagType in a level /// </summary> /// <param name="level">The level where rooms will be auto tagged</param> /// <param name="tagType">The room tag type</param> public void AutoTagRooms(Level level, RoomTagType tagType) { PlanTopology planTopology = m_revit.ActiveUIDocument.Document.get_PlanTopology(level); SubTransaction subTransaction = new SubTransaction(m_revit.ActiveUIDocument.Document); subTransaction.Start(); foreach (Room tmpRoom in planTopology.Rooms) { if (tmpRoom.Level != null && tmpRoom.Location != null) { // Create a specified type RoomTag to tag a room LocationPoint locationPoint = tmpRoom.Location as LocationPoint; Autodesk.Revit.DB.UV point = new Autodesk.Revit.DB.UV(locationPoint.Point.X, locationPoint.Point.Y); RoomTag newTag = m_revit.ActiveUIDocument.Document.Create.NewRoomTag(tmpRoom, point, null); newTag.RoomTagType = tagType; List <RoomTag> tagListInTheRoom = m_roomWithTags[newTag.Room.Id.IntegerValue]; tagListInTheRoom.Add(newTag); } } subTransaction.Commit(); }
private void Getinfo_Room(Room room) { string message = "Room: "; //get the name of the room message += "\nRoom Name: " + room.Name; //get the room position LocationPoint location = room.Location as LocationPoint; XYZ point = location.Point; message += "\nRoom position: " + XYZToString(point); //get the room number message += "\nRoom number: " + room.Number; IList <IList <Autodesk.Revit.DB.BoundarySegment> > segments = room.GetBoundarySegments(new SpatialElementBoundaryOptions()); if (null != segments) //the room may not be bound { TaskDialog.Show("Segment Info", segments[0].Count().ToString()); } }
public static void MoveLinkTags(Document doc, RoomTag rt) { ElementClassFilter classFilter = new ElementClassFilter(typeof(SpatialElement)); ElementId roomId = rt.TaggedRoomId.LinkedElementId; //get link document ElementId rvtLinkId = rt.TaggedRoomId.LinkInstanceId; RevitLinkInstance rvtLink = new FilteredElementCollector(doc) .OfClass(typeof(RevitLinkInstance)) .Cast <RevitLinkInstance>() .Where(rv => rv.Id == rvtLinkId) .FirstOrDefault(); Document link_doc = rvtLink.GetLinkDocument(); // get room from linked document SpatialElement linkedSE = new FilteredElementCollector(link_doc) .OfCategory(BuiltInCategory.OST_Rooms) .WherePasses(classFilter) .Cast <SpatialElement>() .Where(se => se.Id == roomId) .FirstOrDefault(); Room linkedRoom = linkedSE as Room; // tag location Location tLoc = rt.Location; LocationPoint tagLoc = (LocationPoint)rt.Location; XYZ tagPoint = tagLoc.Point; // room location LocationPoint rLoc = linkedRoom.Location as LocationPoint; XYZ rPoint = rLoc.Point; // create "move vector" and move tag XYZ moveVector = new XYZ(rPoint.X - tagPoint.X, rPoint.Y - tagPoint.Y, rPoint.Z - rPoint.Z); tLoc.Move(moveVector); }
//*****************************MoveDoors()***************************** public void MoveDoors(Document doc, ObjDoors linkedDoor, ObjDoors localDoor) { Element linkedElement = linkedDoor.doorElement; Element localElement = localDoor.doorElement; // get the column current location LocationPoint New_InstanceLocation = linkedElement.Location as LocationPoint; LocationPoint Old_InstanceLocation = localElement.Location as LocationPoint; XYZ oldPlace = Old_InstanceLocation.Point; // XY double New_x = linkedDoor.X; double New_y = linkedDoor.Y; //Get Level Level New_level = findLevel(doc, linkedDoor); XYZ New_xyz = new XYZ(New_x, New_y, New_level.Elevation); double Move_X = New_x - oldPlace.X; double Move_Y = New_y - oldPlace.Y; //Get Level Level Old_level = findLevel(doc, linkedDoor); double Move_Z = New_level.Elevation - Old_level.Elevation; // Move the element to new location. XYZ new_xyz = new XYZ(Move_X, Move_Y, Move_Z); //Start move using a transaction. Transaction t = new Transaction(doc); t.Start("Move Element"); ElementTransformUtils.MoveElement(doc, localElement.Id, new_xyz); //ElementTransformUtils.RotateElement(doc, element.Id, New_Axis, Rotate); t.Commit(); }
/// <summary> /// Get the Autodesk.Revit.DB.XYZ point of the selected target element /// </summary> /// <param name="collection">Selected elements</param> /// <returns>the Autodesk.Revit.DB.XYZ point of the selected target element</returns> Autodesk.Revit.DB.XYZ getTargetPoint(ElementSet collection) { FamilyInstance targetElement = null; if (collection.Size != 1) { throw new Exception("You must select one component from which the distance to panels will be measured"); } else { foreach (Autodesk.Revit.DB.Element e in collection) { targetElement = e as FamilyInstance; } } if (null == targetElement) { throw new Exception("You must select one family instance from which the distance to panels will be measured"); } LocationPoint targetLocation = targetElement.Location as LocationPoint; return(targetLocation.Point); }
/// <summary> /// Searches the cabs nearby. /// </summary> /// <returns>System.Threading.Tasks.Task.</returns> private async Task SearchCabsNearby() { var geolocator = new Geolocator(); var pos = await geolocator.GetGeopositionAsync().AsTask(); var locationPoint = new LocationPoint { Latitude = pos.Coordinate.Point.Position.Latitude, Longitude = pos.Coordinate.Point.Position.Longitude }; var searchResult = this.searchClient.SearchDocuments <GpsSensorRecord>( "*", SearchDocument.FilterTextForDistanceFromPoint("geoCoordinates", locationPoint, 50000)); if (!searchResult.Any()) { await this.SendErrorMessageAsync("No cabs available"); return; } var tilelist = searchResult.Select( result => new VoiceCommandContentTile { ContentTileType = VoiceCommandContentTileType.TitleOnly, Title = result.VehicleId }).ToList(); var successmessage = new VoiceCommandUserMessage(); successmessage.DisplayMessage = successmessage.SpokenMessage = "Found the following cabs near you..."; var response = VoiceCommandResponse.CreateResponse(successmessage, tilelist); await this.voiceCommandServiceConnection.ReportSuccessAsync(response); }
private XYZ getTargetPoint(ElementSet collection) { FamilyInstance targetElement = null; if (collection.Size != 1) { throw new Exception("必须选择一个构件,从中可以测量到面板的距离"); } else { foreach (Element e in collection) { targetElement = e as FamilyInstance; } } if (null == targetElement) { throw new Exception("必须选择一个构件,从中可以测量到面板的距离"); } LocationPoint targetLocation = targetElement.Location as LocationPoint; return(targetLocation.Point); }
private void CancelPin() { if (location == null || currentSubLocationIndex < 0) { return; } SubLocation subLoc = (SubLocation)location.SubLocations[currentSubLocationIndex]; if (subLoc == null) { return; } if (targetPoint != null || targetVenue != null || pinPoint == null) { return; } pinPoint = null; pinPointRect = null; Refresh(); }
bool LocationRotate(Element element) { bool rotated = false; // Rotate the element via its location curve. LocationPoint location = element.Location as LocationPoint; LocationCurve curve = element.Location as LocationCurve; if (null != curve) { Curve line = curve.Curve; XYZ aa = line.GetEndPoint(0); XYZ cc = new XYZ(aa.X, aa.Y, aa.Z + 10); Line axis = Line.CreateBound(aa, cc); rotated = curve.Rotate(axis, Math.PI / 2.0); } else if (null != location) { XYZ aa = location.Point; XYZ cc = new XYZ(aa.X, aa.Y, aa.Z + 10); Line axis = Line.CreateBound(aa, cc); rotated = location.Rotate(axis, Math.PI / 2.0); } return(rotated); }
/// <summary> /// if the element location is based on LocationPoint or LocationCurve, return its coordinates /// </summary> /// <param name="elem"></param> /// <returns></returns> private string getCoordinateString(Element elem) { string position = "default"; LocationPoint locationPoint = elem.Location as LocationPoint; if (locationPoint != null) { XYZ point = locationPoint.Point as XYZ; position = "Point: " + point.ToString(); } LocationCurve locationCurve = elem.Location as LocationCurve; if (locationCurve != null) { Line locationLine = locationCurve.Curve as Line; //convert the location to a line XYZ startPoint = locationLine.GetEndPoint(0); //get the first end point XYZ endPoint = locationLine.GetEndPoint(1); //get the second end point //link the coordinates of two end points as the return value position = "Start Point: " + startPoint.ToString() + ", End Point: " + endPoint.ToString(); } return(position); }
/// <summary> /// Show the location information of the given element. /// The location can be a LocationPoint (e.g., furniture) /// or LocationCurve (e.g., wall). /// </summary> public void ShowLocation(Element e) { string s = "Location Information: " + "\n" + "\n"; Location loc = e.Location; if (loc is LocationPoint) { // (1) we have a location point LocationPoint locPoint = (LocationPoint)loc; XYZ pt = locPoint.Point; double r = locPoint.Rotation; s += "LocationPoint" + "\n"; s += "Point = " + PointToString(pt) + "\n"; s += "Rotation = " + r.ToString() + "\n"; } else if (loc is LocationCurve) { // (2) we have a location curve LocationCurve locCurve = (LocationCurve)loc; Curve crv = locCurve.Curve; s += "LocationCurve" + "\n"; s += "EndPoint(0)/Start Point = " + PointToString(crv.GetEndPoint(0)) + "\n"; s += "EndPoint(1)/End point = " + PointToString(crv.GetEndPoint(1)) + "\n"; s += "Length = " + crv.Length.ToString() + "\n"; // Location Curve also has property JoinType at the end s += "JoinType(0) = " + locCurve.get_JoinType(0).ToString() + "\n"; s += "JoinType(1) = " + locCurve.get_JoinType(1).ToString() + "\n"; } TaskDialog.Show("Show Location", s); }
/// <summary> /// The function set value to rotation of the beams and braces /// and rotate columns. /// </summary> public void RotateElement() { Transaction transaction = new Transaction(m_revit.ActiveUIDocument.Document, "RotateElement"); transaction.Start(); try { ElementSet selection = new ElementSet(); foreach (ElementId elementId in m_revit.ActiveUIDocument.Selection.GetElementIds()) { selection.Insert(m_revit.ActiveUIDocument.Document.GetElement(elementId)); } foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance familyComponent = e as FamilyInstance; if (familyComponent == null) { //is not a familyInstance continue; } // if be familyInstance,judge the types of familyInstance if (StructuralType.Beam == familyComponent.StructuralType || StructuralType.Brace == familyComponent.StructuralType) { // selection is a beam or Brace ParameterSetIterator paraIterator = familyComponent.Parameters.ForwardIterator(); paraIterator.Reset(); while (paraIterator.MoveNext()) { object para = paraIterator.Current; Parameter objectAttribute = para as Parameter; //set generic property named "Cross-Section Rotation" if (objectAttribute.Definition.Name.Equals(AngleDefinitionName)) { Double originDegree = objectAttribute.AsDouble(); double rotateDegree = m_receiveRotationTextBox * Math.PI / 180; if (!m_isAbsoluteChecked) { // absolute rotation rotateDegree += originDegree; } objectAttribute.Set(rotateDegree); // relative rotation } } } else if (StructuralType.Column == familyComponent.StructuralType) { // rotate a column Autodesk.Revit.DB.Location columnLocation = familyComponent.Location; // get the location object LocationPoint pointLocation = columnLocation as LocationPoint; Autodesk.Revit.DB.XYZ insertPoint = pointLocation.Point; // get the location point double temp = pointLocation.Rotation; //existing rotation Autodesk.Revit.DB.XYZ directionPoint = new Autodesk.Revit.DB.XYZ(0, 0, 1); // define the vector of axis Line rotateAxis = Line.CreateUnbound(insertPoint, directionPoint); double rotateDegree = m_receiveRotationTextBox * Math.PI / 180; // rotate column by rotate method if (m_isAbsoluteChecked) { rotateDegree -= temp; } bool rotateResult = pointLocation.Rotate(rotateAxis, rotateDegree); if (rotateResult == false) { TaskDialog.Show("Revit", "Rotate Failed."); } } } transaction.Commit(); } catch (Exception ex) { TaskDialog.Show("Revit", "Rotate failed! " + ex.Message); transaction.RollBack(); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { Autodesk.Revit.UI.UIApplication revit = commandData.Application; m_revit = revit; RotateFramingObjectsForm displayForm = new RotateFramingObjectsForm(this); displayForm.StartPosition = FormStartPosition.CenterParent; ElementSet selection = new ElementSet(); foreach (ElementId elementId in revit.ActiveUIDocument.Selection.GetElementIds()) { selection.Insert(revit.ActiveUIDocument.Document.GetElement(elementId)); } bool isSingle = true; //selection is single object bool isAllFamilyInstance = true; //all is not familyInstance // There must be beams, braces or columns selected if (selection.IsEmpty) { // nothing selected message = "Please select some beams, braces or columns."; return(Autodesk.Revit.UI.Result.Failed); } else if (1 != selection.Size) { isSingle = false; try { if (DialogResult.OK != displayForm.ShowDialog()) { return(Autodesk.Revit.UI.Result.Cancelled); } } catch (Exception) { return(Autodesk.Revit.UI.Result.Failed); } // return Autodesk.Revit.UI.Result.Succeeded; // more than one object selected } // if the selected elements are familyInstances, try to get their existing rotation foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance familyComponent = e as FamilyInstance; if (familyComponent != null) { if (StructuralType.Beam == familyComponent.StructuralType || StructuralType.Brace == familyComponent.StructuralType) { // selection is a beam or brace string returnValue = this.FindParameter(AngleDefinitionName, familyComponent); displayForm.rotationTextBox.Text = returnValue.ToString(); } else if (StructuralType.Column == familyComponent.StructuralType) { // selection is a column Location columnLocation = familyComponent.Location; LocationPoint pointLocation = columnLocation as LocationPoint; double temp = pointLocation.Rotation; string output = (Math.Round(temp * 180 / (Math.PI), 3)).ToString(); displayForm.rotationTextBox.Text = output; } else { // other familyInstance can not be rotated message = "It is not a beam, brace or column."; elements.Insert(familyComponent); return(Autodesk.Revit.UI.Result.Failed); } } else { if (isSingle) { message = "It is not a FamilyInstance."; elements.Insert(e); return(Autodesk.Revit.UI.Result.Failed); } // there is some objects is not familyInstance message = "They are not FamilyInstances"; elements.Insert(e); isAllFamilyInstance = false; } } if (isSingle) { try { if (DialogResult.OK != displayForm.ShowDialog()) { return(Autodesk.Revit.UI.Result.Cancelled); } } catch (Exception) { return(Autodesk.Revit.UI.Result.Failed); } } if (isAllFamilyInstance) { return(Autodesk.Revit.UI.Result.Succeeded); } else { //output error information return(Autodesk.Revit.UI.Result.Failed); } }
public async Task <IHttpActionResult> Manage(int id, UserDTO userDTO) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Locations location = new Locations(); var user = new ApplicationUser(); //string profileImage = string.Empty; user = await UserManager.FindByIdAsync(id); if (!string.IsNullOrEmpty(userDTO.ProfileImage)) { string ImageName = FileConverter.UploadFileToFileFolder(userDTO.ProfileImage, "ProfileImages"); user.ProfileImage = ImageName; } //if (string.IsNullOrEmpty(userDTO.ProfileImage)) //{ // profileImage = FileConverter.UploadFileToFileFolder(userDTO.ProfileImage, "ProfileImages"); //} if (!String.IsNullOrEmpty(userDTO.UserName)) { user.UserName = userDTO.UserName; } user.GenderId = userDTO.GenderId; if (!String.IsNullOrEmpty(userDTO.MobileNumber)) { user.PhoneNumber = userDTO.MobileNumber; } if (!String.IsNullOrEmpty(userDTO.Email)) { user.Email = userDTO.Email; } if (!String.IsNullOrEmpty(userDTO.Description)) { user.Description = userDTO.Description; } //user.ProfileImage = profileImage; if (!String.IsNullOrEmpty(userDTO.Latitude) && !String.IsNullOrEmpty(userDTO.Longitude)) { var point = LocationPoint.CreatePoint(Convert.ToDouble(userDTO.Latitude), Convert.ToDouble(userDTO.Longitude)); location.LocationName = userDTO.LocationName; location.LocationGeography = point; location.RowStatus = true; location.CreatedDate = DateTime.UtcNow; } Locations rs; bool locationAvailable = ExtentionMethods.IsLocationAvalable(location.LocationName); if (locationAvailable != false) { rs = await ExtentionMethods.AddLocationAsync(location); user.LocationId = rs.LocationId; } else { rs = ExtentionMethods.FindLocationAsync(location.LocationName); if (rs != null) { user.LocationId = rs.LocationId; } } IdentityResult result = await UserManager.UpdateAsync(user); if (result.Succeeded) { return(Ok(new { Code = "200", Message = "Registration Successfully ", ID = user.Id })); } if (!result.Succeeded) { return(GetErrorResult(result)); } return(Ok()); }
static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); DateTime datetimeNow = DateTime.Now; DataTable dbTbl = new DataTable("houses71dd"); OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\home91\Downloads\fias_dbf;Extended Properties=dBASE IV;"); dbConn.Open(); string whereString = "ADDROB71.POSTALCODE in ('300001','300004','300012','300026','300021','300016','300027','300010','300053')"; if (args.Length > 0) { whereString = args[0]; } string sqlSelect = $"select HOUSE71.HOUSEGUID, ADDROB71.PARENTGUID, ADDROB71.AOGUID, ADDROB71.FORMALNAME, ADDROB71.SHORTNAME, HOUSE71.HOUSENUM, ADDROB71.ENDDATE, HOUSE71.ENDDATE from ADDROB71, HOUSE71 where ADDROB71.AOGUID = HOUSE71.AOGUID and {whereString}"; //string sqlSelect = $"select ADDROB71.PARENTGUID, ADDROB71.AOGUID, ADDROB71.FORMALNAME, ADDROB71.SHORTNAME, HOUSE71.HOUSENUM from ADDROB71, HOUSE71 where ADDROB71.AOGUID = HOUSE71.AOGUID and ADDROB71.ENDDATE > {datetimeNow.ToString("dd/MM/yyyy")} and HOUSE71.ENDDATE > {datetimeNow.ToString("dd/MM/yyyy")} and ADDROB71.POSTALCODE = '300057'"; //string sqlSelect = $"select * from ADDROB71, HOUSE71 where ADDROB71.AOGUID = HOUSE71.AOGUID and ADDROB71.ENDDATE > {datetimeNow.ToString("MM/dd/yyyy")} and HOUSE71.ENDDATE > {datetimeNow.ToString("MM/dd/yyyy")} and ADDROB71.POSTALCODE = '300057'"; //string sqlSelect = $"select * from ADDROB71, HOUSE71 where ADDROB71.AOGUID = HOUSE71.AOGUID and ADDROB71.ENDDATE > @value1 and HOUSE71.ENDDATE > @value1 and ADDROB71.POSTALCODE = '300057'"; OleDbCommand dbComm = new OleDbCommand(sqlSelect, dbConn); //dbComm.Parameters.AddWithValue("@value1", datetimeNow); //dbComm.Parameters.AddWithValue("@value2", datetimeNow); OleDbDataAdapter dbAdap = new OleDbDataAdapter(dbComm); dbAdap.Fill(dbTbl); dbTbl.Columns.Add("ADDRFULL", typeof(String)); dbTbl.Columns.Add("POINTLAT", typeof(Double)); dbTbl.Columns.Add("POINTLNG", typeof(Double)); Console.WriteLine($"Count {dbTbl.Rows.Count} rows from DB."); dbTbl.Rows.Cast <DataRow>().All(r => { if (((DateTime)r["ADDROB71.ENDDATE"] < datetimeNow) || ((DateTime)r["HOUSE71.ENDDATE"] < datetimeNow)) { r.Delete(); Console.WriteLine($"{dbTbl.Rows.IndexOf(r)}/{dbTbl.Rows.Count} DELETE UNUSED"); return(true); } string SFN = $"{ GetShortAndFormalNames(dbConn, r["PARENTGUID"].ToString())}, {r["SHORTNAME"]} {r["FORMALNAME"]} {r["HOUSENUM"]}"; var geocoder = new YandexGeocoder { Apikey = "a1d0badd-df1d-4814-8d43-eab723c50133", SearchQuery = SFN, Results = 1, LanguageCode = LanguageCode.en_RU }; var getRes = geocoder.GetResults(); if (getRes.Count == 0) { r.Delete(); Console.WriteLine($"{dbTbl.Rows.IndexOf(r)}/{dbTbl.Rows.Count} DELETE NO GEOCODE"); return(true); } LocationPoint pnt = getRes[0].Point; Console.WriteLine($"{dbTbl.Rows.IndexOf(r)}/{dbTbl.Rows.Count} {SFN} [ {pnt.Longitude}, {pnt.Latitude} ]"); r["ADDRFULL"] = SFN; r["POINTLAT"] = pnt.Latitude; r["POINTLNG"] = pnt.Longitude; return(true); }); dbTbl.AcceptChanges(); Console.WriteLine($"Count {dbTbl.Rows.Count} rows is live."); //string TBLNAME_DISDUR = $"DISDUR{ datetimeNow.ToString("ddMMyyyy")}"; string TBLNAME_DISDUR = Path.GetRandomFileName(); { OleDbCommand cmd = dbConn.CreateCommand(); //cmd.CommandText = $"CREATE TABLE {TBLNAME_DISDUR} (SRC_HOUSEGUID CHAR(36), DST_HOUSEGUID CHAR(36), DISTANCE DECIMAL, DURATION DECIMAL)"; cmd.CommandText = $"CREATE TABLE {TBLNAME_DISDUR} (WHENQUERY DATETIME, SRC_LAT DECIMAL, SRC_LNG DECIMAL, DST_LAT DECIMAL, DST_LNG DECIMAL, DISTANCE DECIMAL, DURATION DECIMAL)"; cmd.ExecuteNonQuery(); } var osrm = new Osrm5x("http://router.project-osrm.org/", "v1", "car"); //var result = osrm.Nearest(new Location(52.4224, 13.333086)); //NearestResponse result = TryNearest(osrm); //result.Waypoints.All(w => //{ // Console.WriteLine($"{w.Location.Longitude},{w.Location.Latitude}"); // return true; //}); dbTbl.Rows.Cast <DataRow>().All(rowSrc => { dbTbl.Rows.Cast <DataRow>().All(rowDst => { var locations = new Location[] { new Location((Double)rowSrc["POINTLAT"], (Double)rowSrc["POINTLNG"]), new Location((Double)rowDst["POINTLAT"], (Double)rowDst["POINTLNG"]), }; var routeResult = TryRoute(osrm, locations); Console.WriteLine($"{dbTbl.Rows.IndexOf(rowSrc)}/{dbTbl.Rows.IndexOf(rowDst)} {rowSrc["ADDRFULL"]} > {rowDst["ADDRFULL"]} DIS {routeResult.Routes[0].Distance} DUR {routeResult.Routes[0].Duration}"); if ((routeResult.Routes[0].Distance < 3000.0) && (routeResult.Routes[0].Duration < 600.0)) { OleDbCommand cmd = dbConn.CreateCommand(); //cmd.CommandText = $"INSERT INTO {TBLNAME_DISDUR} VALUES ('{rowSrc["HOUSEGUID"]}', '{rowDst["HOUSEGUID"]}', {routeResult.Routes[0].Distance}, {routeResult.Routes[0].Duration})"; cmd.CommandText = $"INSERT INTO {TBLNAME_DISDUR} VALUES ({DateTime.Now.ToShortDateString()}, {(Double)rowSrc["POINTLAT"]}, {(Double)rowSrc["POINTLNG"]}, {(Double)rowDst["POINTLAT"]}, {(Double)rowDst["POINTLNG"]}, {routeResult.Routes[0].Distance}, {routeResult.Routes[0].Duration})"; cmd.ExecuteNonQuery(); } return(true); }); return(true); }); dbConn.Close(); dbConn.Dispose(); dbTbl.WriteXml("house71dd.xml"); }
private void OK(object sender, RoutedEventArgs e) { if (txtround.Text == "") { TaskDialog.Show("ERROR", " Please Enter The Round Value"); return; } if (Frame.IsChecked == false && Walls.IsChecked == false && Column.IsChecked == false) { TaskDialog.Show("ERROR", " Please Select Element Types"); return; } Hide(); Document doc = Singleton.Instance.RevitData.Document; Reference gridrefX = Singleton.Instance.RevitData.Selection.PickObject(ObjectType.Element, new GridSelectionFilter(), "Select The First Grid"); Autodesk.Revit.DB.Grid gridX = doc.GetElement(gridrefX) as Autodesk.Revit.DB.Grid; Reference gridrefY = Singleton.Instance.RevitData.Selection.PickObject(ObjectType.Element, new GridSelectionFilter(), "Select The Second Grid"); Autodesk.Revit.DB.Grid gridY = doc.GetElement(gridrefY) as Autodesk.Revit.DB.Grid; switch (th) { case th1: { List <Reference> elemreflist = Singleton.Instance.RevitData.Selection.PickObjects(ObjectType.Element, new BeamSelectionFilter(), "Select Beams") as List <Reference>; List <Element> elemlist = elemreflist.Select(x => Singleton.Instance.RevitData.Document.GetElement(x) as Autodesk.Revit.DB.Element).ToList(); elemlist.ForEach(x => Singleton.Instance.WPFData.Elements.Add(x)); using (Transaction transactionbeam = new Transaction(doc)) { transactionbeam.Start("Beam Moving"); foreach (Element elem in elemlist) { LocationCurve elemcurve = elem.Location as LocationCurve; Autodesk.Revit.DB.Line elemline = elemcurve.Curve as Autodesk.Revit.DB.Line; Autodesk.Revit.DB.Line gridlineX = gridX.Curve as Autodesk.Revit.DB.Line; Autodesk.Revit.DB.Line gridlineY = gridY.Curve as Autodesk.Revit.DB.Line; //Kiểm tra và đặt tên Grid, GridX song song với Location.Curve - Line, Grid Y vuông góc,... if (Geometry.GeomUtil.IsSameOrOppositeDirection(elemline.Direction, gridlineY.Direction)) { gridX = doc.GetElement(gridrefY) as Autodesk.Revit.DB.Grid; gridY = doc.GetElement(gridrefX) as Autodesk.Revit.DB.Grid; gridlineX = gridX.Curve as Autodesk.Revit.DB.Line; gridlineY = gridY.Curve as Autodesk.Revit.DB.Line; } double movedis = Command.GetMoveDistance(elemline, gridX, roundto); // Move dầm phương song song if (movedis > precision) { XYZ movevector1 = new XYZ(-elemline.Direction.Y, elemline.Direction.X, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); elem.Location.Move(movevector1); if (Math.Abs(Command.GetMoveDistance(elemline, gridX, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemline, gridX, roundto) % roundto) < roundto - precision) { elem.Location.Move(-2 * movevector1); } } movedis = Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto); if (movedis >= precision) { XYZ movevector2 = new XYZ(elemline.Direction.X, elemline.Direction.Y, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); elem.Location.Move(movevector2); if (Math.Abs(Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto) % roundto) < (roundto - precision)) { elem.Location.Move(-2 * movevector2); } } } transactionbeam.Commit(); } break; } case th2: { List <Reference> elemreflist = Singleton.Instance.RevitData.Selection.PickObjects(ObjectType.Element, new StructuralColumnFilter(), "Select Columns") as List <Reference>; List <Element> elemlist = elemreflist.Select(x => Singleton.Instance.RevitData.Document.GetElement(x) as Autodesk.Revit.DB.Element).ToList(); elemlist.ForEach(x => Singleton.Instance.WPFData.Elements.Add(x)); using (Transaction transactioncolumn = new Transaction(doc)) { transactioncolumn.Start("Column Moving "); foreach (Element elem in elemlist) { LocationPoint elemcurve = elem.Location as LocationPoint; Autodesk.Revit.DB.Line gridlineX = gridX.Curve as Autodesk.Revit.DB.Line; Autodesk.Revit.DB.Line gridlineY = gridY.Curve as Autodesk.Revit.DB.Line; double movedis = Command.GetMoveDistance(elemcurve.Point, gridX, roundto); if (movedis > precision) { XYZ movevector1 = new XYZ(-gridlineX.Direction.Y, gridlineX.Direction.X, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); elem.Location.Move(movevector1); if (Math.Abs(Command.GetMoveDistance(elemcurve.Point, gridX, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemcurve.Point, gridX, roundto) % roundto) < roundto - precision) { elem.Location.Move(-2 * movevector1); } } movedis = Command.GetMoveDistance(elemcurve.Point, gridY, roundto); if (movedis >= precision) { XYZ movevector2 = new XYZ(-gridlineY.Direction.Y, gridlineY.Direction.X, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); //TaskDialog.Show("asas", Command.GetMoveDistance(elemcurve.Point, gridY, roundto).ToString()); elem.Location.Move(movevector2); //TaskDialog.Show("asas", Command.GetMoveDistance(elemcurve.Point, gridY, roundto).ToString()); if (Math.Abs(Command.GetMoveDistance(elemcurve.Point, gridY, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemcurve.Point, gridY, roundto) % roundto) < (roundto - precision)) { elem.Location.Move(-2 * movevector2); } } } transactioncolumn.Commit(); } break; } case th3: { List <Reference> elemreflist = Singleton.Instance.RevitData.Selection.PickObjects(ObjectType.Element, new StructuralWallFilter(), "Select Walls") as List <Reference>; List <Element> elemlist = elemreflist.Select(x => Singleton.Instance.RevitData.Document.GetElement(x) as Autodesk.Revit.DB.Element).ToList(); elemlist.ForEach(x => Singleton.Instance.WPFData.Elements.Add(x)); using (Transaction transactionwall = new Transaction(doc)) { transactionwall.Start("Walls Moving"); foreach (Element elem in elemlist) { LocationCurve elemcurve = elem.Location as LocationCurve; Autodesk.Revit.DB.Line elemline = elemcurve.Curve as Autodesk.Revit.DB.Line; Autodesk.Revit.DB.Line gridlineX = gridX.Curve as Autodesk.Revit.DB.Line; Autodesk.Revit.DB.Line gridlineY = gridY.Curve as Autodesk.Revit.DB.Line; if (Geometry.GeomUtil.IsSameOrOppositeDirection(elemline.Direction, gridlineY.Direction)) { gridX = doc.GetElement(gridrefY) as Autodesk.Revit.DB.Grid; gridY = doc.GetElement(gridrefX) as Autodesk.Revit.DB.Grid; gridlineX = gridX.Curve as Autodesk.Revit.DB.Line; gridlineY = gridY.Curve as Autodesk.Revit.DB.Line; } double movedis = Command.GetMoveDistance(elemline, gridX, roundto); if (movedis > precision) { XYZ movevector1 = new XYZ(-elemline.Direction.Y, elemline.Direction.X, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); elem.Location.Move(movevector1); if (Math.Abs(Command.GetMoveDistance(elemline, gridX, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemline, gridX, roundto) % roundto) < roundto - precision) { elem.Location.Move(-2 * movevector1); } } movedis = Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto); if (movedis >= precision) { XYZ movevector2 = new XYZ(elemline.Direction.X, elemline.Direction.Y, 0).Normalize() * Geometry.GeomUtil.milimeter2Feet(movedis); elem.Location.Move(movevector2); if (Math.Abs(Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto) % roundto) > precision && Math.Abs(Command.GetMoveDistance(elemline.GetEndPoint(0), gridY, roundto) % roundto) < (roundto - precision)) { elem.Location.Move(-2 * movevector2); } } } transactionwall.Commit(); } break; } } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet highlightElements) { /* * * // retrieve all link elements: * * Document doc = app.ActiveUIDocument.Document; * List<Element> links = GetElements( * BuiltInCategory.OST_RvtLinks, * typeof( Instance ), app, doc ); * * // determine the link paths: * * DocumentSet docs = app.Documents; * int n = docs.Size; * Dictionary<string, string> paths * = new Dictionary<string, string>( n ); * * foreach( Document d in docs ) * { * string path = d.PathName; * int i = path.LastIndexOf( "\\" ) + 1; * string name = path.Substring( i ); * paths.Add( name, path ); * } */ // Retrieve lighting fixture element // data from linked documents: List <ElementData> data = new List <ElementData>(); UIApplication app = commandData.Application; DocumentSet docs = app.Application.Documents; foreach (Document doc in docs) { FilteredElementCollector a = Util.GetElementsOfType(doc, typeof(FamilyInstance), BuiltInCategory.OST_LightingFixtures); foreach (FamilyInstance e in a) { string name = e.Name; LocationPoint lp = e.Location as LocationPoint; if (null != lp) { XYZ p = lp.Point; data.Add(new ElementData(doc.PathName, e.Name, e.Id.IntegerValue, p.X, p.Y, p.Z, e.UniqueId)); } } } // Display data: using (CmdLinkedFileElementsForm dlg = new CmdLinkedFileElementsForm(data)) { dlg.ShowDialog(); } return(Result.Succeeded); }
protected void PlaceOpeningFamilies(IEnumerable <Intersection> intersections) { var log_param = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров размеров"); var log_id = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров id"); var log_level = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка параметров уровня"); var log_cut = LoggingMachine.NewLog("Добавление отверстий", intersections.Select(x => x.Id), "Ошибка вырезания"); bool unpinFlag = false; bool unpinAsked = false; foreach (Intersection i in intersections) { Element holeElement; if (IsExisted(i)) { holeElement = ExistingOpenings.Where(x => x.LookupParameter("ТеррНИИ_Идентификатор").AsString() == i.Id.ToString()).First(); LocationPoint loc = holeElement.Location as LocationPoint; XYZ vec = new XYZ(i.InsertionPoint.X, i.InsertionPoint.Y, i.Level.ProjectElevation) - loc.Point; if (!unpinAsked) { TaskDialog td = new TaskDialog("Обнаружены закрепленные"); td.MainInstruction = "В отчете найдены отверстия, которые уже существуют в проекте и которые закреплены"; td.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Открепить и обновить отверстия"); td.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Оставить без изменений"); var res = td.Show(); unpinFlag = res == TaskDialogResult.CommandLink1; unpinAsked = true; } if (holeElement.Pinned && unpinFlag) { holeElement.Pinned = false; ElementTransformUtils.MoveElement(doc, holeElement.Id, vec); } else if (!holeElement.Pinned) { ElementTransformUtils.MoveElement(doc, holeElement.Id, vec); } } else { holeElement = doc.Create.NewFamilyInstance( new XYZ( i.InsertionPoint.X, i.InsertionPoint.Y, i.Level.Elevation), openingFamilySymbol, i.Level, StructuralType.NonStructural); // поворачиваем на нужную позицию Line axe = Line.CreateUnbound(i.InsertionPoint, XYZ.BasisZ); ElementTransformUtils.RotateElement(doc, holeElement.Id, axe, i.Angle); //делаем вырез в хосте try { if (i.HasHosts) { foreach (var host in i.Hosts) { InstanceVoidCutUtils.AddInstanceVoidCut(doc, host, holeElement); } } } catch { log_cut.AddError(i.Id); } } try { //идентификация holeElement.LookupParameter("ТеррНИИ_Идентификатор")?.Set(i.Id.ToString()); holeElement.LookupParameter("Связанный файл")?.Set(i.Name); } catch { log_id.AddError(i.Id); } try { // задаем параметры holeElement.LookupParameter("ADSK_Отверстие_Ширина").Set(i.HoleWidth); holeElement.LookupParameter("ADSK_Отверстие_Высота").Set(i.HoleHeight); holeElement.LookupParameter("ADSK_Толщина стены").Set(i.HoleDepth); // (временно) работа с отверстиями в кирпиче holeElement.LookupParameter("ТеррНИИ_Отверстие_В кирпиче")?.Set(1); } catch { log_param.AddError(i.Id); } try { // назначаем отметки holeElement.LookupParameter("ADSK_Отверстие_Отметка от этажа").Set(i.LevelOffset); if (i.Level.Elevation == 0) { holeElement.LookupParameter("ADSK_Отверстие_Отметка этажа").Set(0); } else { holeElement.LookupParameter("ADSK_Отверстие_Отметка этажа").Set(i.Level.Elevation); } // обнуляем смещение holeElement.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM).Set(0); } catch { log_level.AddError(i.Id); } } }
/// <summary> /// sort all the rooms by ascending order according their coordinate /// </summary> private bool SortRooms() { LocationPoint tmpPoint = null; LocationPoint roomPoint = null; Room listRoom = null; int result = 0; //a temp variable int amount = m_rooms.Count; //the number of rooms bool flag = false; // sort the rooms according their location point for (int i = 0; i < amount - 1; i++) { Room tmpRoom = m_rooms[i]; for (int j = i + 1; j < amount; j++) { tmpPoint = tmpRoom.Location as LocationPoint; listRoom = m_rooms[j]; roomPoint = listRoom.Location as LocationPoint; // if can't get location point, return false; if (null == tmpPoint || null == roomPoint) { return(false); } // rooms in different level if (tmpPoint.Point.Z > roomPoint.Point.Z) { tmpRoom = listRoom; result = j; // if tmpRoom was changed, set flag to 1 flag = true; } // the two rooms in the same level else if (tmpPoint.Point.Z == roomPoint.Point.Z) { if (tmpPoint.Point.X > roomPoint.Point.X) { tmpRoom = listRoom; result = j; flag = true; } else if (tmpPoint.Point.X == roomPoint.Point.X && tmpPoint.Point.Y > roomPoint.Point.Y) { tmpRoom = listRoom; result = j; flag = true; } } } // if flag equals 1 ,move the room to the front of list if (flag) { Room tempRoom = m_rooms[i]; m_rooms[i] = m_rooms[result]; m_rooms[result] = tempRoom; flag = false; } } return(true); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; List <Element> a = new List <Element>(); if (!Util.GetSelectedElementsOrAll(a, uidoc, typeof(FamilyInstance))) { Selection sel = uidoc.Selection; message = (0 < sel.GetElementIds().Count) ? "Please select some family instances." : "No family instances found."; return(Result.Failed); } FamilyInstance inst = a[0] as FamilyInstance; // Here are two ways to traverse the nested instance geometry. // The first way can get the right position, but can't get the right structure. // The second way can get the right structure, but can't get the right position. // What I want is the right structure and right position. // First way: // In the current project project1.rvt, I can get myFamily3 instance via API, // the class is Autodesk.Revit.Elements.FamilyInstance. // Then i try to get its geometry: Options opt = app.Application.Create.NewGeometryOptions(); GeometryElement geoElement = inst.get_Geometry(opt); //GeometryObjectArray a1 = geoElement.Objects; // 2012 //int n = a1.Size; // 2012 int n = geoElement.Count <GeometryObject>(); // 2013 Debug.Print( "Family instance geometry has {0} geometry object{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); int i = 0; //foreach( GeometryObject o1 in a1 ) // 2012 foreach (GeometryObject o1 in geoElement) // 2013 { GeometryInstance geoInstance = o1 as GeometryInstance; if (null != geoInstance) { // geometry includes one instance, so get its geometry: GeometryElement symbolGeo = geoInstance.SymbolGeometry; //GeometryObjectArray a2 = symbolGeo.Objects; // 2012 //foreach( GeometryObject o2 in a2 ) // 2012 // the symbol geometry contains five solids. // how can I find out which solid belongs to which column? // how to relate the solid to the family instance? foreach (GeometryObject o2 in symbolGeo) { Solid s = o2 as Solid; if (null != s && 0 < s.Edges.Size) { List <XYZ> vertices = new List <XYZ>(); GetVertices(vertices, s); n = vertices.Count; Debug.Print("Solid {0} has {1} vertices{2} {3}", i++, n, Util.DotOrColon(n), Util.PointArrayString(vertices)); } } } } // In the Revit 2009 API, we can use // FamilyInstance.Symbol.Family.Components // to obtain the nested family instances // within the top level family instance. // In the Revit 2010 API, this property has been // removed, since we can iterate through the elements // of a family just like any other document; // cf. What's New in the RevitAPI.chm: #if REQUIRES_REVIT_2009_API ElementSet components = inst.Symbol.Family.Components; n = components.Size; #endif // REQUIRES_REVIT_2009_API Document fdoc = doc.EditFamily(inst.Symbol.Family); #if REQUIRES_REVIT_2010_API List <Element> components = new List <Element>(); fdoc.get_Elements(typeof(FamilyInstance), components); n = components.Count; #endif // REQUIRES_REVIT_2010_API FilteredElementCollector collector = new FilteredElementCollector(fdoc); collector.OfClass(typeof(FamilyInstance)); IList <Element> components = collector.ToElements(); Debug.Print( "Family instance symbol family has {0} component{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n)); foreach (Element e in components) { // there are 3 FamilyInstance: Column, myFamily1, myFamily2 // then we can loop myFamily1, myFamily2 also. // then get all the Column geometry // But all the Column's position is the same, // because the geometry is defined by the Symbol. // Not the actually position in project1.rvt LocationPoint lp = e.Location as LocationPoint; Debug.Print("{0} at {1}", Util.ElementDescription(e), Util.PointString(lp.Point)); } return(Result.Failed); }
// The Execute method for the updater public void Execute(UpdaterData data) { try { Document doc = data.GetDocument(); FamilyInstance window = doc.get_Element(m_windowId) as FamilyInstance; Element section = doc.get_Element(m_sectionId); // iterate through modified elements to find the one we want the section to follow foreach (ElementId id in data.GetModifiedElementIds()) { if (id == m_windowId) { //Let's take this out temporarily. bool enableLookup = false; if (enableLookup) { m_schema = Schema.Lookup(m_schemaId); // (new Guid("{4DE4BE80-0857-4785-A7DF-8A8918851CB2}")); } Entity storedEntity = null; storedEntity = window.GetEntity(m_schema); // // first we look-up X-Y-Z parameters, which we know are set on our windows // and the values are set to the current coordinates of the window instance Field fieldPosition = m_schema.GetField("Position"); XYZ oldPosition = storedEntity.Get <XYZ>(fieldPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES); TaskDialog.Show("Old position", oldPosition.ToString()); LocationPoint lp = window.Location as LocationPoint; XYZ newPosition = lp.Point; // XYZ has operator overloads XYZ translationVec = newPosition - oldPosition; // move the section by the same vector if (!translationVec.IsZeroLength()) { ElementTransformUtils.MoveElement(doc, section.Id, translationVec); } TaskDialog.Show("Moving", "Moving"); // Lookup the normal vector (i,j,we assume k=0) Field fieldOrientation = m_schema.GetField("Orientation"); // Establish the old and new orientation vectors XYZ oldNormal = storedEntity.Get <XYZ>(fieldOrientation, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES); XYZ newNormal = window.FacingOrientation; // If different, rotate the section by the angle around the location point of the window double angle = oldNormal.AngleTo(newNormal); // Need to adjust the rotation angle based on the direction of rotation (not covered by AngleTo) XYZ cross = oldNormal.CrossProduct(newNormal).Normalize(); double sign = 1.0; if (!cross.IsAlmostEqualTo(XYZ.BasisZ)) { sign = -1.0; } angle *= sign; if (Math.Abs(angle) > 0) { Line axis = doc.Application.Create.NewLineBound(newPosition, newPosition + XYZ.BasisZ); ElementTransformUtils.RotateElement(doc, section.Id, axis, angle); } // update the parameters on the window instance (to be the current position and orientation) storedEntity.Set <XYZ>(fieldPosition, newPosition, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES); storedEntity.Set <XYZ>(fieldOrientation, newNormal, DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES); window.SetEntity(storedEntity); } } } catch (System.Exception ex) { TaskDialog.Show("Exception", ex.ToString()); } return; }
private void changeLocation(LocationPoint newLocationPoint) { positions.RemoveAll(p => p.Identifier == newLocationPoint.Identifier); positions.Add(new LocationPoint() { Identifier = newLocationPoint.Identifier, X = newLocationPoint.X, Y = newLocationPoint.Y }); drawLocations(); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { Selection selection = uidoc.Selection; // Pick a light fixture. var pickedLightReference = selection.PickObject( ObjectType.Element, new LightPickFilter(), "Please select lighting fixture to place"); if (null == pickedLightReference) { return(Result.Failed); } // Get Family Instance of the selected light reference. FamilyInstance lightFamilyInstance = doc.GetElement(pickedLightReference) as FamilyInstance; // Get FamilySymbol of the family instance. if (lightFamilyInstance == null) { return(Result.Failed); } FamilySymbol lightFamilySymbol = lightFamilyInstance.Symbol; // Determine this family's placement type. // This is an important step towards determining // which NewFamilyInstance overload to use to // place new instances of it. FamilyPlacementType placementType = lightFamilySymbol.Family .FamilyPlacementType; // Placement type is WorkPlaneBased, so determine // the host face that defines the work plane. Reference hostFace = lightFamilyInstance.HostFace; // Prompt for placement point of copy. XYZ placeXyzPoint = selection.PickPoint( "Select point to place new light:"); // The location point gives Z elevation value. LocationPoint lp = lightFamilyInstance.Location as LocationPoint; // Assuming the ceiling is horizontal, set // the location point Z value for the copy // equal to the original. placeXyzPoint = new XYZ(placeXyzPoint.X, placeXyzPoint.Y, lp.Point.Z); using (var trans = new Transaction(doc)) { trans.Start("LightArray"); FamilyInstance lightFamilyInstance2 = doc.Create.NewFamilyInstance( hostFace, placeXyzPoint, XYZ.BasisX, lightFamilySymbol); trans.Commit(); } } catch (OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } return(Result.Succeeded); }
private void Stream(ArrayList data, LocationPoint locPt) { data.Add(new Snoop.Data.ClassSeparator(typeof(LocationPoint))); data.Add(new Snoop.Data.Xyz("Point", locPt.Point)); // some point location instance do not support the rotation property and throw exception here. try { data.Add(new Snoop.Data.Angle("Rotation", locPt.Rotation)); } catch (System.Exception ex) { data.Add(new Snoop.Data.String("Rotation", ex.Message)); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Hello World //TaskDialog.Show("VL title", "VL says Hello Revit"); var uiApp = commandData.Application; var app = commandData.Application.Application; var uiDoc = commandData.Application.ActiveUIDocument; var doc = commandData.Application.ActiveUIDocument.Document; #region 放置类型为"0762*2032 mm"的门 //首先通过类型过滤出 类型为门的族类型,找到名称相同的 string doorTypeName = "0762*2032 mm"; FamilySymbol doorType = null; var filter = new LogicalAndFilter( new ElementCategoryFilter(BuiltInCategory.OST_Doors), new ElementClassFilter(typeof(FamilySymbol)) ); var collector = new FilteredElementCollector(doc).WherePasses(filter); bool symbolFound = collector.FirstOrDefault(c => c.Name == doorTypeName) != null; //如果没有则通过文件加载族 if (symbolFound) { doorType = collector.FirstOrDefault(c => c.Name == doorTypeName) as FamilySymbol; } else { string file = @"familyFilePath"; Family family; if (doc.LoadFamily(file, out family)) { var validType = family.GetValidTypes().FirstOrDefault(c => { var symbol = (doc.GetElement(c) as FamilySymbol); if (symbol != null && symbol.Name == doorTypeName) { return(true); } return(false); }); if (validType != null) { doorType = doc.GetElement(validType) as FamilySymbol; symbolFound = true; } } } //使用族类型创建门 线性的门是有着LocationCurve的且LocationCurve.Curve为Line的元素 Wall wall = null; if (doorType != null) { Element element = new FilteredElementCollector(doc) .WherePasses(new ElementClassFilter(typeof(Wall))) .FirstOrDefault(c => { var locationCurve = c.Location as LocationCurve; if (locationCurve != null) { var line = locationCurve.Curve as Line; if (line != null) { return(true); } return(false); } return(false); }); if (element != null) { wall = element as Wall; } } //在墙的中心创建一个门 if (wall != null) { var line = (wall.Location as LocationCurve).Curve as Line; var wallLevel = doc.GetElement(wall.LevelId) as Level; XYZ midPoint = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2; var structureType = Autodesk.Revit.DB.Structure.StructuralType.NonStructural; FamilyInstance door = doc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, structureType); } #endregion #region 制墙类型 var wallElementId = 1111; wall = doc.GetElement(new ElementId(wallElementId)) as Wall; if (wall != null) { var wallType = wall.WallType; ElementType duplicatedType = wallType.Duplicate(wall.Name + "duplicated"); } #endregion #region 元素移动 VLTransactionHelper.DelegateTransaction(doc, "创建一根柱子", () => { //Revit文档的创建句柄 Autodesk.Revit.Creation.Document creator = doc.Create; XYZ origin = new XYZ(0, 0, 0); Level level = doc.GetElement(new ElementId(12122)) as Level; FamilySymbol columnType = doc.GetElement(new ElementId(12123)) as FamilySymbol; var structureType = Autodesk.Revit.DB.Structure.StructuralType.Column; FamilyInstance column = creator.NewFamilyInstance(origin, columnType, level, structureType); XYZ newPlace = new XYZ(10, 20, 30); ElementTransformUtils.MoveElement(doc, column.Id, newPlace); return(true); }); #endregion #region ElementTransformUtils //ElementTransformUtils.CopyElement(); //ElementTransformUtils.CopyElements(); //ElementTransformUtils.MirrorElement(); //ElementTransformUtils.MirrorElements(); //ElementTransformUtils.MoveElement(); //ElementTransformUtils.MoveElements(); //ElementTransformUtils.RotateElement(); //ElementTransformUtils.RotateElements(); #endregion #region 元素旋转 VLTransactionHelper.DelegateTransaction(doc, "ElementTransformUtils旋转方法", () => { LocationCurve wallLine = wall.Location as LocationCurve; XYZ p1 = wallLine.Curve.GetEndPoint(0); XYZ p2 = new XYZ(p1.X, p1.Y, 30); Line axis = Line.CreateBound(p1, p2); ElementTransformUtils.RotateElement(doc, wall.Id, axis, Math.PI / 3);//逆时针60° return(true); }); VLTransactionHelper.DelegateTransaction(doc, "LocationCurve,LocationPoint,自带的旋转方法", () => { LocationCurve locationCurve = wall.Location as LocationCurve;//线性坐标自带线 if (locationCurve != null) { Curve curve = locationCurve.Curve; var start = curve.GetEndPoint(0); Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10))); locationCurve.Rotate(axis, Math.PI);//PI=180° } LocationPoint locationPoint = wall.Location as LocationPoint; if (locationPoint != null) { var start = locationPoint.Point; Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10))); locationPoint.Rotate(axis, Math.PI); } return(true); }); #endregion #region 元素镜像 VLTransactionHelper.DelegateTransaction(doc, "元素镜像", () => { Plane plane = new Plane(XYZ.BasisX, XYZ.Zero); if (ElementTransformUtils.CanMirrorElement(doc, wall.Id)) { ElementTransformUtils.MirrorElement(doc, wall.Id, plane); } return(true); }); #endregion #region 元素删除 //var deleteElements = Document.Delete(@ElementIds); #endregion #region 元素组合 VLTransactionHelper.DelegateTransaction(doc, "元素组合", () => { List <ElementId> elementIds = new List <ElementId>() { new ElementId(1000), new ElementId(1001), new ElementId(1002), }; Group group = doc.Create.NewGroup(elementIds); return(true); }); #endregion #region 元素编辑 VLTransactionHelper.DelegateTransaction(doc, "创建参照平面", () => { XYZ bubbleEnd = new XYZ(0, 5, 5); XYZ freeEnd = new XYZ(5, 5, 5); XYZ cutVector = XYZ.BasisY; View view = doc.ActiveView; ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view); referencePlane.Name = "MyReferencePlane"; return(true); }); VLTransactionHelper.DelegateTransaction(doc, "创建参照线,由模型线-转>参照线", () => { ModelCurve modelCurve = doc.GetElement(new ElementId(1000)) as ModelCurve;//ModelCurve模型线 modelCurve.ChangeToReferenceLine(); //modelCurve.IsReferenceLine; return(true); }); VLTransactionHelper.DelegateTransaction(doc, "通过标高创建草图平面,然后在草图平面创建模型线", () => { Level level = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).FirstOrDefault() as Level; Line line = Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 0)); SketchPlane sketchPlane = SketchPlane.Create(doc, level.Id); ModelCurve modelLine = doc.FamilyCreate.NewModelCurve(line, sketchPlane); return(true); }); VLTransactionHelper.DelegateTransaction(doc, "使用拉身体获取相应的草图平面", () => { Extrusion extrusion = doc.GetElement(new ElementId(11212)) as Extrusion; SketchPlane sketchPlane = extrusion.Sketch.SketchPlane; CurveArrArray sketchProfile = extrusion.Sketch.Profile; return(true); }); #endregion #region 族 string tagName = "梁平法_集中标_左对齐"; FamilySymbol tagSymbol = null; //查找族类型 var symbols = new FilteredElementCollector(doc) .WherePasses(new ElementClassFilter(typeof(FamilySymbol))) .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_StructuralFramingTags)); var targetSymbol = symbols.FirstOrDefault(c => c.Name == tagName); if (targetSymbol != null) { tagSymbol = targetSymbol as FamilySymbol; } //空时加载族类型 if (tagSymbol == null) { var symbolFile = @"E:\WorkingSpace\Tasks\0526标注\梁平法_集中标_左对齐.rfa"; Family family; if (doc.LoadFamily(symbolFile, out family)) { foreach (ElementId typeId in family.GetValidTypes()) { var validType = doc.GetElement(typeId) as FamilySymbol; if (validType != null && validType.Name == tagName) { tagSymbol = validType; break; } } } else { TaskDialogShow("加载族文件失败"); } } //如果上述两者获取到了对应的族 if (tagSymbol != null) { //doc.Create.NewFamilyInstance(, tagSymbol); } #endregion #region 建筑建模 VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () => { var levelId = 111; Level level = doc.GetElement(new ElementId(levelId)) as Level; LevelType levelType = doc.GetElement(level.GetTypeId()) as LevelType; return(true); }); #endregion return(Result.Succeeded); }
public GetEventsResult GetEventsAroundPOI(LocationPoint PointOfInterest) { // NOTE! Business logic is properly routed from service layer to business logic layer return BusinessLogicHandler.CaloomMainService_GetEventsAroundPOI(PointOfInterest); }