0% found this document useful (0 votes)
149 views117 pages

New Text Document

This document contains code for working with geographic data and coordinates in AutoCAD. It defines classes for translating between drawing coordinates and latitude/longitude coordinates, inserting geo-location data into a drawing, and calculating properties of polylines and arcs like centroids, areas, and bulges. Methods are provided for starting a transaction to edit the drawing database and for buffering polylines by a given distance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views117 pages

New Text Document

This document contains code for working with geographic data and coordinates in AutoCAD. It defines classes for translating between drawing coordinates and latitude/longitude coordinates, inserting geo-location data into a drawing, and calculating properties of polylines and arcs like centroids, areas, and bulges. Methods are provided for starting a transaction to edit the drawing database and for buffering polylines by a given distance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 117

using System.

IO;
using System.Windows.Forms;
using System;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using GenXCTool.utils;
using System.Collections;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using Polyline = Autodesk.AutoCAD.DatabaseServices.Polyline;
using System.Collections.Generic;
using System.Data.SQLite;
using Autodesk.AutoCAD.ApplicationServices;
using System.Data;

using Exception = System.Exception;


using OpenMode = Autodesk.AutoCAD.DatabaseServices.OpenMode;

using System.Linq;
using System.Net;
using System.Xml;
using Autodesk.AutoCAD.GraphicsInterface;
using Viewport = Autodesk.AutoCAD.DatabaseServices.Viewport;

namespace GenXCTool.Class
{
public class CClass
{

public class Point2


{
public Point3d LatLongFromPoint2(Point3d P)
{

var doc = Application.DocumentManager.MdiActiveDocument;

var ed = doc.Editor;
var db = doc.Database;

var lonlat = TranslateGeoPoint(db, P, true);


var p = new Point3d(lonlat.X, lonlat.Y, 0);

return p;
}

//public Point2d LatLongFromPoint2(Point2d P)


//{
// var doc = Application.DocumentManager.MdiActiveDocument;

// var ed = doc.Editor;
// var db = doc.Database;

// var lonlat = TranslateGeoPoint(db, P, true);


// var p = new Point2d(lonlat.X, lonlat.Y);

// return p;
//}
public Point3d LatLongFromPoint2d(Point3d P)
{
var doc = Application.DocumentManager.MdiActiveDocument;

var ed = doc.Editor;
var db = doc.Database;

var lonlat = TranslateGeoPoint(db, P, true);


var p = new Point3d(lonlat.X, lonlat.Y, 0);

return p;
}

private Point3d TranslateGeoPoint(Database db, Point3d inPt, bool fromDwg)


{
using (var tr = db.TransactionManager.StartOpenCloseTransaction())
{
// Get the drawing's GeoLocation object

var gd = tr.GetObject(db.GeoDataObject, OpenMode.ForRead) as


GeoLocationData;

// Get the output point...


// dwg2lonlat if fromDwg is true,
// lonlat2dwg otherwise

var outPt = (fromDwg ? gd.TransformToLonLatAlt(inPt) :


gd.TransformFromLonLatAlt(inPt));

tr.Commit();

return outPt;
}
}

public Point3d PointFromLatLong(Point3d Point)


{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

// Translate the lat-lon to a drawing point

var dwgPt = TranslateGeoPoint(db, Point, false);


return dwgPt;
}

public Point2d Point2FromLatLon(Point3d Point)


{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

// Translate the lat-lon to a drawing point

var dwgPt = TranslateGeoPoint(db, Point, false);


Point2d p2 = new Point2d(dwgPt.X, dwgPt.Y);

return p2;
}
public string getBetween(string Data, string St, string En)
{
int Start, End;
if (Data.Contains(St) && Data.Contains(En))
{
Start = Data.IndexOf(St, 0) + St.Length;
End = Data.IndexOf(En, Start);
return Data.Substring(Start, End - Start);
}
else
{
return "";
}
}

public void InsertGeoRef(Point3d PC)


{

var doc = Application.DocumentManager.MdiActiveDocument;

if (doc == null)

return;

var ed = doc.Editor;

var db = doc.Database;

var msId = SymbolUtilityServices.GetBlockModelSpaceId(db);

bool hasGeoData = false;

try
{
var gdId = db.GeoDataObject;
hasGeoData = true;
}
catch { }

if (hasGeoData)
{
ed.WriteMessage("\nDrawing already has geo-location data!");

return;
}

var data = new GeoLocationData();

data.BlockTableRecordId = msId;

data.PostToDb();

data.CoordinateSystem = "WORLD-MERCATOR";

data.TypeOfCoordinates = TypeOfCoordinates.CoordinateTypeGrid;
var wcsPt = data.TransformFromLonLatAlt(PC);

data.DesignPoint = wcsPt;

data.ReferencePoint = PC;

ed.Command("_.GEOMAP", "_AERIAL");
}

public class BClass


{
CTransaction CT = new CTransaction();

public double BulgeFromCurve(Curve cv, bool clockwise)


{
double bulge = 0.0;
Arc a = cv as Arc;
if (a != null)
{
double newStart;

if (a.StartAngle > a.EndAngle)


{
newStart = a.StartAngle - 8 * Math.Atan(1);
}
else
{
newStart = a.StartAngle;
}

bulge = Math.Tan((a.EndAngle - newStart) / 4);

if (clockwise)
{
bulge = -bulge;
}
}

return bulge;

}
public Point2d ArcCentroid(Point2d start, Point2d end, Point2d cen, double
tmpArea)
{
double chord = start.GetDistanceTo(end);
double angle = (end - start).Angle;
return Polar2d(cen, angle - (Math.PI / 2.0), (chord * chord * chord) /
(12.0 * tmpArea));
}

public double ArcAlgebricArea(double rad, double ang)


{
return rad * rad * (ang - Math.Sin(ang)) / 2.0;
}
public Point2d Polar2d(Point2d org, double angle, double distance)
{
return org + new Vector2d(distance * Math.Cos(angle), distance *
Math.Sin(angle));
}
public double[] GetArcGeom(Polyline pl, double bulge, int index1, int
index2)
{
CircularArc2d arc = (pl.GetArcSegment2dAt(index1));
double arcRadius = arc.Radius;
Point2d arcCenter = arc.Center;
double arcAngle = 4.0 * Math.Atan(bulge);
double tmpArea = ArcAlgebricArea(arcRadius, arcAngle);
Point2d tmpPoint = ArcCentroid(pl.GetPoint2dAt(index1),
pl.GetPoint2dAt(index2), arcCenter, tmpArea);
return new double[3] { tmpArea, tmpPoint.X, tmpPoint.Y };
}

public Point2d TriangleCentroid(Point2d p0, Point2d p1, Point2d p2)


{
return (p0 + p1.GetAsVector() + p2.GetAsVector()) / 3.0;
}

public double TriangleAlgebricArea(Point2d p0, Point2d p1, Point2d p2)


{
return (((p1.X - p0.X) * (p2.Y - p0.Y)) - ((p2.X - p0.X) * (p1.Y -
p0.Y))) / 2.0;
}
public Point3d GetCentroid(Polyline pl)
{
Point2d p0 = pl.GetPoint2dAt(0);
Point2d cen = new Point2d(0.0, 0.0);
double area = 0.0;
int last = pl.NumberOfVertices - 1;
double tmpArea;
Point2d tmpPoint;

if (pl.GetSegmentType(0) == SegmentType.Arc)
{
double[] datas = GetArcGeom(pl, pl.GetBulgeAt(0), 0, 1);
area = datas[0];
cen = new Point2d(datas[1], datas[2]) * datas[0];
}
for (int i = 1; i < last; i++)
{
tmpArea = TriangleAlgebricArea(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
tmpPoint = TriangleCentroid(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
cen += (tmpPoint * tmpArea).GetAsVector();
area += tmpArea;
if (pl.GetSegmentType(i) == SegmentType.Arc)
{
double[] datas = GetArcGeom(pl, pl.GetBulgeAt(i), i, i + 1);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
}
if (pl.GetSegmentType(last) == SegmentType.Arc)
{
double[] datas = GetArcGeom(pl, pl.GetBulgeAt(last), last, 0);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
cen = cen.DivideBy(area);
Point3d result = new Point3d(cen.X, cen.Y, pl.Elevation);
return result.TransformBy(Matrix3d.PlaneToWorld(pl.Normal));
}
}

public class CTransaction


{
public Editor editor;
public Autodesk.AutoCAD.ApplicationServices.Document document;
public Database database;
public BlockTable blockTable;
public LayerTable layerTable;
public Transaction transaction;
public BlockTableRecord blockTableRecordMe;
public BlockTableRecord blockTableRecordPe;
public DocumentLock documentloc;

public void Start_Trans()


{
document = Application.DocumentManager.MdiActiveDocument;

documentloc = document.LockDocument();

database = document.Database;

transaction = database.TransactionManager.StartTransaction();

blockTable = transaction.GetObject(database.BlockTableId,
OpenMode.ForWrite) as BlockTable;

layerTable = transaction.GetObject(database.LayerTableId,
OpenMode.ForWrite) as LayerTable;

blockTableRecordMe =
transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite)
as BlockTableRecord;

blockTableRecordPe =
transaction.GetObject(blockTable[BlockTableRecord.PaperSpace], OpenMode.ForWrite)
as BlockTableRecord;

editor = document.Editor;
}

public Point3dCollection Buffer(Polyline rute, double dist)


{
Point3dCollection buffer = new Point3dCollection();
List<Polyline> pllist = new List<Polyline>();
if (rute != null)
{

if (dist > 0)
{
DBObjectCollection PloffSet1 = rute.GetOffsetCurves(dist);
rute.ReverseCurve();
DBObjectCollection PloffSet2 = rute.GetOffsetCurves(dist);
rute.ReverseCurve();
Polyline pl1buffer = new Polyline();
Polyline pl2buffer = new Polyline();
foreach (Polyline item in PloffSet1) pl1buffer = item;
foreach (Polyline item in PloffSet2) pl2buffer = item;
//Line ln = new Line(pl1buffer.EndPoint, pl2buffer.EndPoint);
//pl1buffer.JoinEntity(ln);
//pl1buffer.JoinEntity(pl2buffer);
//pl1buffer.Closed = true;
//REVISAR ESTO
//pl2buffer.ReverseCurve();

pllist.Add(pl1buffer);

pllist.Add(pl2buffer);
}
else
{
pllist.Add(rute);
}
foreach (Polyline PlB in pllist)
{
for (int i = 0; i < PlB.NumberOfVertices; i++)
{
buffer.Add(PlB.GetPoint3dAt(i));
if (PlB.GetPoint3dAt(i) !=
PlB.GetPoint3dAt(PlB.NumberOfVertices - 1))
{
if (PlB.GetSegmentType(i).ToString() == "Arc")
{
for (double j =
PlB.GetDistAtPoint(PlB.GetPoint3dAt(i)) + 1; j <
PlB.GetDistAtPoint(PlB.GetPoint3dAt(i + 1)); j++)
{
if (!buffer.Contains(PlB.GetPointAtDist(j)))
{
buffer.Add(PlB.GetPointAtDist(j));
}

}
}
}
}
if (PlB.Closed)
{
if (PlB.GetSegmentType(PlB.NumberOfVertices - 1).ToString()
== "Arc")
{
for (double j =
PlB.GetDistAtPoint(PlB.GetPoint3dAt(PlB.NumberOfVertices - 1)) + 1; j < PlB.Length;
j++)
{
buffer.Add(PlB.GetPointAtDist(j));
}
}
buffer.Add(PlB.EndPoint);
}
}

}
return buffer;

public Point3dCollection Buffer(Polyline rute, double dist, bool Draw)


{
Point3dCollection LBuffer = Buffer(rute, dist);
if (Draw)
{
Polyline pl = new Polyline();
foreach (Point3d item in LBuffer)
{
pl.AddVertexAt(pl.NumberOfVertices, item.Convert2d(new
Plane()), 0, 0, 0);

}
Insert(pl, true);
}

return LBuffer;
}

public void End_Trans()


{
editor.Regen();
transaction.Commit();
transaction.Dispose();
}

public void Insert(Line OB, bool M)


{
if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Hyper(Entity ent, string description, string name, string


sublocation)
{
HyperLinkCollection linkCollection = ent.Hyperlinks;
HyperLink hyperLink = new HyperLink();
hyperLink.Description = description;
hyperLink.Name = name;
hyperLink.SubLocation = sublocation;
linkCollection.Add(hyperLink);
}

public void Insert(Polyline OB, bool M)


{
if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Insert(BlockReference OB)


{
blockTableRecordMe.AppendEntity(OB);
transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Insert(Point3d Location, String Block_Name)


{
if(Verify_Exist_Block(Block_Name))
{
BlockReference Br = new BlockReference(Location,
blockTable[Block_Name]);

blockTableRecordMe.AppendEntity(Br);
transaction.AddNewlyCreatedDBObject(Br, true);
}
else
{
MessageBox.Show("Error When Copying Or Inserting Block");
}
}

public void Insert(BlockReference OB, bool M)


{

string name = OB.IsDynamicBlock ?


((BlockTableRecord)OB.DynamicBlockTableRecord.GetObject(OpenMode.ForRead)).Name :
OB.Name;

BlockTableRecord blockDef =
blockTable[name].GetObject(OpenMode.ForRead) as BlockTableRecord;

if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);

DynamicBlockReferencePropertyCollection pc =
OB.DynamicBlockReferencePropertyCollection;

foreach (ObjectId id2 in blockDef)


{
DBObject obj = id2.GetObject(OpenMode.ForRead);

if (obj is AttributeDefinition)
{
AttributeDefinition attDef = obj as AttributeDefinition;

using (AttributeReference attRef = new AttributeReference())


{
attRef.SetAttributeFromBlock(attDef, OB.BlockTransform);

attRef.Visible = true;

OB.AttributeCollection.AppendAttribute(attRef);
transaction.AddNewlyCreatedDBObject(attRef, true);
}
}
}
}

public void Insert(Circle OB, bool M)


{
if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Insert(MText OB, bool M)


{
OB.Attachment = AttachmentPoint.MiddleCenter;

if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Insert(Viewport OB, bool M)


{
if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);
}

public void Insert(Entity OB, bool M)


{
if (M)
blockTableRecordMe.AppendEntity(OB);
else
blockTableRecordPe.AppendEntity(OB);

transaction.AddNewlyCreatedDBObject(OB, true);

if (OB is BlockReference)
{
BlockReference blockReference = (BlockReference)OB;

string name = blockReference.IsDynamicBlock ?


((BlockTableRecord)blockReference.DynamicBlockTableRecord.GetObject(OpenMode.ForRea
d)).Name : blockReference.Name;

BlockTableRecord blockDef =
blockTable[name].GetObject(OpenMode.ForRead) as BlockTableRecord;

foreach (ObjectId id2 in blockDef)


{
DBObject obj = id2.GetObject(OpenMode.ForRead);

AttributeDefinition attDef = obj as AttributeDefinition;

if ((attDef != null))
{

using (AttributeReference attRef = new


AttributeReference())
{
attRef.SetAttributeFromBlock(attDef,
blockReference.BlockTransform);

attRef.TextString = "";
attRef.Visible = true;

blockReference.AttributeCollection.AppendAttribute(attRef);
transaction.AddNewlyCreatedDBObject(attRef, true);
}
}
}
}

public Entity Get(string Dialog, CTransaction Trans, string Typee)


{
Entity En = null;

PromptSelectionOptions promptPointOptions = new


PromptSelectionOptions();
promptPointOptions.MessageForAdding = (Dialog);
PromptSelectionResult selectLinesFollow =
Trans.editor.GetSelection(promptPointOptions);
if (selectLinesFollow.Status == PromptStatus.OK)
{
foreach (ObjectId Obj in selectLinesFollow.Value.GetObjectIds())
{
DBObject entity = Trans.transaction.GetObject(Obj,
OpenMode.ForWrite);
if (entity.GetType().Name == Typee)
{
En = entity as Polyline;
}
else
{
MessageBox.Show(entity.GetType().Name);
}
}
}

return En;
}

public void End_Trans(bool regen, bool dispose)


{
if (regen) editor.Regen();
transaction.Commit();
if (dispose) transaction.Dispose();
}

public bool Verify_Exist_Block(string Block_Name)


{
bool Find = false;

// Check each block in the block table


foreach (ObjectId BlockTableRecord_Id in blockTable)
{
BlockTableRecord Blocktablerecord =
(BlockTableRecord)transaction.GetObject(BlockTableRecord_Id, OpenMode.ForRead,
false);

// Only add named & non-layout blocks to the copy list


if (!Blocktablerecord.IsAnonymous && !Blocktablerecord.IsLayout &&
Blocktablerecord.Name == Block_Name)
Find = true;
}

if(!Find)
{
if (Copy_Block(Block_Name))
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}

public bool Verify_Exist_Layer(string Layer_Name)


{
CLayer CLAYERS = new CLayer();

bool Find = false;

ArrayList Layers = CLAYERS.GetLayerName();

foreach(string S in Layers)
{
if (S == Layer_Name)
{
Find = true;

}
}

if (!Find)
{
if (Copy_Layer(Layer_Name))
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}

public bool Copy_Block(string Block_Name)


{
CDatabase Db = new CDatabase
{
DataSource = @"C:\GenXCTool\DBS\UpdateCheking.db"
};

System.Data.DataTable Dt = Db.Select("Select * From OneDrive");

string Dir = Dt.Rows[0][0].ToString();

bool RETURN = false;

DocumentCollection Document_Collect = Application.DocumentManager;

Editor EDITOR = Document_Collect.MdiActiveDocument.Editor;

Database Des_DB = Document_Collect.MdiActiveDocument.Database;

Database Sor_Db = new Database(false, true);

try
{

// Get name of DWG from which to copy blocks

// sourceFileName = ed.GetString("\nEnter the name of the source


drawing: ");

//sourceFileName = @"Z:\Desktop\Template 1.6.2.dwg";

// Read the DWG into a side database


Sor_Db.ReadDwgFile(Dir + "/Autocad/Blocks/" + Block_Name + ".dwg",
System.IO.FileShare.Read, true, "");
//MessageBox.Show(Dir + "/Autocad/Blocks/" + Block_Name + ".dwg");

// Create a variable to store the list of block identifiers


ObjectIdCollection Blocks_Id = new ObjectIdCollection();

Autodesk.AutoCAD.DatabaseServices.TransactionManager
Sor_Trans_Manager = Sor_Db.TransactionManager;

using (Transaction Sor_Trans =


Sor_Trans_Manager.StartTransaction())
{

// Open the block table

BlockTable Block_Table =
(BlockTable)Sor_Trans.GetObject(Sor_Db.BlockTableId, OpenMode.ForRead, false);

// Check each block in the block table

foreach (ObjectId Block_Table_Id in Block_Table)


{

BlockTableRecord Block_Table_Record =
(BlockTableRecord)Sor_Trans.GetObject(Block_Table_Id, OpenMode.ForRead, false);

// Only add named & non-layout blocks to the copy list

if (!Block_Table_Record.IsAnonymous && !
Block_Table_Record.IsLayout && Block_Table_Record.Name == Block_Name)
Blocks_Id.Add(Block_Table_Id);

Block_Table_Record.Dispose();

// Copy blocks from source to destination database

IdMapping Mapping = new IdMapping();

Sor_Db.WblockCloneObjects(Blocks_Id, Des_DB.BlockTableId, Mapping,


DuplicateRecordCloning.Replace, false);

EDITOR.WriteMessage("\nCopied " + Blocks_Id.Count.ToString() + "


block definitions to the current drawing.");

RETURN = true;
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
EDITOR.WriteMessage("\nError during copy: " + ex.Message);
RETURN = false;
}

Sor_Db.Dispose();
return RETURN;
}

public bool Copy_Layer(string Layer_Name)


{
bool RETURN = false;

DocumentCollection Document_Collect = Application.DocumentManager;

Editor EDITOR = Document_Collect.MdiActiveDocument.Editor;

var curDb = HostApplicationServices.WorkingDatabase;


string dwgPath = @"Z:\Desktop\Template 1.6.2.dwg";
using (var db = new Database(false, true))
{
db.ReadDwgFile(dwgPath, FileOpenMode.OpenForReadAndAllShare, true,
null);
using (var tr = db.TransactionManager.StartOpenCloseTransaction())
{
var layerTable = (LayerTable)tr.GetObject(db.LayerTableId,
OpenMode.ForRead);
if (!layerTable.Has(Layer_Name))
{
EDITOR.WriteMessage("\nError during copy: " + Layer_Name);

return false;
}
else
{
var ids = new ObjectIdCollection();
ids.Add(layerTable[Layer_Name]);
var mapping = new IdMapping();
db.WblockCloneObjects(ids, curDb.LayerTableId, mapping,
DuplicateRecordCloning.Replace, false);

EDITOR.WriteMessage("\nCopied " + Layer_Name + " Layer


definitions to the current drawing.");

return true;
}
}
}

return RETURN;
}
}

public class CCentroide


{
#region Geometric Center of Polyline
public double BulgeFromCurve(Curve cv, bool clockwise)
{
double bulge = 0.0;
Arc a = cv as Arc;
if (a != null)
{
double newStart;
// The start angle is usually greater than the end,
// as arcs are all counter-clockwise.

// (If it isn't it's because the arc crosses the

// 0-degree line, and we can subtract 2PI from the

// start angle.)
if (a.StartAngle > a.EndAngle)
{
newStart = a.StartAngle - 8 * Math.Atan(1);
}
else
{
newStart = a.StartAngle;
}
// Bulge is defined as the tan of

// one fourth of the included angle

bulge = Math.Tan((a.EndAngle - newStart) / 4);


// If the curve is clockwise, we negate the bulge
if (clockwise)
{
bulge = -bulge;
}
}

return bulge;

public Point3d GetCentroid(Polyline pl)


{
Point2d p0 = pl.GetPoint2dAt(0);
Point2d cen = new Point2d(0.0, 0.0);
double area = 0.0;
double bulge = pl.GetBulgeAt(0);
int last = pl.NumberOfVertices - 1;
double tmpArea;
Point2d tmpPoint;

if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, 0, 1);
area = datas[0];
cen = new Point2d(datas[1], datas[2]) * datas[0];
}
for (int i = 1; i < last; i++)
{
tmpArea = TriangleAlgebricArea(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
tmpPoint = TriangleCentroid(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
cen += (tmpPoint * tmpArea).GetAsVector();
area += tmpArea;
bulge = pl.GetBulgeAt(i);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, i, i + 1);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
}
bulge = pl.GetBulgeAt(last);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, last, 0);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
cen = cen.DivideBy(area);
Point3d result = new Point3d(cen.X, cen.Y, pl.Elevation);
return result.TransformBy(Matrix3d.PlaneToWorld(pl.Normal));
}

public Point2d GetCentroid_2d(Polyline pl)


{
Point2d p0 = pl.GetPoint2dAt(0);
Point2d cen = new Point2d(0.0, 0.0);
double area = 0.0;
double bulge = pl.GetBulgeAt(0);
int last = pl.NumberOfVertices - 1;
double tmpArea;
Point2d tmpPoint;

if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, 0, 1);
area = datas[0];
cen = new Point2d(datas[1], datas[2]) * datas[0];
}
for (int i = 1; i < last; i++)
{
tmpArea = TriangleAlgebricArea(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
tmpPoint = TriangleCentroid(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
cen += (tmpPoint * tmpArea).GetAsVector();
area += tmpArea;
bulge = pl.GetBulgeAt(i);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, i, i + 1);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
}
bulge = pl.GetBulgeAt(last);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, last, 0);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
cen = cen.DivideBy(area);
Point3d result = new Point3d(cen.X, cen.Y, pl.Elevation);
result = result.TransformBy(Matrix3d.PlaneToWorld(pl.Normal));
return new Point2d(result.X, result.Y);
}

private static double[] GetArcGeom(Polyline pl, double bulge, int index1,


int index2)
{
CircularArc2d arc = (pl.GetArcSegment2dAt(index1));
double arcRadius = arc.Radius;
Point2d arcCenter = arc.Center;
double arcAngle = 4.0 * Math.Atan(bulge);
double tmpArea = ArcAlgebricArea(arcRadius, arcAngle);
Point2d tmpPoint = ArcCentroid(pl.GetPoint2dAt(index1),
pl.GetPoint2dAt(index2), arcCenter, tmpArea);
return new double[3] { tmpArea, tmpPoint.X, tmpPoint.Y };
}

private static Point2d TriangleCentroid(Point2d p0, Point2d p1, Point2d p2)


{
return (p0 + p1.GetAsVector() + p2.GetAsVector()) / 3.0;
}

private static double TriangleAlgebricArea(Point2d p0, Point2d p1, Point2d


p2)
{
return (((p1.X - p0.X) * (p2.Y - p0.Y)) - ((p2.X - p0.X) * (p1.Y -
p0.Y))) / 2.0;
}

private static Point2d ArcCentroid(Point2d start, Point2d end, Point2d cen,


double tmpArea)
{
double chord = start.GetDistanceTo(end);
double angle = (end - start).Angle;
return Polar2d(cen, angle - (Math.PI / 2.0), (chord * chord * chord) /
(12.0 * tmpArea));
}

private static double ArcAlgebricArea(double rad, double ang)


{
return rad * rad * (ang - Math.Sin(ang)) / 2.0;
}

private static Point2d Polar2d(Point2d org, double angle, double distance)


{
return org + new Vector2d(distance * Math.Cos(angle), distance *
Math.Sin(angle));
}

#endregion
}

public class CPole


{
/* private string pole_tag = " ";
private string pole_owner = " ";
private string material = " ";
private string pole_class = " ";
private string ground = " ";
private string telco_first_attachment = " ";
private string telco_second_attachment = " ";
private string comcast = " ";
private string catv_second_attachment = " ";
private string streetlight = " ";
private string secondaryneutral = " ";
private string transfer = " ";
private string pole_address_full = " ";

private string proposed_or_existing_1 = " ";


private string bearing_1 = " ";
private string lead_1 = " ";
private string photo = " ";

private int pole_tag_p = 0;


private int pole_owner_p = 0;
private int material_p = 0;
private int pole_class_p = 0;
private int ground_p = 0;
private int telco_first_attachment_p = 0;
private int telco_second_attachment_p = 0;
private int comcast_p = 0;
private int catv_second_attachment_p = 0;
private int streetlight_p = 0;
private int secondaryneutral_p = 0;
private int transfer_p = 0;

private int proposed_or_existing_1_p = 0;


private int bearing_1_p = 0;
private int lead_1_p = 0;
private int photo_p = 0;
private int latitude_p = 0;
private int longitude_p = 0;*/

//public string Pole_Detail(string S, int P)


//{
// try
// {
// string Data = "";
// var reader = new StreamReader(S);
// int lines = 0;

// while (!reader.EndOfStream)
// {
// string[] comas;
// string line = reader.ReadLine();
// string[] values = line.Split(',');

// if (lines == 0)
// for (int c = 0; c < values.Length; c++)
// if (values[c] == "pole_owner")
// pole_owner_p = c;
// else if (values[c] == "material")
// material_p = c;
// else if (values[c] == "pole_class")
// pole_class_p = c;
// else if (values[c] == "ground")
// ground_p = c;
// else if (values[c] == "telco_first_attachment")
// telco_first_attachment_p = c;
// else if (values[c] == "telco_second_attachment")
// telco_second_attachment_p = c;
// else if (values[c] == "comcast")
// comcast_p = c;
// else if (values[c] == "catv_second_attachment")
// catv_second_attachment_p = c;
// else if (values[c] == "streetlight")
// streetlight_p = c;
// else if (values[c] == "secondaryneutral")
// secondaryneutral_p = c;
// else if (values[c] == "transfer" || values[c] ==
"general_notes")
// transfer_p = c;
// else if (values[c] == "pole_tag")
// pole_tag_p = c;

// if (lines == P && P != 0)
// {
// pole_owner = values[pole_owner_p];

// if (pole_tag_p != 0)
// {
// pole_tag = values[pole_tag_p];
// }

// if (pole_owner != "Cross Messenger")


// {
// if(material_p != 0)
// material = values[material_p];

// if(pole_class_p != 0)
// pole_class = values[pole_class_p];

// if (ground_p != 0)
// ground = values[ground_p];

// if(telco_first_attachment_p != 0)
// telco_first_attachment =
values[telco_first_attachment_p];

// if(telco_second_attachment_p != 0)
// telco_second_attachment =
values[telco_second_attachment_p];

// if(comcast_p != 0)
// comcast = values[comcast_p];

// if(catv_second_attachment_p != 0)
// catv_second_attachment =
values[catv_second_attachment_p];

// if(streetlight_p != 0)
// streetlight = values[streetlight_p];

// if(secondaryneutral_p != 0)
// secondaryneutral = values[secondaryneutral_p];

// if(transfer_p != 0)
// transfer = values[transfer_p];

// try
// {
// if (pole_tag != " " && pole_tag != "")
// {
// Data += "Pole#: " +
Convert.ToInt32(pole_tag).ToString();
// }
// }
// catch (Exception)
// {
// Data += pole_tag;
// }

// if (pole_owner == "BST Pole")


// Data += "\n" + "TELCO POLE";
// else
// Data += "\n" + pole_owner;

// if (material != "" && material != " ")


// Data += "\n" + material;

// if (pole_class != " " && pole_class != "")


// {
// comas = pole_class.Split('-');
// pole_class = comas[0] + " - " + comas[1];
// Data += "\n" + material;
// Data += "\n" + "CLASS: " + pole_class;
// }

// if (ground != " " && ground != "")


// {
// Data += "\n" + "MGNV: " + ground;
// }

// if (telco_first_attachment != " " &&


telco_first_attachment != "")
// {
// comas = telco_first_attachment.Split('-');
// telco_first_attachment = comas[0] + "' - " +
comas[1] + "\" ";
// Data += "\n" + "TELCO: " +
telco_first_attachment;
// }

// if (telco_second_attachment != " " &&


telco_second_attachment != "")
// {
// comas = telco_second_attachment.Split('-');
// telco_second_attachment = comas[0] + "' - " +
comas[1] + "\" ";
// Data += "\n" + "TELCO: " +
telco_second_attachment;
// }
// if (comcast != " " && comcast != "")
// {
// comas = comcast.Split('-');
// comcast = comas[0] + "' - " + comas[1] + "\" ";
// Data += "\n" + "CATV: " + comcast;
// }

// if (catv_second_attachment != " " &&


catv_second_attachment != "")
// {
// comas = catv_second_attachment.Split('-');
// catv_second_attachment = comas[0] + "' - " +
comas[1] + "\" ";
// Data += "\n" + "CATV: " + catv_second_attachment;
// }

// if (streetlight != " " && streetlight != "")


// {
// comas = streetlight.Split('-');
// streetlight = comas[0] + "' - " + comas[1] + "\"
";
// Data += "\n" + "LIGHT: " + streetlight;
// }

// if (secondaryneutral != " " && secondaryneutral !=


"")
// {
// comas = secondaryneutral.Split('-');
// secondaryneutral = comas[0] + "' - " + comas[1] +
"\" ";
// Data += "\n" + "POWER: " + secondaryneutral;
// }

// if (transfer.Contains("Yes") ||
transfer.Contains("Transfer"))
// {
// Data += "\n" + transfer;
// }

// }

// else
// {
// try
// {
// if (pole_tag != " " && pole_tag != "")
// {
// Data += "Pole#: " +
Convert.ToInt32(pole_tag).ToString();
// }
// }
// catch (Exception)
// {
// Data += pole_tag;
// }

// Data += "\n" + pole_owner;


// }

// }
// lines++;
// }
// return Data.ToUpper();
// }
// catch (Exception Ex)
// {
// MessageBox.Show(Ex + "");
// return "Explote";
// }
//}

private string fulcrum_id = " ";


private string fulcrum_parent_id = " ";
private string fulcrum_record_id = " ";
private string version = " ";
private string latitude = " ";
private string longitude = " ";
private string geometry = " ";
private string created_at = " ";
private string updated_at = " ";
private string created_by = " ";
private string updated_by = " ";
private string pole_owner = " ";
private string pole_tag = " ";
private string pole_address_sub_thoroughfare = " ";
private string pole_address_thoroughfare = " ";
private string pole_address_suite = " ";
private string pole_address_locality = " ";
private string pole_address_sub_admin_area = " ";
private string pole_address_admin_area = " ";
private string pole_address_postal_code = " ";
private string pole_address_country = " ";
private string pole_address_full = " ";
private string pole_boc_eop_measurement = " ";
private string pole_class = " ";
private string material = " ";
private string strand_size = " ";
private string guying = " ";
private string joint_use_anchor_1 = " ";
private string proposed_or_existing_1 = " ";
private string anchor_size_1 = " ";
private string down_guy_wire_size_1 = " ";
private string lead_1 = " ";
private string guy_quantity_1 = " ";
private string guy_hoa_1 = " ";
private string pull_1 = " ";
private string bearing_1 = " ";
private string number_of_eyes_1 = " ";
private string joint_use_anchor_2 = " ";
private string proposed_or_existing_2 = " ";
private string anchor_size_2 = " ";
private string down_guy_wire_size_2 = " ";
private string lead_2 = " ";
private string guy_quantity_2 = " ";
private string guy_hoa_2 = " ";
private string pull_2 = " ";
private string bearing_2 = " ";
private string number_of_eyes_2 = " ";
private string joint_use_anchor_3 = " ";
private string proposed_or_existing_3 = " ";
private string anchor_size_3 = " ";
private string down_guy_wire_size_3 = " ";
private string lead_3 = " ";
private string guy_quantity_3 = " ";
private string guy_hoa_3 = " ";
private string pull_3 = " ";
private string bearing_3 = " ";
private string number_of_eyes_3 = " ";
private string joint_use_anchor_4 = " ";
private string proposed_or_existing_4 = " ";
private string anchor_size_4 = " ";
private string down_guy_wire_size_4 = " ";
private string lead_4 = " ";
private string guy_quantity_4 = " ";
private string guy_hoa_4 = " ";
private string pull_4 = " ";
private string bearing_4 = " ";
private string number_of_eyes_4 = " ";
private string telco_first_attachment = " ";
private string telco_second_attachment = " ";
private string roadside_attachment = " ";
private string catv_first_attachment = " ";
private string catv_second_attachment = " ";
private string roadside_attachment_2 = " ";
private string provider_1 = " ";
private string hoa_1 = " ";
private string provider_2 = " ";
private string hoa_2 = " ";
private string provider_3 = " ";
private string hoa_3 = " ";
private string provider_4 = " ";
private string hoa_4 = " ";
private string provider_5 = " ";
private string hoa_5 = " ";
private string secondaryneutral = " ";
private string streetlight = " ";
private string transformer = " ";
private string ground = " ";
private string general_notes = " ";
private string damage_notes = " ";
private string photo = " ";
private string photo_caption = " ";
private string photo_url = " ";

private int fulcrum_id_p = 0;


private int fulcrum_parent_id_p = 0;
private int fulcrum_record_id_p = 0;
private int version_p = 0;
private int latitude_p = 0;
private int longitude_p = 0;
private int geometry_p = 0;
private int created_at_p = 0;
private int updated_at_p = 0;
private int created_by_p = 0;
private int updated_by_p = 0;
private int pole_owner_p = 0;
private int pole_tag_p = 0;
private int pole_address_sub_thoroughfare_p = 0;
private int pole_address_thoroughfare_p = 0;
private int pole_address_suite_p = 0;
private int pole_address_locality_p = 0;
private int pole_address_sub_admin_area_p = 0;
private int pole_address_admin_area_p = 0;
private int pole_address_postal_code_p = 0;
private int pole_address_country_p = 0;
private int pole_address_full_p = 0;
private int pole_boc_eop_measurement_p = 0;
private int pole_class_p = 0;
private int material_p = 0;
private int strand_size_p = 0;
private int guying_p = 0;
private int joint_use_anchor_1_p = 0;
private int proposed_or_existing_1_p = 0;
private int anchor_size_1_p = 0;
private int down_guy_wire_size_1_p = 0;
private int lead_1_p = 0;
private int guy_quantity_1_p = 0;
private int guy_hoa_1_p = 0;
private int pull_1_p = 0;
private int bearing_1_p = 0;
private int number_of_eyes_1_p = 0;
private int joint_use_anchor_2_p = 0;
private int proposed_or_existing_2_p = 0;
private int anchor_size_2_p = 0;
private int down_guy_wire_size_2_p = 0;
private int lead_2_p = 0;
private int guy_quantity_2_p = 0;
private int guy_hoa_2_p = 0;
private int pull_2_p = 0;
private int bearing_2_p = 0;
private int number_of_eyes_2_p = 0;
private int joint_use_anchor_3_p = 0;
private int proposed_or_existing_3_p = 0;
private int anchor_size_3_p = 0;
private int down_guy_wire_size_3_p = 0;
private int lead_3_p = 0;
private int guy_quantity_3_p = 0;
private int guy_hoa_3_p = 0;
private int pull_3_p = 0;
private int bearing_3_p = 0;
private int number_of_eyes_3_p = 0;
private int joint_use_anchor_4_p = 0;
private int proposed_or_existing_4_p = 0;
private int anchor_size_4_p = 0;
private int down_guy_wire_size_4_p = 0;
private int lead_4_p = 0;
private int guy_quantity_4_p = 0;
private int guy_hoa_4_p = 0;
private int pull_4_p = 0;
private int bearing_4_p = 0;
private int number_of_eyes_4_p = 0;
private int telco_first_attachment_p = 0;
private int telco_second_attachment_p = 0;
private int roadside_attachment_p = 0;
private int catv_first_attachment_p = 0;
private int catv_second_attachment_p = 0;
private int roadside_attachment_2_p = 0;
private int provider_1_p = 0;
private int hoa_1_p = 0;
private int provider_2_p = 0;
private int hoa_2_p = 0;
private int provider_3_p = 0;
private int hoa_3_p = 0;
private int provider_4_p = 0;
private int hoa_4_p = 0;
private int provider_5_p = 0;
private int hoa_5_p = 0;
private int secondaryneutral_p = 0;
private int streetlight_p = 0;
private int transformer_p = 0;
private int ground_p = 0;
private int general_notes_p = 0;
private int damage_notes_p = 0;
private int photo_p = 0;
private int photo_caption_p = 0;
private int photo_url_p = 0;

public string Pole_Detail(string S, int P)


{
try
{
string Data = "";
var reader = new StreamReader(S);
int lines = 0;

while (!reader.EndOfStream)
{
string[] comas;
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "fulcrum_id")
fulcrum_id_p = c;
else if (values[c] == "fulcrum_parent_id")
fulcrum_parent_id_p = c;
else if (values[c] == "fulcrum_record_id")
fulcrum_record_id_p = c;
else if (values[c] == "version")
version_p = c;
else if (values[c] == "latitude")
latitude_p = c;
else if (values[c] == "longitude")
longitude_p = c;
else if (values[c] == "geometry")
geometry_p = c;
else if (values[c] == "created_at")
created_at_p = c;
else if (values[c] == "updated_at")
updated_at_p = c;
else if (values[c] == "created_by")
created_by_p = c;
else if (values[c] == "updated_by")
updated_by_p = c;
else if (values[c] == "pole_owner")
pole_owner_p = c;
else if (values[c] == "pole_tag")
pole_tag_p = c;
else if (values[c] == "pole_address_sub_thoroughfare")
pole_address_sub_thoroughfare_p = c;
else if (values[c] == "pole_address_thoroughfare")
pole_address_thoroughfare_p = c;
else if (values[c] == "pole_address_suite")
pole_address_suite_p = c;
else if (values[c] == "pole_address_locality")
pole_address_locality_p = c;
else if (values[c] == "pole_address_sub_admin_area")
pole_address_sub_admin_area_p = c;
else if (values[c] == "pole_address_admin_area")
pole_address_admin_area_p = c;
else if (values[c] == "pole_address_postal_code")
pole_address_postal_code_p = c;
else if (values[c] == "pole_address_country")
pole_address_country_p = c;
else if (values[c] == "pole_address_full")
pole_address_full_p = c;
else if (values[c] == "pole_boc_eop_measurement")
pole_boc_eop_measurement_p = c;
else if (values[c] == "pole_class")
pole_class_p = c;
else if (values[c] == "material")
material_p = c;
else if (values[c] == "strand_size")
strand_size_p = c;
else if (values[c] == "guying")
guying_p = c;
else if (values[c] == "joint_use_anchor_1")
joint_use_anchor_1_p = c;
else if (values[c] == "proposed_or_existing_1")
proposed_or_existing_1_p = c;
else if (values[c] == "anchor_size_1")
anchor_size_1_p = c;
else if (values[c] == "down_guy_wire_size_1")
down_guy_wire_size_1_p = c;
else if (values[c] == "lead_1")
lead_1_p = c;
else if (values[c] == "guy_quantity_1")
guy_quantity_1_p = c;
else if (values[c] == "guy_hoa_1")
guy_hoa_1_p = c;
else if (values[c] == "pull_1")
pull_1_p = c;
else if (values[c] == "bearing_1")
bearing_1_p = c;
else if (values[c] == "number_of_eyes_1")
number_of_eyes_1_p = c;
else if (values[c] == "joint_use_anchor_2")
joint_use_anchor_2_p = c;
else if (values[c] == "proposed_or_existing_2")
proposed_or_existing_2_p = c;
else if (values[c] == "anchor_size_2")
anchor_size_2_p = c;
else if (values[c] == "down_guy_wire_size_2")
down_guy_wire_size_2_p = c;
else if (values[c] == "lead_2")
lead_2_p = c;
else if (values[c] == "guy_quantity_2")
guy_quantity_2_p = c;
else if (values[c] == "guy_hoa_2")
guy_hoa_2_p = c;
else if (values[c] == "pull_2")
pull_2_p = c;
else if (values[c] == "bearing_2")
bearing_2_p = c;
else if (values[c] == "number_of_eyes_2")
number_of_eyes_2_p = c;
else if (values[c] == "joint_use_anchor_3")
joint_use_anchor_3_p = c;
else if (values[c] == "proposed_or_existing_3")
proposed_or_existing_3_p = c;
else if (values[c] == "anchor_size_3")
anchor_size_3_p = c;
else if (values[c] == "down_guy_wire_size_3")
down_guy_wire_size_3_p = c;
else if (values[c] == "lead_3")
lead_3_p = c;
else if (values[c] == "guy_quantity_3")
guy_quantity_3_p = c;
else if (values[c] == "guy_hoa_3")
guy_hoa_3_p = c;
else if (values[c] == "pull_3")
pull_3_p = c;
else if (values[c] == "bearing_3")
bearing_3_p = c;
else if (values[c] == "number_of_eyes_3")
number_of_eyes_3_p = c;
else if (values[c] == "joint_use_anchor_4")
joint_use_anchor_4_p = c;
else if (values[c] == "proposed_or_existing_4")
proposed_or_existing_4_p = c;
else if (values[c] == "anchor_size_4")
anchor_size_4_p = c;
else if (values[c] == "down_guy_wire_size_4")
down_guy_wire_size_4_p = c;
else if (values[c] == "lead_4")
lead_4_p = c;
else if (values[c] == "guy_quantity_4")
guy_quantity_4_p = c;
else if (values[c] == "guy_hoa_4")
guy_hoa_4_p = c;
else if (values[c] == "pull_4")
pull_4_p = c;
else if (values[c] == "bearing_4")
bearing_4_p = c;
else if (values[c] == "number_of_eyes_4")
number_of_eyes_4_p = c;
else if (values[c] == "telco_first_attachment")
telco_first_attachment_p = c;
else if (values[c] == "telco_second_attachment")
telco_second_attachment_p = c;
else if (values[c] == "roadside_attachment")
roadside_attachment_p = c;
else if (values[c] == "catv_first_attachment")
catv_first_attachment_p = c;
else if (values[c] == "catv_second_attachment")
catv_second_attachment_p = c;
else if (values[c] == "roadside_attachment_2")
roadside_attachment_2_p = c;
else if (values[c] == "provider_1")
provider_1_p = c;
else if (values[c] == "hoa_1")
hoa_1_p = c;
else if (values[c] == "provider_2")
provider_2_p = c;
else if (values[c] == "hoa_2")
hoa_2_p = c;
else if (values[c] == "provider_3")
provider_3_p = c;
else if (values[c] == "hoa_3")
hoa_3_p = c;
else if (values[c] == "provider_4")
provider_4_p = c;
else if (values[c] == "hoa_4")
hoa_4_p = c;
else if (values[c] == "provider_5")
provider_5_p = c;
else if (values[c] == "hoa_5")
hoa_5_p = c;
else if (values[c] == "secondaryneutral")
secondaryneutral_p = c;
else if (values[c] == "streetlight")
streetlight_p = c;
else if (values[c] == "transformer")
transformer_p = c;
else if (values[c] == "ground")
ground_p = c;
else if (values[c] == "general_notes")
general_notes_p = c;
else if (values[c] == "damage_notes")
damage_notes_p = c;
else if (values[c] == "photo")
photo_p = c;
else if (values[c] == "photo_caption")
photo_caption_p = c;
else if (values[c] == "photo_url")
photo_url_p = c;

if (fulcrum_id_p != 0)
fulcrum_id = values[fulcrum_id_p];
if (fulcrum_parent_id_p != 0)
fulcrum_parent_id = values[fulcrum_parent_id_p];
if (fulcrum_record_id_p != 0)
fulcrum_record_id = values[fulcrum_record_id_p];
if (version_p != 0)
version = values[version_p];
if (latitude_p != 0)
latitude = values[latitude_p];
if (longitude_p != 0)
longitude = values[longitude_p];
if (geometry_p != 0)
geometry = values[geometry_p];
if (created_at_p != 0)
created_at = values[created_at_p];
if (updated_at_p != 0)
updated_at = values[updated_at_p];
if (created_by_p != 0)
created_by = values[created_by_p];
if (updated_by_p != 0)
updated_by = values[updated_by_p];
if (pole_owner_p != 0)
pole_owner = values[pole_owner_p];
if (pole_tag_p != 0)
pole_tag = values[pole_tag_p];
if (pole_address_sub_thoroughfare_p != 0)
pole_address_sub_thoroughfare =
values[pole_address_sub_thoroughfare_p];
if (pole_address_thoroughfare_p != 0)
pole_address_thoroughfare =
values[pole_address_thoroughfare_p];
if (pole_address_suite_p != 0)
pole_address_suite = values[pole_address_suite_p];
if (pole_address_locality_p != 0)
pole_address_locality = values[pole_address_locality_p];
if (pole_address_sub_admin_area_p != 0)
pole_address_sub_admin_area =
values[pole_address_sub_admin_area_p];
if (pole_address_admin_area_p != 0)
pole_address_admin_area =
values[pole_address_admin_area_p];
if (pole_address_postal_code_p != 0)
pole_address_postal_code =
values[pole_address_postal_code_p];
if (pole_address_country_p != 0)
pole_address_country = values[pole_address_country_p];
if (pole_address_full_p != 0)
pole_address_full = values[pole_address_full_p];
if (pole_boc_eop_measurement_p != 0)
pole_boc_eop_measurement =
values[pole_boc_eop_measurement_p];
if (pole_class_p != 0)
pole_class = values[pole_class_p];
if (material_p != 0)
material = values[material_p];
if (strand_size_p != 0)
strand_size = values[strand_size_p];
if (guying_p != 0)
guying = values[guying_p];
if (joint_use_anchor_1_p != 0)
joint_use_anchor_1 = values[joint_use_anchor_1_p];
if (proposed_or_existing_1_p != 0)
proposed_or_existing_1 = values[proposed_or_existing_1_p];
if (anchor_size_1_p != 0)
anchor_size_1 = values[anchor_size_1_p];
if (down_guy_wire_size_1_p != 0)
down_guy_wire_size_1 = values[down_guy_wire_size_1_p];
if (lead_1_p != 0)
lead_1 = values[lead_1_p];
if (guy_quantity_1_p != 0)
guy_quantity_1 = values[guy_quantity_1_p];
if (guy_hoa_1_p != 0)
guy_hoa_1 = values[guy_hoa_1_p];
if (pull_1_p != 0)
pull_1 = values[pull_1_p];
if (bearing_1_p != 0)
bearing_1 = values[bearing_1_p];
if (number_of_eyes_1_p != 0)
number_of_eyes_1 = values[number_of_eyes_1_p];
if (joint_use_anchor_2_p != 0)
joint_use_anchor_2 = values[joint_use_anchor_2_p];
if (proposed_or_existing_2_p != 0)
proposed_or_existing_2 = values[proposed_or_existing_2_p];
if (anchor_size_2_p != 0)
anchor_size_2 = values[anchor_size_2_p];
if (down_guy_wire_size_2_p != 0)
down_guy_wire_size_2 = values[down_guy_wire_size_2_p];
if (lead_2_p != 0)
lead_2 = values[lead_2_p];
if (guy_quantity_2_p != 0)
guy_quantity_2 = values[guy_quantity_2_p];
if (guy_hoa_2_p != 0)
guy_hoa_2 = values[guy_hoa_2_p];
if (pull_2_p != 0)
pull_2 = values[pull_2_p];
if (bearing_2_p != 0)
bearing_2 = values[bearing_2_p];
if (number_of_eyes_2_p != 0)
number_of_eyes_2 = values[number_of_eyes_2_p];
if (joint_use_anchor_3_p != 0)
joint_use_anchor_3 = values[joint_use_anchor_3_p];
if (proposed_or_existing_3_p != 0)
proposed_or_existing_3 = values[proposed_or_existing_3_p];
if (anchor_size_3_p != 0)
anchor_size_3 = values[anchor_size_3_p];
if (down_guy_wire_size_3_p != 0)
down_guy_wire_size_3 = values[down_guy_wire_size_3_p];
if (lead_3_p != 0)
lead_3 = values[lead_3_p];
if (guy_quantity_3_p != 0)
guy_quantity_3 = values[guy_quantity_3_p];
if (guy_hoa_3_p != 0)
guy_hoa_3 = values[guy_hoa_3_p];
if (pull_3_p != 0)
pull_3 = values[pull_3_p];
if (bearing_3_p != 0)
bearing_3 = values[bearing_3_p];
if (number_of_eyes_3_p != 0)
number_of_eyes_3 = values[number_of_eyes_3_p];
if (joint_use_anchor_4_p != 0)
joint_use_anchor_4 = values[joint_use_anchor_4_p];
if (proposed_or_existing_4_p != 0)
proposed_or_existing_4 = values[proposed_or_existing_4_p];
if (anchor_size_4_p != 0)
anchor_size_4 = values[anchor_size_4_p];
if (down_guy_wire_size_4_p != 0)
down_guy_wire_size_4 = values[down_guy_wire_size_4_p];
if (lead_4_p != 0)
lead_4 = values[lead_4_p];
if (guy_quantity_4_p != 0)
guy_quantity_4 = values[guy_quantity_4_p];
if (guy_hoa_4_p != 0)
guy_hoa_4 = values[guy_hoa_4_p];
if (pull_4_p != 0)
pull_4 = values[pull_4_p];
if (bearing_4_p != 0)
bearing_4 = values[bearing_4_p];
if (number_of_eyes_4_p != 0)
number_of_eyes_4 = values[number_of_eyes_4_p];
if (telco_first_attachment_p != 0)
telco_first_attachment = values[telco_first_attachment_p];
if (telco_second_attachment_p != 0)
telco_second_attachment =
values[telco_second_attachment_p];
if (roadside_attachment_p != 0)
roadside_attachment = values[roadside_attachment_p];
if (catv_first_attachment_p != 0)
catv_first_attachment = values[catv_first_attachment_p];
if (catv_second_attachment_p != 0)
catv_second_attachment = values[catv_second_attachment_p];
if (roadside_attachment_2_p != 0)
roadside_attachment_2 = values[roadside_attachment_2_p];
if (provider_1_p != 0)
provider_1 = values[provider_1_p];
if (hoa_1_p != 0)
hoa_1 = values[hoa_1_p];
if (provider_2_p != 0)
provider_2 = values[provider_2_p];
if (hoa_2_p != 0)
hoa_2 = values[hoa_2_p];
if (provider_3_p != 0)
provider_3 = values[provider_3_p];
if (hoa_3_p != 0)
hoa_3 = values[hoa_3_p];
if (provider_4_p != 0)
provider_4 = values[provider_4_p];
if (hoa_4_p != 0)
hoa_4 = values[hoa_4_p];
if (provider_5_p != 0)
provider_5 = values[provider_5_p];
if (hoa_5_p != 0)
hoa_5 = values[hoa_5_p];
if (secondaryneutral_p != 0)
secondaryneutral = values[secondaryneutral_p];
if (streetlight_p != 0)
streetlight = values[streetlight_p];
if (transformer_p != 0)
transformer = values[transformer_p];
if (ground_p != 0)
ground = values[ground_p];
if (general_notes_p != 0)
general_notes = values[general_notes_p];
if (damage_notes_p != 0)
damage_notes = values[damage_notes_p];
if (photo_p != 0)
photo = values[photo_p];
if (photo_caption_p != 0)
photo_caption = values[photo_caption_p];
if (photo_url_p != 0)
photo_url = values[photo_url_p];

if (lines == P && P != 0)
{
if (pole_owner != " " && pole_owner != "")
{
Data += "pole_owner: " + pole_owner + "\n";
}
if (pole_tag != " " && pole_tag != "")
{
Data += "pole_tag: " + pole_tag + "\n";
}
if (pole_address_full != " " && pole_address_full != "")
{
Data += "pole_address_full: " + pole_address_full + "\
n";
}
if (pole_boc_eop_measurement != " " &&
pole_boc_eop_measurement != "")
{
Data += "pole_boc_eop_measurement: " +
pole_boc_eop_measurement + "\n";
}
if (pole_class != " " && pole_class != "")
{
Data += "pole_class: " + pole_class + "\n";
}
if (material != " " && material != "")
{
Data += "material: " + material + "\n";
}
if (strand_size != " " && strand_size != "")
{
Data += "strand_size: " + strand_size + "\n";
}
if (guying != " " && guying != "")
{
Data += "guying: " + guying + "\n";
}
if (joint_use_anchor_1 != " " && joint_use_anchor_1 != "")
{
Data += "joint_use_anchor_1: " + joint_use_anchor_1 +
"\n";
}
if (proposed_or_existing_1 != " " && proposed_or_existing_1
!= "")
{
Data += "proposed_or_existing_1: " +
proposed_or_existing_1 + "\n";
}
if (anchor_size_1 != " " && anchor_size_1 != "")
{
Data += "anchor_size_1: " + anchor_size_1 + "\n";
}
if (down_guy_wire_size_1 != " " && down_guy_wire_size_1 !=
"")
{
Data += "down_guy_wire_size_1: " + down_guy_wire_size_1
+ "\n";
}
if (lead_1 != " " && lead_1 != "")
{
Data += "lead_1: " + lead_1 + "\n";
}
if (guy_quantity_1 != " " && guy_quantity_1 != "")
{
Data += "guy_quantity_1: " + guy_quantity_1 + "\n";
}
if (guy_hoa_1 != " " && guy_hoa_1 != "")
{
Data += "guy_hoa_1: " + guy_hoa_1 + "\n";
}
if (pull_1 != " " && pull_1 != "")
{
Data += "pull_1: " + pull_1 + "\n";
}
if (bearing_1 != " " && bearing_1 != "")
{
Data += "bearing_1: " + bearing_1 + "\n";
}
if (number_of_eyes_1 != " " && number_of_eyes_1 != "")
{
Data += "number_of_eyes_1: " + number_of_eyes_1 + "\n";
}
if (joint_use_anchor_2 != " " && joint_use_anchor_2 != "")
{
Data += "joint_use_anchor_2: " + joint_use_anchor_2 +
"\n";
}
if (proposed_or_existing_2 != " " && proposed_or_existing_2
!= "")
{
Data += "proposed_or_existing_2: " +
proposed_or_existing_2 + "\n";
}
if (anchor_size_2 != " " && anchor_size_2 != "")
{
Data += "anchor_size_2: " + anchor_size_2 + "\n";
}
if (down_guy_wire_size_2 != " " && down_guy_wire_size_2 !=
"")
{
Data += "down_guy_wire_size_2: " + down_guy_wire_size_2
+ "\n";
}
if (lead_2 != " " && lead_2 != "")
{
Data += "lead_2: " + lead_2 + "\n";
}
if (guy_quantity_2 != " " && guy_quantity_2 != "")
{
Data += "guy_quantity_2: " + guy_quantity_2 + "\n";
}
if (guy_hoa_2 != " " && guy_hoa_2 != "")
{
Data += "guy_hoa_2: " + guy_hoa_2 + "\n";
}
if (pull_2 != " " && pull_2 != "")
{
Data += "pull_2: " + pull_2 + "\n";
}
if (bearing_2 != " " && bearing_2 != "")
{
Data += "bearing_2: " + bearing_2 + "\n";
}
if (number_of_eyes_2 != " " && number_of_eyes_2 != "")
{
Data += "number_of_eyes_2: " + number_of_eyes_2 + "\n";
}
if (joint_use_anchor_3 != " " && joint_use_anchor_3 != "")
{
Data += "joint_use_anchor_3: " + joint_use_anchor_3 +
"\n";
}
if (proposed_or_existing_3 != " " && proposed_or_existing_3
!= "")
{
Data += "proposed_or_existing_3: " +
proposed_or_existing_3 + "\n";
}
if (anchor_size_3 != " " && anchor_size_3 != "")
{
Data += "anchor_size_3: " + anchor_size_3 + "\n";
}
if (down_guy_wire_size_3 != " " && down_guy_wire_size_3 !=
"")
{
Data += "down_guy_wire_size_3: " + down_guy_wire_size_3
+ "\n";
}
if (lead_3 != " " && lead_3 != "")
{
Data += "lead_3: " + lead_3 + "\n";
}
if (guy_quantity_3 != " " && guy_quantity_3 != "")
{
Data += "guy_quantity_3: " + guy_quantity_3 + "\n";
}
if (guy_hoa_3 != " " && guy_hoa_3 != "")
{
Data += "guy_hoa_3: " + guy_hoa_3 + "\n";
}
if (pull_3 != " " && pull_3 != "")
{
Data += "pull_3: " + pull_3 + "\n";
}
if (bearing_3 != " " && bearing_3 != "")
{
Data += "bearing_3: " + bearing_3 + "\n";
}
if (number_of_eyes_3 != " " && number_of_eyes_3 != "")
{
Data += "number_of_eyes_3: " + number_of_eyes_3 + "\n";
}
if (joint_use_anchor_4 != " " && joint_use_anchor_4 != "")
{
Data += "joint_use_anchor_4: " + joint_use_anchor_4 +
"\n";
}
if (proposed_or_existing_4 != " " && proposed_or_existing_4
!= "")
{
Data += "proposed_or_existing_4: " +
proposed_or_existing_4 + "\n";
}
if (anchor_size_4 != " " && anchor_size_4 != "")
{
Data += "anchor_size_4: " + anchor_size_4 + "\n";
}
if (down_guy_wire_size_4 != " " && down_guy_wire_size_4 !=
"")
{
Data += "down_guy_wire_size_4: " + down_guy_wire_size_4
+ "\n";
}
if (lead_4 != " " && lead_4 != "")
{
Data += "lead_4: " + lead_4 + "\n";
}
if (guy_quantity_4 != " " && guy_quantity_4 != "")
{
Data += "guy_quantity_4: " + guy_quantity_4 + "\n";
}
if (guy_hoa_4 != " " && guy_hoa_4 != "")
{
Data += "guy_hoa_4: " + guy_hoa_4 + "\n";
}
if (pull_4 != " " && pull_4 != "")
{
Data += "pull_4: " + pull_4 + "\n";
}
if (bearing_4 != " " && bearing_4 != "")
{
Data += "bearing_4: " + bearing_4 + "\n";
}
if (number_of_eyes_4 != " " && number_of_eyes_4 != "")
{
Data += "number_of_eyes_4: " + number_of_eyes_4 + "\n";
}
if (telco_first_attachment != " " && telco_first_attachment
!= "")
{
Data += "telco_first_attachment: " +
telco_first_attachment + "\n";
}
if (telco_second_attachment != " " &&
telco_second_attachment != "")
{
Data += "telco_second_attachment: " +
telco_second_attachment + "\n";
}
if (roadside_attachment != " " && roadside_attachment !=
"")
{
Data += "roadside_attachment: " + roadside_attachment +
"\n";
}
if (catv_first_attachment != " " && catv_first_attachment !
= "")
{
Data += "catv_first_attachment: " +
catv_first_attachment + "\n";
}
if (catv_second_attachment != " " && catv_second_attachment
!= "")
{
Data += "catv_second_attachment: " +
catv_second_attachment + "\n";
}
if (roadside_attachment_2 != " " && roadside_attachment_2 !
= "")
{
Data += "roadside_attachment_2: " +
roadside_attachment_2 + "\n";
}
if (provider_1 != " " && provider_1 != "")
{
Data += "provider_1: " + provider_1 + "\n";
}
if (hoa_1 != " " && hoa_1 != "")
{
Data += "hoa_1: " + hoa_1 + "\n";
}
if (provider_2 != " " && provider_2 != "")
{
Data += "provider_2: " + provider_2 + "\n";
}
if (hoa_2 != " " && hoa_2 != "")
{
Data += "hoa_2: " + hoa_2 + "\n";
}
if (provider_3 != " " && provider_3 != "")
{
Data += "provider_3: " + provider_3 + "\n";
}
if (hoa_3 != " " && hoa_3 != "")
{
Data += "hoa_3: " + hoa_3 + "\n";
}
if (provider_4 != " " && provider_4 != "")
{
Data += "provider_4: " + provider_4 + "\n";
}
if (hoa_4 != " " && hoa_4 != "")
{
Data += "hoa_4: " + hoa_4 + "\n";
}
if (provider_5 != " " && provider_5 != "")
{
Data += "provider_5: " + provider_5 + "\n";
}
if (hoa_5 != " " && hoa_5 != "")
{
Data += "hoa_5: " + hoa_5 + "\n";
}
if (secondaryneutral != " " && secondaryneutral != "")
{
Data += "secondaryneutral: " + secondaryneutral + "\n";
}
if (streetlight != " " && streetlight != "")
{
Data += "streetlight: " + streetlight + "\n";
}
if (transformer != " " && transformer != "")
{
Data += "transformer: " + transformer + "\n";
}
if (ground != " " && ground != "")
{
Data += "ground: " + ground + "\n";
}
if (general_notes != " " && general_notes != "")
{
Data += "general_notes: " + general_notes + "\n";
}
if (damage_notes != " " && damage_notes != "")
{
Data += "damage_notes: " + damage_notes + "\n";
}
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return "Explote";
}
}

public string Pole_Photo(Double Lat, Double Lon, string s)


{
try
{
string Data = "";
var reader = new StreamReader(s);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "photo")
photo_p = c;
else if (values[c] == "latitude")
latitude_p = c;
else if (values[c] == "longitude")
longitude_p = c;
if (lines != 0)
{
decimal lat1 = Math.Round(Convert.ToDecimal(Lat), 5);
decimal lon1 = Math.Round(Convert.ToDecimal(Lon), 5);

decimal lat2 =
Math.Round(Convert.ToDecimal(values[latitude_p]), 5);
decimal lon2 =
Math.Round(Convert.ToDecimal(values[longitude_p]), 5);

if (Convert.ToDouble(Math.Abs(lat1 - lat2)) <= 0.0002 &&


Convert.ToDouble(Math.Abs(lon1 - lon2)) <= 0.0002)
{
Data = values[photo_p];
return Data;
}
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return "Explote";
}
}

public string Dow_Anc_Detail(string S, int P)


{
try
{
string Data = "";
var reader = new StreamReader(S);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "proposed_or_existing_1")
proposed_or_existing_1_p = c;
else if (values[c] == "bearing_1")
bearing_1_p = c;
else if (values[c] == "lead_1")
lead_1_p = c;

if (lines == P && P != 0)
{
proposed_or_existing_1 = values[proposed_or_existing_1_p];
bearing_1 = values[bearing_1_p];
lead_1 = values[lead_1_p];
if (proposed_or_existing_1 == "Proposed")
Data += "PROPOSED DOWNGUY AND ANCHOR AT " + lead_1 + "'
LEAD FROM POLE ";
else if (proposed_or_existing_1 == "Existing")
Data += "EXISTING DOWNGUY BEARING" + " " + bearing_1;
//return Dow_Anc_Details.ToUpper();
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return "Explote";
}
}
}

public class CSpan


{
private string environment = " ";
private string aerial_value = " ";

private int environment_p = 0;


private int aerial_value_p = 0;

public string Span_Detail(string S, int P)


{
try
{
string Data = "";
var reader = new StreamReader(S);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "environment")
environment_p = c;
else if (values[c] == "aerial_value")
aerial_value_p = c;

if (lines == P && P != 0)
{
environment = values[environment_p];
aerial_value = values[aerial_value_p];

if (environment == "Buried")
Data = "{\\fArial|b1|;\\LDIRECTIONAL BORE -MAX\nBACK
REAMER SIZE =6\" \\P}INSTALL 1\'-2\" HDPE \\PCONDUIT PULL 1-FIBER OPTIC CABLE \\
P(84\" MIN. GROUND COVER)";
else if (environment == "Aerial")
Data = "{\\fArial|b1|;\\LOVERLASH \\P}OVERLASH 1 - FOC
TO \\PEXISTING STRAND \\P{\\C5;" + aerial_value + "\'}";
}
lines++;
}
return Data;
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return "Explote";
}
}
}

public class CBuried


{
private string buried_reference = " ";
private int buried_reference_p = 0;
private int buried_ref_notes_p = 0;

private int buried_ref_photos_P = 0;


private int latitude_p = 0;
private int longitude_p = 0;

public string Buried_Detail(string S, int P)


{
string Data = "";

try
{
var reader = new StreamReader(S);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "buried_reference")
buried_reference_p = c;
else if (values[c] == "buried_ref_notes")
buried_ref_notes_p = c;

if (lines == P && P != 0)
{
buried_reference = values[buried_reference_p];
//buried_ref_notes = values[buried_ref_notes_p];

if (buried_reference != " " /*|| buried_ref_notes != " "*/)


Data += buried_reference /*+ " - " +
buried_ref_notes*/;
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return Data;
}
}

public string Buried_Photo(Double Lat, Double Lon, string s)


{
try
{
string Data = "";
var reader = new StreamReader(s);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "buried_ref_photos")
buried_ref_photos_P = c;
else if (values[c] == "latitude")
latitude_p = c;
else if (values[c] == "longitude")
longitude_p = c;
if (lines != 0)
{
decimal lat1 = Math.Round(Convert.ToDecimal(Lat), 5);
decimal lon1 = Math.Round(Convert.ToDecimal(Lon), 5);

decimal lat2 =
Math.Round(Convert.ToDecimal(values[latitude_p]), 5);
decimal lon2 =
Math.Round(Convert.ToDecimal(values[longitude_p]), 5);

if (Convert.ToDouble(Math.Abs(lat1 - lat2)) <= 0.0002 &&


Convert.ToDouble(Math.Abs(lon1 - lon2)) <= 0.0002)
{
Data = values[buried_ref_photos_P];
return Data;
}
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return "Explote";
}
}
}

public class CClearance


{
private string midspan_clearance = " ";

private int midspan_clearance_p = 0;

public string Clearance_Detail(string S, int P)


{
string Data = "";

try
{
var reader = new StreamReader(S);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "midspan_clearance")
midspan_clearance_p = c;

if (lines == P && P != 0)
{
midspan_clearance = values[midspan_clearance_p];
values = midspan_clearance.Split('-');
Data = "Clearance " + values[0] + "\'-" + values[1] + "\"";
return Data.ToUpper();
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return Data;
}
}
}

public class CPoint


{
private double Lat = 0;
private double Lon = 0;

public double GSLat { get => Lat; set => Lat = value; }
public double GSLon { get => Lon; set => Lon = value; }

public Point3d Regla_3(Polyline Ori, Polyline Des, Point3d Pb)


{
double OriL = Ori.Length / 100;

double DesL = Des.Length / 100;

double Pr = Ori.GetDistAtPoint(Pb) / OriL;

return (Des.GetPointAtDist(DesL * Pr));


}

public Point3d PointFromLatLong(Point3d Point)


{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

// Translate the lat-lon to a drawing point

var dwgPt = TranslateGeoPoint(db, Point, false);


return dwgPt;
}

public Point3d PointFromLatLong(double lat, double lon)


{
Point3d Point = new Point3d(lat, lon, 0);

var doc = Application.DocumentManager.MdiActiveDocument;


var db = doc.Database;

// Translate the lat-lon to a drawing point

var dwgPt = TranslateGeoPoint(db, Point, false);


return dwgPt;
}

public Point2d LatLongFromPoint2(Point3d P)


{
var doc = Application.DocumentManager.MdiActiveDocument;

var ed = doc.Editor;
var db = doc.Database;

// Translate the drawing point to a lat-lon

var lonlat = TranslateGeoPoint(db, P, true);


var p = new Point2d(lonlat.X, lonlat.Y);

return p;
}

private Point3d TranslateGeoPoint(Database db, Point3d inPt, bool fromDwg)


{
using (var tr = db.TransactionManager.StartOpenCloseTransaction())
{

// Get the drawing's GeoLocation object

var gd = tr.GetObject(db.GeoDataObject, OpenMode.ForRead) as


GeoLocationData;

// Get the output point...


// dwg2lonlat if fromDwg is true,
// lonlat2dwg otherwise

var outPt = (fromDwg ? gd.TransformToLonLatAlt(inPt) :


gd.TransformFromLonLatAlt(inPt));

tr.Commit();
return outPt;
}
}

public double Distance(Point2d A, Point2d B)


{
double Lat1 = 0;
double lon1 = 0;
double Lat2 = 0;
double lon2 = 0;

double deg2radMultiplier = Math.PI / 180;

Lat1 *= deg2radMultiplier;
lon1 *= deg2radMultiplier;
Lat2 *= deg2radMultiplier;
lon2 *= deg2radMultiplier;

double radius = 6378.137; // earth mean radius defined by WGS84


            double dlon = lon2 - lon1;
double distance = Math.Acos(Math.Sin(Lat1) * Math.Sin(Lat2) +
Math.Cos(Lat1) * Math.Cos(Lat2) * Math.Cos(dlon)) * radius;

return (distance);
}

#region Geometric Center of Polyline


public Point3d GetCentroid(Polyline pl)
{
Point2d p0 = pl.GetPoint2dAt(0);
Point2d cen = new Point2d(0.0, 0.0);
double area = 0.0;
double bulge = pl.GetBulgeAt(0);
int last = pl.NumberOfVertices - 1;
double tmpArea;
Point2d tmpPoint;

if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, 0, 1);
area = datas[0];
cen = new Point2d(datas[1], datas[2]) * datas[0];
}
for (int i = 1; i < last; i++)
{
tmpArea = TriangleAlgebricArea(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
tmpPoint = TriangleCentroid(p0, pl.GetPoint2dAt(i),
pl.GetPoint2dAt(i + 1));
cen += (tmpPoint * tmpArea).GetAsVector();
area += tmpArea;
bulge = pl.GetBulgeAt(i);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, i, i + 1);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
}
bulge = pl.GetBulgeAt(last);
if (bulge != 0.0)
{
double[] datas = GetArcGeom(pl, bulge, last, 0);
area += datas[0];
cen += new Vector2d(datas[1], datas[2]) * datas[0];
}
cen = cen.DivideBy(area);
Point3d result = new Point3d(cen.X, cen.Y, pl.Elevation);
return result.TransformBy(Matrix3d.PlaneToWorld(pl.Normal));
}

private static double[] GetArcGeom(Polyline pl, double bulge, int index1,


int index2)
{
CircularArc2d arc = (pl.GetArcSegment2dAt(index1));
double arcRadius = arc.Radius;
Point2d arcCenter = arc.Center;
double arcAngle = 4.0 * Math.Atan(bulge);
double tmpArea = ArcAlgebricArea(arcRadius, arcAngle);
Point2d tmpPoint = ArcCentroid(pl.GetPoint2dAt(index1),
pl.GetPoint2dAt(index2), arcCenter, tmpArea);
return new double[3] { tmpArea, tmpPoint.X, tmpPoint.Y };
}

private static Point2d TriangleCentroid(Point2d p0, Point2d p1, Point2d p2)


{
return (p0 + p1.GetAsVector() + p2.GetAsVector()) / 3.0;
}

private static double TriangleAlgebricArea(Point2d p0, Point2d p1, Point2d


p2)
{
return (((p1.X - p0.X) * (p2.Y - p0.Y)) - ((p2.X - p0.X) * (p1.Y -
p0.Y))) / 2.0;
}

private static Point2d ArcCentroid(Point2d start, Point2d end, Point2d cen,


double tmpArea)
{
double chord = start.GetDistanceTo(end);
double angle = (end - start).Angle;
return Polar2d(cen, angle - (Math.PI / 2.0), (chord * chord * chord) /
(12.0 * tmpArea));
}

private static double ArcAlgebricArea(double rad, double ang)


{
return rad * rad * (ang - Math.Sin(ang)) / 2.0;
}

private static Point2d Polar2d(Point2d org, double angle, double distance)


{
return org + new Vector2d(distance * Math.Cos(angle), distance *
Math.Sin(angle));
}
#endregion
}

public class CStations


{
private string station_reference = " ";

private int station_referenceP = 0;

private string sta = " ";

private int staP = 0;

public string STATIONS_Detail(string SF, int P)


{
string Data = "";

try
{
var reader = new StreamReader(SF);
int lines = 0;

while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');

if (lines == 0)
for (int c = 0; c < values.Length; c++)
if (values[c] == "station_reference")
station_referenceP = c;
else if (values[c] == "sta")
staP = c;

if (lines == P && P != 0)
{
station_reference = values[station_referenceP];
sta = values[staP];
Data = (station_reference + "\n" + sta).ToString();
return Data.ToUpper();
}
lines++;
}
return Data.ToUpper();
}
catch (Exception Ex)
{
MessageBox.Show(Ex + "");
return Data;
}
}
}

public class CLayer


{
public void GetLayerName(ComboBox CbLayer)
{
ArrayList Layers = new ArrayList();
// Get the current document and database
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

// Start a transaction
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as
LayerTable;
foreach (ObjectId acObjId in acLyrTbl)
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as
LayerTableRecord;
Layers.Add(acLyrTblRec.Name);
}
}

foreach (string S in Layers)


CbLayer.Items.Add(S);
}

public ArrayList GetLayerName()


{
ArrayList Layers = new ArrayList();
// Get the current document and database
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

// Start a transaction
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as
LayerTable;
foreach (ObjectId acObjId in acLyrTbl)
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as
LayerTableRecord;
Layers.Add(acLyrTblRec.Name);
}
}

Layers.Sort();

return Layers;
}

public bool GetLayerOnOff(string layerName)


{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
using (Transaction acTrans = db.TransactionManager.StartTransaction())
{
var layerTable = acTrans.GetObject(db.LayerTableId,
OpenMode.ForRead) as LayerTable;
var layerTableRecord = acTrans.GetObject(layerTable[layerName],
OpenMode.ForWrite) as LayerTableRecord;

return layerTableRecord.IsOff;
}
}
}

public class CBlock


{
public void GetBlockName(ComboBox CbBlock)
{
ArrayList Blocks = new ArrayList();

// Get the current document and database


Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans =
acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
BlockTable table =
(BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);

foreach (ObjectId acObjId in table)


{
BlockTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as
BlockTableRecord;
Blocks.Add(acLyrTblRec.Name);
}
}

Blocks.Sort();

foreach (string S in Blocks)


CbBlock.Items.Add(S);
}

public ArrayList GetBlockName()


{
ArrayList Blocks = new ArrayList();

// Get the current document and database


Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans =
acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
BlockTable table =
(BlockTable)acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead);

foreach (ObjectId acObjId in table)


{
BlockTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead) as
BlockTableRecord;
if (!acLyrTblRec.Name.Contains("*"))
Blocks.Add(acLyrTblRec.Name);
}
}

Blocks.Sort();

return Blocks;
}

public string GetBlockName(BlockReference Br)


{
return Br.IsDynamicBlock ?
((BlockTableRecord)Br.DynamicBlockTableRecord.GetObject(OpenMode.ForWrite)).Name :
Br.Name;
}
}

public class CCSV


{
private string[] headers;

public void Load(TextBox TbLoa, ComboBox CbLongitude, ComboBox CbLatitude)


{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|
*.xls;*.xlsx;*.xlsm;*.csv;*.txt;*.kml";//Filtro para solo buscar archivos Excel
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
TbLoa.Text = openFileDialog.FileName;
TbLoa.SelectionStart = openFileDialog.FileName.Length;
try
{
using (var reader = new StreamReader(TbLoa.Text))
{
bool header = true;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] values = line.Split(',');
if (header)
{
headers = values;
header = false;
}
else
{
break;
}
}
}

CbLatitude.Items.AddRange(headers);
CbLongitude.Items.AddRange(headers);

CbLatitude.Text = "latitude";
CbLongitude.Text = "longitude";
}
catch (Exception)
{
Application.ShowAlertDialog("Close file and try");
TbLoa.Text = "";
}
}
}
}

public class CKML


{
public int orientation = 0;
public void SimplePolyline(TextBox TBLoadKML)
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;

using (Transaction acTrans = db.TransactionManager.StartTransaction())


{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as
BlockTable;

// Open the Block table record Model space for write


BlockTableRecord acBlkTblRec;
acBlkTblRec =
acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as
BlockTableRecord;

string s;
using (var reader = new StreamReader(TBLoadKML.Text))
{
while (!reader.EndOfStream)
{
s = reader.ReadLine();

if (s.Contains("<coordinates>"))
{
string info = getBetween(s, "<coordinates>",
"</coordinates>");

acBlkTbl = acTrans.GetObject(db.BlockTableId,
OpenMode.ForRead) as BlockTable;
acBlkTblRec =
acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as
BlockTableRecord;
using (Polyline acPoly = new Polyline())
{
acPoly.Layer = "ROW";

ArrayList TemArrLis = new ArrayList();


string[] TempArrayData;

string[] j = info.Split(' ');


for (int c = 1; c <= j.Length - 2; c++)
{
TempArrayData = j[c].Split(',');
TemArrLis.Add(TempArrayData[0]);
TemArrLis.Add(TempArrayData[1]);
}

TempArrayData = j[0].Split(',');
TemArrLis.Add(TempArrayData[0]);
TemArrLis.Add(TempArrayData[1]);

int p = 0;

for (int c = 0; c < TemArrLis.Count - 1; c += 2)


{
Point3d Point = new
Point3d(Convert.ToDouble(TemArrLis[c]), Convert.ToDouble(TemArrLis[c + 1]), 0);

Class.CPoint P = new Class.CPoint();

acPoly.AddVertexAt(acPoly.NumberOfVertices, new
Point2d(P.PointFromLatLong(Point).X, P.PointFromLatLong(Point).Y), 0, 0, 0);
}

acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);

acPoly.Closed = true;
}
}
}
}

acTrans.Commit();
acTrans.Dispose();
}
db.Dispose();

MessageBox.Show("Draw Complete");
}

public string getBetween(string Data, string St, string En)


{
int Start, End;
if (Data.Contains(St) && Data.Contains(En))
{
Start = Data.IndexOf(St, 0) + St.Length;
End = Data.IndexOf(En, Start);
return Data.Substring(Start, End - Start);
}
else
{
return "";
}
}

public void Draw_Early(TextBox TBLoadKML, Point3d BRP)


{
Polyline acPoly = new Polyline();

var Pol = new Polyline();


CPoint Cp = new CPoint();
double minddis = 15011515;
string s = "";
int pbm = 0;

using (var reader = new StreamReader(TBLoadKML.Text))


while (!reader.EndOfStream)
{
s = reader.ReadLine();
pbm++;
}

pbm = 0;

var Dm = Application.DocumentManager.MdiActiveDocument;
Database Db = Dm.Database;

using (Transaction acTrans = Db.TransactionManager.StartTransaction())


{
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(Db.BlockTableId, OpenMode.ForRead) as
BlockTable;

BlockTableRecord acBlkTblRec;
acBlkTblRec =
acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as
BlockTableRecord;

var reader = new StreamReader(TBLoadKML.Text);

int NLines = 0;

while (!reader.EndOfStream)
{
acPoly = new Polyline();
string Data = reader.ReadLine();
pbm++;

string Rute = "";


try
{
if (Data.Contains("<coordinates>"))
{

Rute = getBetween(Data, "<coordinates>",


"</coordinates>");

ArrayList TemArrLis = new ArrayList();


string[] TempArrayData;

string[] j = Rute.Split(' ');


for (int c = 0; c < j.Length; c++)
{
TempArrayData = j[c].Split(',');
TemArrLis.Add(TempArrayData[0]);
TemArrLis.Add(TempArrayData[1]);
}

for (int c = 0; c < TemArrLis.Count - 1; c += 2)


{
Point3d Point = new
Point3d(Convert.ToDouble(TemArrLis[c]), Convert.ToDouble(TemArrLis[c + 1]), 0);
acPoly.AddVertexAt(acPoly.NumberOfVertices, new
Point2d(Cp.PointFromLatLong(Point).X, Cp.PointFromLatLong(Point).Y), 0, 0, 0);
}

Point3d P1 = acPoly.GetClosestPointTo(BRP, false);


var BRP2 = new Point2d(BRP.X, BRP.Y);

Line l = new Line(P1, BRP);

if (l.Length < minddis)


minddis = l.Length;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

NLines++;
}

reader = new StreamReader(TBLoadKML.Text);

Polyline[] Lines = new Polyline[NLines];

NLines = 1;

while (!reader.EndOfStream)
{
acPoly = new Polyline();

var Data = reader.ReadLine();


pbm++;

var Rute = "";


try
{
if (Data.Contains("<coordinates>"))
{

Rute = getBetween(Data, "<coordinates>",


"</coordinates>");

ArrayList TemArrLis = new ArrayList();


string[] TempArrayData;

string[] j = Rute.Split(' ');


for (int c = 0; c < j.Length; c++)
{
TempArrayData = j[c].Split(',');
TemArrLis.Add(TempArrayData[0]);
TemArrLis.Add(TempArrayData[1]);
}

for (int c = 0; c < TemArrLis.Count - 1; c += 2)


{
Point3d Point = new
Point3d(Convert.ToDouble(TemArrLis[c]), Convert.ToDouble(TemArrLis[c + 1]), 0);
acPoly.AddVertexAt(acPoly.NumberOfVertices, new
Point2d(Cp.PointFromLatLong(Point).X, Cp.PointFromLatLong(Point).Y), 0, 0, 0);
}

Point3d P1 = acPoly.GetClosestPointTo(BRP, false);


var BRP2 = new Point2d(BRP.X, BRP.Y);

Line l = new Line(P1, BRP);

if (l.Length == minddis)
{
Lines[0] = new Polyline();
Lines[0] = acPoly;
}
else
{
Lines[NLines] = new Polyline();
Lines[NLines] = acPoly;
NLines++;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

bool Fin = false;


int Poliline = 1;

OffSet(Lines[0], BRP, acTrans, acBlkTblRec, minddis);

while (!Fin)
{
try
{
Lines[0].JoinEntity(Lines[Poliline]);
//OffSet(Lines[Poliline], BRP, acTrans, acBlkTblRec,
minddis, OLines);

OffSet(Lines[0], BRP, acTrans, acBlkTblRec, minddis);


}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
finally
{
Poliline++;
}

if (Poliline == NLines - 1)
Fin = true;
}

Fin = false;
while (!Fin)
{
try
{
Lines[0].JoinEntity(Lines[Poliline]);
//OffSet(Lines[Poliline], BRP, acTrans, acBlkTblRec,
minddis, OLines);
}
catch (Exception)
{

}
finally
{
Poliline--;
}

if (Poliline == 0)
Fin = true;
}

acBlkTblRec.AppendEntity(Lines[0]);
acTrans.AddNewlyCreatedDBObject(Lines[0], true);

acTrans.Commit();
}

MessageBox.Show("Drawing Complete");
}

public void OffSet(Polyline Lines, Point3d BRP, Transaction acTrans,


BlockTableRecord acBlkTblRec, double minddis, Polyline P0)
{
try
{
var Dm = Application.DocumentManager.MdiActiveDocument;
Editor editor = Dm.Editor;
Point3d viewDir =
(Point3d)Application.GetSystemVariable("VIEWDIR");
orientation = GeometryTool.IsRightDirection(Lines as Curve,
BRP.TransformBy(editor.CurrentUserCoordinateSystem), viewDir.GetAsVector()) ? 1 : -
1;

DBObjectCollection acDbObjColl = Lines.GetOffsetCurves(minddis *


orientation);

foreach (Entity acEnt in acDbObjColl)


{
double Xdif;
double Ydif;

double min;

var pl = (acEnt) as Polyline;

Point3d Sp = pl.StartPoint;
Point3d Ep = pl.EndPoint;

Polyline l1 = new Polyline();

l1.AddVertexAt(l1.NumberOfVertices, new
Point2d(pl.StartPoint.X, pl.StartPoint.Y), 0, 0, 0);

l1.AddVertexAt(l1.NumberOfVertices, new
Point2d(P0.GetClosestPointTo(Ep, false).X, P0.GetClosestPointTo(Ep, false).Y), 0,
0, 0);

if (l1.Length > minddis * 2 - 1 && l1.Length < minddis * 2 + 1)


{
Xdif = l1.StartPoint.X - l1.EndPoint.X;
Ydif = l1.StartPoint.Y - l1.EndPoint.Y;
}
else
{
l1.StartPoint = Sp;
l1.EndPoint = P0.GetClosestPointTo(Sp, false);

Xdif = l1.StartPoint.X - l1.EndPoint.X;


Ydif = l1.StartPoint.Y - l1.EndPoint.Y;
}

Polyline PL = new Polyline();

PL.AddVertexAt(PL.NumberOfVertices, new Point2d((Sp.X + Xdif),


(Sp.Y + Ydif)), 0, 0, 0);

PL.AddVertexAt(PL.NumberOfVertices, new Point2d((Ep.X + Xdif),


(Ep.Y + Ydif)), 0, 0, 0);

acBlkTblRec.AppendEntity(PL);
acTrans.AddNewlyCreatedDBObject(PL, true);

P0.JoinEntity(PL);

}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

public Line OffSet(Polyline Lines, Point3d BRP, Transaction acTrans,


BlockTableRecord acBlkTblRec, double minddis)
{
var Dm = Application.DocumentManager.MdiActiveDocument;
Editor editor = Dm.Editor;
Point3d viewDir = (Point3d)Application.GetSystemVariable("VIEWDIR");
orientation = GeometryTool.IsRightDirection(Lines as Curve,
BRP.TransformBy(editor.CurrentUserCoordinateSystem), viewDir.GetAsVector()) ? 1 : -
1;

DBObjectCollection acDbObjColl = Lines.GetOffsetCurves(minddis *


orientation);

Polyline Pl = new Polyline();

foreach (Entity acEnt in acDbObjColl)


{
Pl = (acEnt) as Polyline;
acBlkTblRec.AppendEntity(Pl);
acTrans.AddNewlyCreatedDBObject(Pl, true);
}

Line L = new Line();


L.StartPoint = Pl.StartPoint;
L.EndPoint = Pl.EndPoint;
return L;
}
}

public class CParcel


{
public string Id;

public Polyline Body;

public bool Status = false;

public Point3d Cp;

public string Cable;

public string Type;

public CParcel(Polyline body)


{
Body = body;
}

public CParcel()
{

public void SetId(List<MText> Text, Polyline Pr)


{
double max = 0;
double min = 1000;

Point3d SP = new Point3d();


Point3d Ep = new Point3d();

Line L;

for (int c = 0; c < Body.NumberOfVertices; c++)


{
L = new Line(Body.GetPoint3dAt(c),
Pr.GetClosestPointTo(Body.GetPoint3dAt(c), false));
if (L.Length > max)
{
max = L.Length;
Ep = L.StartPoint;
}
else if (L.Length < min)
{
min = L.Length;
SP = L.StartPoint;
}
}

L = new Line(SP, Ep);


SP = L.GetPointAtDist(L.Length / 2);

//max = 1000;
min = 1000;

foreach (MText T in Text)


{
L = new Line(SP, T.Location);
if (L.Length < min)
{
min = L.Length;
string[] Data = T.Contents.Split('\n');
Id = Data[0];

Cp = new Point3d(T.Location.X, T.Location.Y + 10, 0);


}
}
}
}

public class CCable


{
public string Id;

public string Parent;

public Polyline Body;

public Polyline Buffer;

public bool Status = false;

public CCable()
{

public CCable(Polyline body, string id, string parent)


{
Body = body;
Id = id;
Parent = parent;
}

public override string ToString()


{
return "Id: " + Id + " Parent: " + Parent + " Status:" +
Status.ToString();
}
}

public class CHH


{
public string Id;

public CHH Terminal;

public Point3d Body;

public string Fibers;

public string Station;

public string type;

public List<CParcel> Parcels = new List<CParcel>();

public CHH()
{
}
}

class CDatabase
{
//Local Database
static SQLiteConnection conn;
static SQLiteDataReader dr;
static SQLiteCommand cmd;
static System.Data.DataTable dt;
public string DataSource = (@"C:\GenXCTool\DB\Plannin");

public CDatabase(string dataSource)


{
DataSource = dataSource;
}

public CDatabase()
{
}

//If there's any error, Write a Log

public static void Log(string text)


{
string file = @"C:\GenXCTool\DB\Log.txt";
string txt = text;

File.AppendAllText(file, txt + "\n");


}

//Functions Local Database


public void conect()
{
try
{
string Coneccion = ("Data Source = " + DataSource);
conn = new SQLiteConnection(Coneccion);
conn.Open();
}

catch (Exception Ex)


{
MessageBox.Show("Error al conectar con la base de datos= " +
Ex.ToString());
}
}

public void Save(string commd)


{
conect();

cmd = new SQLiteCommand(commd, conn);


cmd.ExecuteNonQuery();

conn.Close();
}

public void eliminar(string commd)


{
conect();

cmd = new SQLiteCommand(commd, conn);


cmd.ExecuteNonQuery();

conn.Close();
}

public void Update(string commd)


{
conect();

cmd = new SQLiteCommand(commd, conn);


cmd.ExecuteNonQuery();

conn.Close();

public System.Data.DataTable Select(string commd)


{
conect();

cmd = new SQLiteCommand(commd, conn);


dr = cmd.ExecuteReader();

dt = new System.Data.DataTable();

dt.Load(dr);

conn.Close();

return dt;
}
public Boolean Existe(string commd)
{
try
{
int q = 0;
conect();
cmd = new SQLiteCommand(commd, conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
q++;
}

if (q == 0)
return false;
else
return true;
}

catch (Exception Ex)


{
//MessageBox.Show("Error al Cargar datos de la base de datos = " +
Ex.ToString());

File.AppendAllText(@"C:\GenXCTool\Temp Arc\Data.txt", commd + "\


n");

return false;
}

finally
{
conn.Close();
}
}
}

public class CPostgres


{
static System.Data.SQLite.SQLiteConnection Con;
//static SQLiteDataAdapter Da;
static SQLiteDataReader Dr;
static SQLiteCommand Com;
static string DataSource = @"C:\GenXCTool\DB\dbPrueba.db";
//static string DataSource = @"C:\GenXCTool\DB\KmlConf.db";
//static string DataSource1 = @"C:\Users\genxc\OneDrive - GenXC Group\
Documents - IT\GenXC Apps\Dinanyeli\Planning.db";

public void ClassDB(string Ds)


{
DataSource = Ds;
}

public void ClassDB()


{

}
public static void Ds(string Ds)
{
DataSource = Ds;
}

public void Conectar(string DataSource)


{
try
{
string Conexion = ("Data Source = " + DataSource);
Con = new System.Data.SQLite.SQLiteConnection(Conexion);
Con.Open();
//MessageBox.Show("done");
}
catch (Exception Ex)
{
MessageBox.Show("Error al conectar con la base de datos= " +
Ex.ToString());
}
}

public void Set(string query, string DataSource)


{
try
{
Conectar(DataSource);
Com = new SQLiteCommand(query, Con);
Com.ExecuteNonQuery();
}
catch (Exception Ex)
{
MessageBox.Show("Error al guardar en la base de datos= " +
Ex.ToString() + "\n" + query);
}
finally
{
Con.Close();
}
}
public void Guardar(string query)
{
try
{
Conectar(DataSource);
Com = new SQLiteCommand(query, Con);
Com.ExecuteNonQuery();
MessageBox.Show("Cambios guardados Correctamente", "Guardar",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception Ex)
{
MessageBox.Show("Error al guardar en la base de datos= " +
Ex.ToString() + "\n" + query);
}
finally
{
Con.Close();
}
}
public Boolean Existe(string query)
{
try
{
int q = 0;
Conectar(DataSource);
Com = new SQLiteCommand(query, Con);
Dr = Com.ExecuteReader();
while (Dr.Read())
{
q++;
}
if (q == 0)
return false;
else
return true;
}
catch (Exception Ex)
{
MessageBox.Show("Error al Cargar datos de la base de datos = " +
Ex.ToString());
return false;
}
finally
{
Con.Close();
}
}
#region Foto

public Byte[] Get(string query)


{
Byte[] Dat = null;

try
{
Conectar(DataSource);
Com = new SQLiteCommand(query, Con);
Dr = Com.ExecuteReader();
while (Dr.Read())
{
Dat = (byte[])Dr[0];
}
}
catch (Exception Ex)
{
MessageBox.Show("Error al Conectar en la base de datos= " +
Ex.ToString());
}
finally
{
Con.Close();
}
return Dat;
}
public void GuardarFoto(byte[] B)
{
try
{
Conectar(DataSource);
Com = new SQLiteCommand("Insert into Imagen Values(@imagen)", Con);
Com.Parameters.AddWithValue("@imagen", B);
Com.ExecuteNonQuery();
MessageBox.Show("Cambios guardados Correctamente", "Guardar",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception Ex)
{
MessageBox.Show("Error al guardar en la base de datos= " +
Ex.ToString());
}
finally
{
Con.Close();
}
}
#endregion
public SQLiteCommand select(string query, string DataSource)
{
try
{
Conectar(DataSource);
Com = new SQLiteCommand(query, Con);
Com.ExecuteNonQuery();
}
catch (Exception Ex)
{
MessageBox.Show("Error al guardar en la base de datos= " +
Ex.ToString());
}
finally
{
//Con.Close();
}

return Com;
}

public void ExecuteQuery(string txtQuery)


{
Conectar(DataSource);
Com = Con.CreateCommand();
Com.CommandText = txtQuery;
Com.ExecuteNonQuery();
Con.Close();
}

public System.Data.DataTable Datatable1(string cod, string DataSource)


{
System.Data.DataTable dt = new System.Data.DataTable();
DataSet ds = new DataSet();
Conectar(DataSource);
Com = Con.CreateCommand();

SQLiteDataAdapter DB = new SQLiteDataAdapter(cod, Con);


ds.Reset();
DB.Fill(ds);
dt = ds.Tables[0];
Con.Close();

return dt;
}

public void Dispose()


{
Com.Dispose();
}
}

class CPolyline
{
public static void Lin2Pol(Polyline Pl, Line L)
{
Pl.AddVertexAt(Pl.NumberOfVertices, (new Point2d(L.StartPoint.X,
L.StartPoint.Y)), 0, 0, 0);

Pl.AddVertexAt(Pl.NumberOfVertices, (new Point2d(L.EndPoint.X,


L.EndPoint.Y)), 0, 0, 0);

Pl.Layer = L.Layer;
}
}

class CLayout
{
CBlock cBlock = new CBlock();

DBObjectCollection DB0 = new DBObjectCollection();

bool Layn = true;

CCentroide centroide = new CCentroide();

CPoint cPoint = new CPoint();

string Page = "";

public void Create_Viewport_Auto(CTransaction Trans, string Typ)


{
bool J = true;

int ViewportN = 0;

ArrayList Conts = new ArrayList();

while (J)
{
PromptSelectionOptions promptPointOptions = new
PromptSelectionOptions();
promptPointOptions.MessageForAdding = ("Select Cable");
PromptSelectionResult selectLinesFollow =
Trans.editor.GetSelection(promptPointOptions);
if (selectLinesFollow.Status == PromptStatus.OK)
{
foreach (ObjectId Obj in
selectLinesFollow.Value.GetObjectIds())
{
DBObject entity = Trans.transaction.GetObject(Obj,
OpenMode.ForWrite);
if (entity is Polyline)
{
Polyline Pl = (Polyline)entity;

double Cont = 0;

//List<BlockReference> Vports = new


List<BlockReference>();

PromptSelectionResult selectLinesFollow3 =
Trans.editor.SelectAll();
if (selectLinesFollow3.Status == PromptStatus.OK)
{
foreach (ObjectId Obj3 in
selectLinesFollow3.Value.GetObjectIds())
{
DBObject entity3 =
Trans.transaction.GetObject(Obj3, OpenMode.ForWrite);
if (entity3 is BlockReference)
{
BlockReference Br =
(BlockReference)entity3;

string name = Br.IsDynamicBlock ?


((BlockTableRecord)Br.DynamicBlockTableRecord.GetObject(OpenMode.ForRead)).Name :
Br.Name;

if (name == "Vport")
{
Point3dCollection AB = new
Point3dCollection();

DBObjectCollection dBObjectCollection =
new DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Db in
dBObjectCollection)
{
if (Db is Polyline)
{
Polyline Tpl = (Polyline)Db;

Tpl.IntersectWith(Pl,
Intersect.OnBothOperands, AB, IntPtr.Zero, IntPtr.Zero);

if (AB.Count > 0)
{
foreach (Point3d P in AB)
{
if
(Pl.GetDistAtPoint(P) > Cont)
{
Cont =
Pl.GetDistAtPoint(P);
}
}
}
}
}

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
if
(Convert.ToInt32(acAtt.TextString) > ViewportN)
ViewportN =
Convert.ToInt32(acAtt.TextString);
}
}
}
}
}
}

ViewportN = ViewportN + 1;

while (Cont < Pl.Length)


{
bool LengF = false;

ObjectId ObjId = Trans.blockTable["Vport"];

BlockReference Br = new
BlockReference(Pl.GetPointAtDist(Cont), ObjId);

Br.Layer = "Vport";

if (Br.Position != new Point3d(0, 0, 0))


{
Line TempAngle = new Line();

if (Pl.Length > Cont + 50)


{
TempAngle = new
Line(Pl.GetPointAtDist(Cont), Pl.GetPointAtDist(Cont + 50));
}
else if (Cont - 50 > 0)
{
TempAngle = new Line(Pl.GetPointAtDist(Cont
- 50), Pl.GetPointAtDist(Cont));
LengF = true;
}

double RealAngle = 0;

RealAngle = TempAngle.Angle;

if(Typ == "360")
{
Br.Rotation = RealAngle;
}

if(Typ == "0_90")
{
if (RealAngle >= 0 && RealAngle <=
Math.PI / 180 * 45)
{
Br.Rotation = 0;
}

else if (RealAngle >= Math.PI / 180 * 315)


{
Br.Rotation = 0;
}

else if (RealAngle >= Math.PI / 180 * 135


&& RealAngle <= Math.PI / 180 * 225)
{
Br.Rotation = Math.PI / 180 * 180;
}

else if (RealAngle > Math.PI / 180 * 45 &&


RealAngle < Math.PI / 180 * 135)
{
Br.Rotation = Math.PI / 180 * 90;
}

else if (RealAngle > Math.PI / 180 * 225 &&


RealAngle < Math.PI / 180 * 315)
{
Br.Rotation = Math.PI / 180 * 270;
}
}
else if (Typ == "0")
{
Point3d Pos = new Point3d(0, 0, 0);

DBObjectCollection DbObjCol = new


DBObjectCollection();

Br.Explode(DbObjCol);

foreach (DBObject Db in DbObjCol)


{
if (Db is Polyline)
{
Point3dCollection AB = new
Point3dCollection();

Polyline Tpl = (Polyline)Db;

double Hi =
Tpl.GetDistanceAtParameter(2) - Tpl.GetDistanceAtParameter(1);
double Le =
Tpl.GetDistanceAtParameter(1);

Pos = new Point3d(Br.Position.X -


Le / 2, Br.Position.Y - Hi / 2, Br.Position.Z);
}
}

Br = new BlockReference(Pos, ObjId);

Br.Layer = "Vport";

Br.Rotation = 0;

Trans.Insert(Br, true);

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
acAtt.TextString =
ViewportN.ToString("000");
ViewportN++;
}
}

DBObjectCollection dBObjectCollection = new


DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Db in dBObjectCollection)


{
if (Db is Polyline)
{
Point3dCollection AB = new
Point3dCollection();

Polyline Tpl = (Polyline)Db;

Tpl.IntersectWith(Pl,
Intersect.OnBothOperands, AB, IntPtr.Zero, IntPtr.Zero);

if (AB.Count > 0)
{
List<Point3d> LIP = new
List<Point3d>();

foreach (Point3d P in AB)


{
if (Pl.GetDistAtPoint(P) >
Cont)
Cont =
Pl.GetDistAtPoint(P);
}
}
}
}

if (!Conts.Contains(Cont.ToString()))
{
Conts.Add(Cont.ToString());
}
else
{
Cont += Cont;
}

if (LengF)
Cont += Pl.Length;
}
}
}
}
}
else
{
J = false;
}

J = false;
}
}

public void Create(CTransaction Trans)


{
List<BlockReference> LVp = Get_LVp(Trans);

while(Layn)
{
BlockReference Used_Vport = Get_Used_Vport(Trans, LVp);

if(Layn)
{
Create_Layout(Trans, Used_Vport);

SetLayoutOrder(Trans);

Create_Cover(Trans, Page);

Create_MatchLine(Trans, Used_Vport, LVp);

Create_North(Trans, Used_Vport);
}
}
}

public List<BlockReference> Get_LVp(CTransaction Trans)


{
List<BlockReference> LViewPort = new List<BlockReference>();

PromptSelectionResult selectLinesFollow = Trans.editor.SelectAll();


if (selectLinesFollow.Status == PromptStatus.OK)
{
foreach (ObjectId objectid in
selectLinesFollow.Value.GetObjectIds())
{
DBObject entityp = Trans.transaction.GetObject(objectid,
OpenMode.ForWrite);
if (entityp is BlockReference)
{
BlockReference Br = (BlockReference)entityp;

if (cBlock.GetBlockName(Br) == "Vport")
LViewPort.Add(entityp as BlockReference);
}
}
}

return LViewPort;
}

public BlockReference Get_Used_Vport(CTransaction Trans,


List<BlockReference> LVp)
{
BlockReference Used_Vport = new BlockReference(new Point3d(0, 0, 0),
Trans.blockTable["Vport"]);

double NearVport = 500;

PromptPointOptions promptPointOptions = new


PromptPointOptions("Point");
PromptPointResult selectStartPoint =
Trans.editor.GetPoint(promptPointOptions);
if (selectStartPoint.Status == PromptStatus.OK)
{
Point3d P3d = selectStartPoint.Value;

foreach (BlockReference Pl in LVp)


{
Point3dCollection P3dc = new Point3dCollection();

DBObjectCollection DB02 = new DBObjectCollection();

Pl.Explode(DB02);

foreach (DBObject Db in DB02)


{
if (Db is Polyline)
{
Polyline Tpol = (Polyline)Db;

Point3d Pc_Polyline_viewport =
centroide.GetCentroid(Tpol);

if (new Line(Pc_Polyline_viewport, P3d).Length <


NearVport)
{
NearVport = new Line(Pl.Position, P3d).Length;
Used_Vport = Pl;
}
}
}
}
}
else
{
Layn = false;
}

return Used_Vport;
}

private void Create_Layout(CTransaction Trans, BlockReference Used_Vport)


{
Viewport Vport = new Viewport();

Polyline PLC = new Polyline();

//Get Page In Vport


{
foreach (ObjectId attId in Used_Vport.AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
Page = acAtt.TextString;
}
}
}

//Get Polyline In Vport


{
DBObjectCollection DBOC = new DBObjectCollection();

Used_Vport.Explode(DBOC);

foreach (DBObject Db in DBOC)


{
if (Db is Polyline)
{
PLC = (Polyline)Db;
}
}
}

Point2d PC2d = centroide.GetCentroid_2d(PLC);

Application.SetSystemVariable("TILEMODE", 0);
Trans.editor.SwitchToPaperSpace();

LayoutManager acLayoutMgr = LayoutManager.Current;

if (acLayoutMgr.LayoutExists(Page))
{
acLayoutMgr.DeleteLayout(Page);
}

// Create the new layout with default settings


ObjectId objID = acLayoutMgr.CreateLayout(Page);
//lo coloque yo
Layout Aclayout = Trans.transaction.GetObject(objID, OpenMode.ForWrite)
as Layout;

//Set the layout current if it is not already


acLayoutMgr.CurrentLayout = Page;

//Set Page Setup


{
DBDictionary acPlSet =
Trans.transaction.GetObject(Trans.database.PlotSettingsDictionaryId,
OpenMode.ForRead) as DBDictionary;

if (acPlSet.Contains("11 X 17") == true)


{
PlotSettings plSet = acPlSet.GetAt("11 X
17").GetObject(OpenMode.ForRead) as PlotSettings;

Aclayout.UpgradeOpen();
Aclayout.CopyFrom(plSet);
}
}

//Creando y alineando Layout


{
var vpIds = Aclayout.GetViewports();
//configurando los viewports existentes
foreach (ObjectId vpId in vpIds)
{
Vport = Trans.transaction.GetObject(vpId, OpenMode.ForWrite) as
Viewport;
Vport.SetDatabaseDefaults();

Vport.CenterPoint = new Point3d(7.0534, 6.1598, 0);

Vport.Width = 13.3000;
Vport.Height = 8.3000;

Vport.CustomScale = (1.0 / 30.0);

Circle C = new Circle();


C.Radius = 40;
C.Center = new Point3d(PC2d.X, PC2d.Y, 0);

Vport.ViewCenter = PC2d;

Vport.On = true;
}

SpaceAlign_General(Trans, vpIds, PLC);


}
}

private void Create_MatchLine(CTransaction Trans, BlockReference


Used_Vport, List<BlockReference> LVp)
{
Trans.End_Trans();

Trans.Start_Trans();

LayoutManager.Current.CurrentLayout = "Model";
List<Polyline> LRutes = new List<Polyline>();

Point3dCollection P3dc = new Point3dCollection();

Point3dCollection CableIntersectionPoint = new Point3dCollection();

Polyline VpPolyOri = new Polyline();

DB0 = new DBObjectCollection();

Used_Vport.Explode(DB0);

foreach (DBObject Db in DB0)


{
if (Db is Polyline)
{
Polyline Tpol = (Polyline)Db;

for (int i = 0; i < Tpol.NumberOfVertices; i++)


{
P3dc.Add(Tpol.GetPoint3dAt(i));
}

P3dc.Add(Tpol.GetPoint3dAt(0));

VpPolyOri = Tpol;
}
}

List<Polyline> Lpl = new List<Polyline>();

PromptSelectionResult selectLinesFollow =
Trans.editor.SelectCrossingPolygon(P3dc);

if (selectLinesFollow.Status == PromptStatus.OK)
{
Application.SetSystemVariable("TILEMODE", 0);
Trans.editor.SwitchToPaperSpace();

LayoutManager acLayoutMgr = LayoutManager.Current;

acLayoutMgr.CurrentLayout = Page;

foreach (ObjectId objectid in


selectLinesFollow.Value.GetObjectIds())
{
DBObject entityp = Trans.transaction.GetObject(objectid,
OpenMode.ForWrite);

if (entityp is Polyline)
{
Polyline polyline = (Polyline)entityp;

if ((polyline.Layer == "PROPOSED_AERIAL" || polyline.Layer


== "PROPOSED_UG" || polyline.Layer == "PROPOSED_BURIED") && polyline.Length > 10)
{
Point3dCollection intersectionPoints = new
Point3dCollection();
polyline.IntersectWith(VpPolyOri,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
foreach (Point3d item in intersectionPoints)
{
CableIntersectionPoint.Add(item);
}

LRutes.Add(polyline);
}

Lpl.Add(polyline);

}
}
}

List<string> ml = new List<string>();


////polilineas
foreach (Polyline Pl in Lpl)
{
List<Point3d> LCorInter = new List<Point3d>();

double Max = 0;

double Min = Pl.Length;

Point3dCollection MyCableIntersectionPoint = new


Point3dCollection();

foreach (Point3d Pd3 in CableIntersectionPoint)


{
if (Pl.GetClosestPointTo(Pd3, false) == Pd3)
{
if (Pl.GetDistAtPoint(Pd3) > Max)
Max = Pl.GetDistAtPoint(Pd3);
else if (Pl.GetDistAtPoint(Pd3) < Min)
Min = Pl.GetDistAtPoint(Pd3);

MyCableIntersectionPoint.Add(Pd3);
}
}

double Dc = Max - Min;

List<BlockReference> LVportVec = new List<BlockReference>();

foreach (BlockReference Br in LVp)


{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
LVportVec.Add(Br);
}
}
}
}

for (int i = 0; i < LVportVec.Count; i++)


{
for (int i2 = i; i2 < LVportVec.Count; i2++)
{
if
(Pl.GetDistAtPoint(Pl.GetClosestPointTo(LVportVec[i].Position, false)) >
Pl.GetDistAtPoint(Pl.GetClosestPointTo(LVportVec[i2].Position, false)))
{
BlockReference Tem = LVportVec[i];
LVportVec[i] = LVportVec[i2];
LVportVec[i2] = Tem;
}
}
}

for (int i = 0; i < LVportVec.Count; i++)


{
MText mText = new MText();
mText.TextHeight = 10;
mText.Contents = i.ToString();
mText.Location = LVportVec[i].Position;
//Trans.Insert(mText, true);

foreach (ObjectId attId in


LVportVec[i].AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
//MessageBox.Show(acAtt.TextString);
}
}
}

List<BlockReference> LFVportVec = new List<BlockReference>();


List<BlockReference> LFVportVecU = new List<BlockReference>();

for (int i = 0; i < LVportVec.Count; i++)


{
foreach (ObjectId attId in
LVportVec[i].AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
if (acAtt.TextString == Page)
{
if (i > 0)
{
LFVportVec.Add(LVportVec[i - 1]);
}

if (LVportVec.Count > (i + 1))


{
LFVportVec.Add(LVportVec[i + 1]);
}
}
}
}
}

//MessageBox.Show("New Cable");

foreach (BlockReference BR in LFVportVec)


{
foreach (ObjectId attId in BR.AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
// MessageBox.Show(acAtt.TextString);
}
}
}

ArrayList IntvsVport = new ArrayList();

foreach (Point3d point3D in MyCableIntersectionPoint)


{
double Dist = 1500;

string PaGe = "";

BlockReference Tembr;

foreach (BlockReference Br in LFVportVec)


{
if (!LFVportVecU.Contains(Br))
{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
foreach (Point3d P3f in
intersectionPoints)
{
if (new Line(point3D, P3f).Length <
Dist)
{
Dist = new Line(point3D,
P3f).Length;

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
PaGe =
acAtt.TextString;
}
}
}
}
}
}
}
}
}

foreach (BlockReference Br in LFVportVec)


{
if (!LFVportVecU.Contains(Br))
{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
foreach (Point3d P3f in
intersectionPoints)
{
if (new Line(point3D, P3f).Length
== Dist)
{
LFVportVecU.Add(Br);

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{

//MessageBox.Show(acAtt.TextString);
}
}

}
}
}
}
}
}
}

IntvsVport.Add(point3D.ToString() + "\n" + PaGe);


}

Polyline Dest = new Polyline();

//rectangulo
ObjectId Obj_Id = Trans.blockTable["vPORT2"];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new BlockReference(new
Point3d(7.0536, 6.1437, 0), Obj_Id))
{
Br.ScaleFactors = new Scale3d(1, 1, 1);

Br.Layer = "Vport2";

Br.Rotation = Math.PI / 180 * 0;

BlockTableRecord Btr =
(BlockTableRecord)Trans.blockTable["vPORT2"].GetObject(OpenMode.ForWrite);

DBObjectCollection dBObjectCollection = new


DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Dest = Obj as Polyline;
}
}
}
}

//Matchlines

foreach (Point3d P in MyCableIntersectionPoint)


{
bool Der = false;

if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(cPoint.Regla_3(VpPolyOri, Dest, P),
false)) < Dest.GetDistanceAtParameter(1))
{
Der = true;

}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(cPoint.Regla_3(VpPolyOri, Dest, P),
false)) < Dest.GetDistanceAtParameter(2))
{
Der = true;
}

string BlockName = "MatchLine";

if (Der)
BlockName = "MatchLine2";

//if (Pl.GetClosestPointTo(P, false) == P)


{
Obj_Id = Trans.blockTable[BlockName];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new
BlockReference(cPoint.Regla_3(VpPolyOri, Dest, P), Obj_Id))
{
Br.Layer = "Vport2";
Br.ScaleFactors = new Scale3d(0.8, 0.8, 0.8);

if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(1))
{
Br.Rotation = Math.PI / 180 * 0;

//Br.Position = new Point3d(Br.Position.X,


Br.Position.Y + 0.1463, 0);

if (Br.Position.X > 12.4259)


{
Br.Position = new Point3d(12.4259,
Br.Position.Y, 0);
}
else if (Br.Position.X < 1.8937)
{
Br.Position = new Point3d(1.8937,
Br.Position.Y, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());

}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(2))
{
Br.Rotation = Math.PI / 180 * 270;

//Br.Position = new Point3d(Br.Position.X +


0.1463, Br.Position.Y, 0);

if (Br.Position.Y < 3.2861)


{
Br.Position = new
Point3d(Br.Position.X, 3.2861, 0);
}
else if (Br.Position.Y > 8.8263)
{
Br.Position = new
Point3d(Br.Position.X, 8.8263, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(3))
{
Br.Rotation = Math.PI / 180 * 0;

//Br.Position = new Point3d(Br.Position.X,


Br.Position.Y - 0.1463, 0);

if (Br.Position.X > 12.3174)


{
Br.Position = new Point3d(12.3174,
Br.Position.Y, 0);
}
else if (Br.Position.X < 1.7825)
{
Br.Position = new Point3d(1.7825,
Br.Position.Y, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
else
{
Br.Rotation = Math.PI / 180 * 270;

//Br.Position = new Point3d(Br.Position.X -


0.1463, Br.Position.Y, 0);

if (Br.Position.Y < 3.3957)


{
Br.Position = new
Point3d(Br.Position.X, 3.3957, 0);
}
else if (Br.Position.Y > 8.9395)
{
Br.Position = new
Point3d(Br.Position.X, 8.9395, 0);
}

// MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
string Pag = "";

foreach (string S in IntvsVport)


{
if (S.Contains(P.ToString()))
{
Pag = S.Split('\n')[1];
}
}

if (!ml.Contains(Pag))
{

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

BlockTableRecord Btr =
(BlockTableRecord)blockTable[BlockName].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj =
id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef =
new AttributeReference())
{

attRef.SetAttributeFromBlock(attDef, Br.BlockTransform);
attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);

Trans.transaction.AddNewlyCreatedDBObject(attRef, true);

if (attRef.Tag ==
"DESCRIPTION")
{
attRef.TextString = "SEE
DRAWING# ";
}
else if (attRef.Tag == "PAGE"
|| attRef.Tag == "REF#")
{

attRef.TextString = Pag;
}
else
{
attRef.TextString = "";
}
}
}
}

DynamicBlockReferencePropertyCollection
pcFST = Br.DynamicBlockReferencePropertyCollection;

foreach (DynamicBlockReferenceProperty dP
in pcFST)
{
if (dP.PropertyName == "Flip state1")
{
/* Trans.editor.WriteMessage(
$"\nName: {dP.PropertyName} " +
$"Type code: {dP.PropertyTypeCode}
" +
$"Unit type: {dP.UnitsType} " +
$"Allowed values: [{string.Join(",
", dP.GetAllowedValues())}]");*/

//dP.Value = "1";
}
}

bool Del = false;

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
if (acAtt.TextString == "")
{
Del = true;
}
}
}

if (Del)
{
Br.Erase();
}
ml.Add(Pag);
}
}
}
}
}
}
}
}

public void Create_Cover(CTransaction Trans, string Page)


{
Trans.End_Trans();

Trans.Start_Trans();

BlockReference Br = new BlockReference(new Point3d(8.3815, 5.3826, 0),


Trans.blockTable["COVER"]);

Br.ScaleFactors = new Scale3d(1, 1, 1);

Br.Layer = "Vport2";

DynamicBlockReferencePropertyCollection DBRC =
Br.DynamicBlockReferencePropertyCollection;

foreach (DynamicBlockReferenceProperty prop in DBRC)


{
if (prop.PropertyName == "PAGE")
{
prop.Value = Page;
}
}

Trans.Insert(Br, false);
}

public void Create_North(CTransaction Trans, BlockReference Used_Vport)


{
Trans.End_Trans();

Trans.Start_Trans();

LayoutManager.Current.CurrentLayout = "Model";

Point3d PC = new Point3d(0, 0, 0);

PromptSelectionResult PSR = Trans.editor.SelectAll();


if (PSR.Status == PromptStatus.OK)
{
foreach (ObjectId Obj in PSR.Value.GetObjectIds())
{
DBObject DbObj = Trans.transaction.GetObject(Obj,
OpenMode.ForWrite);

if (DbObj is BlockReference)
{
BlockReference Br = DbObj as BlockReference;

string name = Br.IsDynamicBlock ?


((BlockTableRecord)Br.DynamicBlockTableRecord.GetObject(OpenMode.ForWrite)).Name :
Br.Name;

if (name == "NORTH ARROW")


{
PC = new Point3d(Br.Position.X, Br.Position.Y, 0);
}
}
}
}

Line L = new Line();


L.StartPoint = PC;
L.EndPoint = new Point3d(PC.X + 1, PC.Y, PC.Z);

var ang = L.GetFirstDerivative(L.GetParameterAtPoint(L.StartPoint));


ang = ang.GetNormal() * 0.53;
ang = ang.TransformBy(Matrix3d.Rotation(Used_Vport.Rotation, L.Normal,
Point3d.Origin));

var Li = new Line(L.GetPointAtDist(0) + ang, L.GetPointAtDist(0) -


ang);

//Trans.Insert(Li, true);

Polyline PLC = new Polyline();

PLC.AddVertexAt(PLC.NumberOfVertices, new Point2d(Li.StartPoint.X,


Li.StartPoint.Y), 0, 0, 0);
PLC.AddVertexAt(PLC.NumberOfVertices, new Point2d(Li.EndPoint.X,
Li.EndPoint.Y), 0, 0, 0);

// Trans.Insert(PLC, true);

Application.SetSystemVariable("TILEMODE", 0);
Trans.editor.SwitchToPaperSpace();

LayoutManager acLayoutMgr = LayoutManager.Current;

acLayoutMgr.CurrentLayout = Page;

Layout Aclayout =
Trans.transaction.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout),
OpenMode.ForRead) as Layout;

Viewport acVport = new Viewport();


acVport.SetDatabaseDefaults();
acVport.CenterPoint = new Point3d(13.1869, 1.5377, 0);
acVport.Width = 0.8681;
acVport.Height = 0.8681;
acVport.CustomScale = 1;

acVport.ViewCenter = new Point2d(PC.X,PC.Y);

Trans.Insert(acVport, false);

acVport.On = true;

SpaceAlign_General_North(Trans, acVport, PLC);

LayoutManager.Current.CurrentLayout = "Model";
}

public void SpaceAlign2(Polyline Pl, Viewport Vp)


{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
var documentloc = doc.LockDocument();

ArrayList Lp = new ArrayList();

using (var tr = db.TransactionManager.StartTransaction())


{
{
var modelPt1 =
Pl.GetPointAtDist((Pl.GetDistAtPoint(Pl.GetPoint3dAt(1)) +
Pl.GetDistAtPoint(Pl.GetPoint3dAt(2))) / 2);
Circle C = new Circle();
C.Radius = 15;
C.Center = modelPt1;
//Trans.Insert(C, true);

var modelPt2 =
Pl.GetPointAtDist((Pl.GetDistAtPoint(Pl.GetPoint3dAt(3)) + Pl.Length) / 2);
C = new Circle();
C.Radius = 15;
C.Center = modelPt2;
//Trans.Insert(C, true);

modelPt1 =
modelPt1.TransformBy(ed.CurrentUserCoordinateSystem);
modelPt2 =
modelPt2.TransformBy(ed.CurrentUserCoordinateSystem);

C = new Circle();
C.Radius = 15;
C.Center = centroide.GetCentroid(Pl);
//Trans.Insert(C, true);

// ed.SwitchToPaperSpace();
var paperPt2 = new Point3d(1.2694, 6.1092, 0);
C = new Circle();
C.Radius = 2;
C.Center = paperPt2;
//Trans.Insert(C, false);

var paperPt1 = new Point3d(13.5880, 6.1092, 0);


C = new Circle();
C.Radius = 2;
C.Center = paperPt1;
//Trans.Insert(C, false);

paperPt1 =
paperPt1.TransformBy(ed.CurrentUserCoordinateSystem);
paperPt2 =
paperPt2.TransformBy(ed.CurrentUserCoordinateSystem);

var ucs = ed.CurrentUserCoordinateSystem;


AlignSpace(Vp, modelPt1, modelPt2, paperPt1, paperPt2);

//ed.SwitchToModelSpace();
}
tr.Commit();
}
}

private void SetLayoutOrder(CTransaction Trans)


{
string[] array =
((IEnumerable<string>)GetLayoutNames()).OrderBy<string, string>((Func<string,
string>)(l => l)).ToArray<string>();
Database workingDatabase = HostApplicationServices.WorkingDatabase;
LayoutManager current = LayoutManager.Current;
int num = 1;
foreach (string name in array)
{
(Trans.transaction.GetObject(current.GetLayoutId(name),
Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite) as Layout).TabOrder = num;
++num;
}
}

public string[] GetLayoutNames()


{
List<Layout> source = new List<Layout>();
Database workingDatabase = HostApplicationServices.WorkingDatabase;
using (Transaction transaction =
workingDatabase.TransactionManager.StartTransaction())
{
foreach (DBDictionaryEntry dbDictionaryEntry in
(DBDictionary)transaction.GetObject(workingDatabase.LayoutDictionaryId,
Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite))
{
ObjectId id = dbDictionaryEntry.Value;
source.Add(transaction.GetObject(id,
Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite) as Layout);
}
transaction.Commit();
}
int count = source.Count;
return source.Where<Layout>((Func<Layout, bool>)(l =>
l.LayoutName.ToUpper() != "MODEL")).Select<Layout, string>((Func<Layout, string>)(l
=> l.LayoutName)).ToArray<string>();
}

public void SpaceAlign_General(CTransaction Trans, ObjectIdCollection


vpIds, Polyline Pl)
{

foreach (ObjectId vpId in vpIds)


{
Viewport Vport = Trans.transaction.GetObject(vpId,
OpenMode.ForWrite) as Viewport;

var modelPt1 =
Pl.GetPointAtDist(Pl.GetDistAtPoint(Pl.GetPoint3dAt(3)) + (Pl.Length -
Pl.GetDistAtPoint(Pl.GetPoint3dAt(3))) / 2);
//richTextBox1.Text += modelPt1.ToString() + "\n";

var modelPt2 =
Pl.GetPointAtDist(Pl.GetDistAtPoint(Pl.GetPoint3dAt(1)) +
(Pl.GetDistAtPoint(Pl.GetPoint3dAt(2)) - Pl.GetDistAtPoint(Pl.GetPoint3dAt(1))) /
2);
//richTextBox1.Text += modelPt2.ToString() + "\n";

modelPt1 =
modelPt1.TransformBy(Trans.editor.CurrentUserCoordinateSystem);
modelPt2 =
modelPt2.TransformBy(Trans.editor.CurrentUserCoordinateSystem);

Trans.editor.SwitchToPaperSpace();

var paperPt1 = new Point3d(0.4044, 6.1601, 0);


//richTextBox1.Text += paperPt1.ToString() + "\n";

var paperPt2 = new Point3d(13.7034, 6.1601, 0);


//richTextBox1.Text += paperPt2.ToString() + "\n";

//Verify Points
{
Circle C = new Circle
{
Center = modelPt1,
Radius = 5
};

// Trans.Insert(C, true);

C = new Circle
{
Center = modelPt2,
Radius = 5
};

// Trans.Insert(C, true);

C = new Circle
{
Center = paperPt1,
Radius = 1
};

// Trans.Insert(C, false);

C = new Circle
{
Center = paperPt2,
Radius = 1
};

// Trans.Insert(C, false);
}

paperPt1 =
paperPt1.TransformBy(Trans.editor.CurrentUserCoordinateSystem);
paperPt2 =
paperPt2.TransformBy(Trans.editor.CurrentUserCoordinateSystem);

var ucs = Trans.editor.CurrentUserCoordinateSystem;


AlignSpace(Vport, modelPt1, modelPt2, paperPt1, paperPt2);
}
}

public void SpaceAlign_General_North(CTransaction Trans, Viewport vpIds,


Polyline Pl)
{
var modelPt1 = Pl.EndPoint;
//richTextBox1.Text += modelPt1.ToString() + "\n";

var modelPt2 = Pl.StartPoint;


//richTextBox1.Text += modelPt2.ToString() + "\n";

modelPt1 =
modelPt1.TransformBy(Trans.editor.CurrentUserCoordinateSystem);
modelPt2 =
modelPt2.TransformBy(Trans.editor.CurrentUserCoordinateSystem);

Trans.editor.SwitchToPaperSpace();

var paperPt1 = new Point3d(12.8216, 1.5396, 0);


//richTextBox1.Text += paperPt1.ToString() + "\n";

var paperPt2 = new Point3d(13.6897, 1.5396, 0);


//richTextBox1.Text += paperPt2.ToString() + "\n";

//Verify Points
{
Circle C = new Circle
{
Center = modelPt1,
Radius = 5
};

// Trans.Insert(C, true);

C = new Circle
{
Center = modelPt2,
Radius = 5
};

// Trans.Insert(C, true);

C = new Circle
{
Center = paperPt1,
Radius = 1
};

// Trans.Insert(C, false);

C = new Circle
{
Center = paperPt2,
Radius = 1
};

// Trans.Insert(C, false);
}

paperPt1 =
paperPt1.TransformBy(Trans.editor.CurrentUserCoordinateSystem);
paperPt2 =
paperPt2.TransformBy(Trans.editor.CurrentUserCoordinateSystem);

var ucs = Trans.editor.CurrentUserCoordinateSystem;


AlignSpace(vpIds, modelPt1, modelPt2, paperPt1, paperPt2);
}

public void SpaceAlign2(Polyline Pl)


{
//this.Hide();

//MessageBox.Show(objectId.ToString());

var doc = Application.DocumentManager.MdiActiveDocument;


var db = doc.Database;
var ed = doc.Editor;
var documentloc = doc.LockDocument();

ArrayList Lp = new ArrayList();

using (var tr = db.TransactionManager.StartTransaction())


{
Viewport vp;
if ((short)Application.GetSystemVariable("cvport") == 1)
{
PromptSelectionOptions promptPointOptions = new
PromptSelectionOptions();
promptPointOptions.MessageForAdding = ("\nSelect Viewport: ");
PromptSelectionResult selectLinesFollow =
ed.GetSelection(promptPointOptions);
if (selectLinesFollow.Status == PromptStatus.OK)
{
foreach (ObjectId objectId in
selectLinesFollow.Value.GetObjectIds())
{
DBObject dBObject = tr.GetObject(objectId,
OpenMode.ForWrite);
if (dBObject is Viewport)
{
vp = (Viewport)tr.GetObject(objectId,
OpenMode.ForWrite);
ed.SwitchToModelSpace();
Application.SetSystemVariable("cvport", vp.Number);

/* var ppo = new PromptPointOptions("\nFirst


alignment point in model space: ");
var ppr = ed.GetPoint(ppo);
if (ppr.Status != PromptStatus.OK)
return;*/
var modelPt1 = Pl.StartPoint;
//richTextBox1.Text += modelPt1.ToString() + "\n";

/* ppo.Message = "\nSecond alignment point in model


space: ";
ppo.UseBasePoint = true;
ppo.BasePoint = modelPt1;
ppr = ed.GetPoint(ppo);
if (ppr.Status != PromptStatus.OK)
return;*/
var modelPt2 = Pl.GetPoint3dAt(2);
//richTextBox1.Text += modelPt2.ToString() + "\n";

modelPt1 =
modelPt1.TransformBy(ed.CurrentUserCoordinateSystem);
modelPt2 =
modelPt2.TransformBy(ed.CurrentUserCoordinateSystem);

ed.SwitchToPaperSpace();

var paperPt1 = new Point3d(5.8301, 11.219, 0);


////richTextBox1.Text += paperPt1.ToString() + "\
n";

var paperPt2 = new Point3d(14.8301, 4.219, 0);


//richTextBox1.Text += paperPt2.ToString() + "\n";

paperPt1 =
paperPt1.TransformBy(ed.CurrentUserCoordinateSystem);
paperPt2 =
paperPt2.TransformBy(ed.CurrentUserCoordinateSystem);

var ucs = ed.CurrentUserCoordinateSystem;


AlignSpace(vp, modelPt1, modelPt2, paperPt1,
paperPt2);

ed.SwitchToModelSpace();
}
}
}
}
else
{
vp = (Viewport)tr.GetObject(ed.ActiveViewportId,
OpenMode.ForWrite);

var modelPt1 = Pl.StartPoint;

var modelPt2 = Pl.GetPoint3dAt(2);


modelPt1 =
modelPt1.TransformBy(ed.CurrentUserCoordinateSystem);
modelPt2 =
modelPt2.TransformBy(ed.CurrentUserCoordinateSystem);

ed.SwitchToPaperSpace();

var paperPt1 = new Point3d(5.8301, 11.219, 0);


//richTextBox1.Text += paperPt1.ToString() + "\n";

var paperPt2 = new Point3d(14.8301, 4.219, 0);


//richTextBox1.Text += paperPt2.ToString() + "\n";

paperPt1 =
paperPt1.TransformBy(ed.CurrentUserCoordinateSystem);
paperPt2 =
paperPt2.TransformBy(ed.CurrentUserCoordinateSystem);

var ucs = ed.CurrentUserCoordinateSystem;


AlignSpace(vp, modelPt1, modelPt2, paperPt1, paperPt2);

ed.SwitchToModelSpace();

tr.Commit();
}

//this.Show();
}

private void AlignSpace(Viewport vp, Point3d modelPoint1, Point3d


modelPoint2, Point3d paperPoint1, Point3d paperPoint2)
{
if (!vp.IsWriteEnabled)
vp.UpgradeOpen();

var locked = vp.Locked;


if (locked) vp.Locked = false;

modelPoint2 = new Point3d(modelPoint2.X, modelPoint2.Y, modelPoint1.Z);


var psdcs2wcs = DCS2WCS(vp) * PSDCS2DCS(vp);
var wcsPaperPt2 = new Point3d(paperPoint2.X, paperPoint2.Y,
paperPoint1.Z).TransformBy(psdcs2wcs);
var wcsPaperPt1 = paperPoint1.TransformBy(psdcs2wcs);
var vector1 = modelPoint1.GetVectorTo(modelPoint2);
var vector2 = wcsPaperPt1.GetVectorTo(wcsPaperPt2);
double rotation = vector1.GetAngleTo(vector2, Vector3d.ZAxis);
vp.TwistAngle += rotation;
var scale = vector2.Length / vector1.Length;
vp.CustomScale *= scale;
vp.UpdateDisplay();
wcsPaperPt1 = paperPoint1.TransformBy(DCS2WCS(vp) * PSDCS2DCS(vp));
var wcsPaperPt2d = new Point2d(wcsPaperPt1.X, wcsPaperPt1.Y);
vp.ViewCenter += new Vector2d(modelPoint1.X - wcsPaperPt2d.X,
modelPoint1.Y - wcsPaperPt2d.Y).TransformBy(Matrix2d.Rotation(rotation,
wcsPaperPt2d));

vp.Locked = locked;
}

public Matrix3d DCS2WCS(Viewport vp)


{
return
Matrix3d.Rotation(-vp.TwistAngle, vp.ViewDirection, vp.ViewTarget)
*
Matrix3d.Displacement(vp.ViewTarget - Point3d.Origin) *
Matrix3d.PlaneToWorld(vp.ViewDirection);
}

public Matrix3d WCS2DCS(Viewport vp)


{
return DCS2WCS(vp).Inverse();
}

public static Matrix3d DCS2PSDCS(Viewport vp)


{
return
Matrix3d.Scaling(vp.CustomScale, vp.CenterPoint) *
Matrix3d.Displacement(vp.CenterPoint.GetAsVector()) *
Matrix3d.Displacement(new Vector3d(-vp.ViewCenter.X, -
vp.ViewCenter.Y, 0.0));
}

public Matrix3d PSDCS2DCS(Viewport vp)


{
return DCS2PSDCS(vp).Inverse();
}

public void Clayout_Manual(CTransaction Trans)


{
CPoint Poi = new CPoint();

bool Layn = true;

Point3d P3d = new Point3d();

string name = "";

List<BlockReference> LViewPort = new List<BlockReference>();

List<Polyline> Cables = new List<Polyline>();

List<BlockReference> Vecinos = new List<BlockReference>();

Point3dCollection P3dc;
PromptPointOptions promptPointOptions = new
PromptPointOptions("Point");
PromptPointResult selectStartPoint =
Trans.editor.GetPoint(promptPointOptions);
if (selectStartPoint.Status == PromptStatus.OK)
{
P3d = selectStartPoint.Value;
}
else
{
Layn = false;
}

if (Layn)
{
PromptSelectionResult selectLinesFollow = Trans.editor.SelectAll();
if (selectLinesFollow.Status == PromptStatus.OK)
{
foreach (ObjectId objectid in
selectLinesFollow.Value.GetObjectIds())
{
DBObject entityp = Trans.transaction.GetObject(objectid,
OpenMode.ForWrite);
if (entityp is BlockReference)
{
BlockReference Br = (BlockReference)entityp;

name = Br.IsDynamicBlock ?
((BlockTableRecord)Br.DynamicBlockTableRecord.GetObject(OpenMode.ForWrite)).Name :
Br.Name;

if (name == "Vport")
LViewPort.Add(entityp as BlockReference);
}

}
}

double dist = 5000;

ObjectId ObjId = Trans.blockTable["Vport"];

BlockReference Used_Vport = new BlockReference(new Point3d(0, 0,


0), ObjId);

double NearVport = 5000;

foreach (BlockReference Pl in LViewPort)


{
//if(new Line(Pl.Position,P3d).Length < NearVport)
{
P3dc = new Point3dCollection();

DBObjectCollection DB0 = new DBObjectCollection();

Pl.Explode(DB0);

foreach (DBObject Db in DB0)


{
if (Db is Polyline)
{
Polyline Tpol = (Polyline)Db;

Point3d Pc_Polyline_viewport =
Poi.GetCentroid(Tpol);

if (new Line(Pc_Polyline_viewport, P3d).Length <


NearVport)
{
NearVport = new Line(Pl.Position, P3d).Length;
Used_Vport = Pl;
}
}
}
}
}

{
P3dc = new Point3dCollection();

DBObjectCollection DB0 = new DBObjectCollection();

Used_Vport.Explode(DB0);

foreach (DBObject Db in DB0)


{
if (Db is Polyline)
{
Polyline Tpol = (Polyline)Db;

for (int i = 0; i < Tpol.NumberOfVertices; i++)


{
P3dc.Add(Tpol.GetPoint3dAt(i));
}

P3dc.Add(Tpol.GetPoint3dAt(0));
}
}

Polyline PLC = new Polyline();


PLC.Layer = "0";

foreach (Point3d P in P3dc)


{
PLC.AddVertexAt(PLC.NumberOfVertices, new Point2d(P.X,
P.Y), 0, 0, 0);
}

//Trans.Insert(PLC, true);

string Page = "000";

foreach (ObjectId attId in Used_Vport.AttributeCollection)


{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
Page = acAtt.TextString;
// MessageBox.Show(Page);
}

//MessageBox.Show(acAtt.Tag + " " + acAtt.TextString);


}

Polyline VpPolyOri = new Polyline();

Polyline VpPolyDes = new Polyline();

DBObjectCollection collection = new DBObjectCollection();

Used_Vport.Explode(collection);

foreach (DBObject item in collection)


{
if (item is Polyline)
VpPolyOri = (Polyline)item;
}

Create_Layout(P3dc, Page, Trans);


}
}
else
{
Trans.End_Trans();
}
}

private void Create_Layout(Point3dCollection P3dc, string Page,


CTransaction Trans)
{
CPoint Poi = new CPoint();

int CabCon = 1;
int Hhcon = 0;
double MaxX = 0;
double MinX = 0;
double MaxY = 0;
double MinY = 0;
double MaxWidth = 0;

Polyline Space = new Polyline();

Polyline PLC = new Polyline();

Polyline VpPolyOri = PLC;

//Polyline VpPolyDes;

List<Polyline> LCable = new List<Polyline>();

Point3dCollection CableIntersectionPoint = new Point3dCollection();

foreach (Point3d P in P3dc)


PLC.AddVertexAt(PLC.NumberOfVertices, new Point2d(P.X, P.Y), 0, 0,
0);
//Trans.Insert(PLC,true);

Polyline PL05 = new Polyline();

List<BlockReference> LBR = new List<BlockReference>();


List<Polyline> Lpl = new List<Polyline>();

List<BlockReference> LVp = new List<BlockReference>();


ObjectIdCollection oidC = new ObjectIdCollection();

PromptSelectionResult selectLinesFollow =
Trans.editor.SelectCrossingPolygon(P3dc);

if (selectLinesFollow.Status == PromptStatus.OK)
{
PromptSelectionResult selectLines = Trans.editor.SelectAll();
if (selectLines.Status == PromptStatus.OK)
{
foreach (ObjectId objectid in selectLines.Value.GetObjectIds())
{
DBObject entityp = Trans.transaction.GetObject(objectid,
OpenMode.ForWrite);
if (entityp is BlockReference)
{
BlockReference Br = (BlockReference)entityp;

string name = Br.IsDynamicBlock ?


((BlockTableRecord)Br.DynamicBlockTableRecord.GetObject(OpenMode.ForWrite)).Name :
Br.Name;

if (name == "Vport")
{
LVp.Add(Br);
}
}
}
}

Point3d PC3d = Poi.GetCentroid(PLC);


Point2d PC2d = new Point2d(PC3d.X, PC3d.Y);

Application.SetSystemVariable("TILEMODE", 0);
Trans.editor.SwitchToPaperSpace();

LayoutManager acLayoutMgr = LayoutManager.Current;

if (acLayoutMgr.LayoutExists(Page))
{
acLayoutMgr.DeleteLayout(Page);
}

// Create the new layout with default settings


ObjectId objID = acLayoutMgr.CreateLayout(Page);
//lo coloque yo
Layout Aclayout = Trans.transaction.GetObject(objID,
OpenMode.ForWrite) as Layout;
{
DBDictionary acPlSet =
Trans.transaction.GetObject(Trans.database.PlotSettingsDictionaryId,
OpenMode.ForRead) as DBDictionary;
if (acPlSet.Contains("11-17") == true)
{
PlotSettings plSet = acPlSet.GetAt("11-
17").GetObject(OpenMode.ForRead) as PlotSettings;

Aclayout.CopyFrom(plSet);
}
}
// Set the layout current if it is not already
acLayoutMgr.CurrentLayout = Page;

var vpIds = Aclayout.GetViewports();


//configurando los viewports existentes
foreach (ObjectId vpId in vpIds)
{
var vp2 = Trans.transaction.GetObject(vpId, OpenMode.ForWrite)
as Viewport;

//MessageBox.Show("Vpid = " + vpId.ToString());

//vp2.ViewCenter = PC2d;
vp2.CenterPoint = new Point3d(10.2319, 7.7190, 0);

//vp2.StandardScale = StandardScaleType.Scale1To8inchAnd1ft;
//
vp2.Width = 9;
vp2.Height = 7;

vp2.CustomScale = (1.0 / 30.0);

//Application.ShowAlertDialog(vp2.ViewCenter.ToString());

Circle C = new Circle();


C.Radius = 40;
C.Center = new Point3d(PC2d.X, PC2d.Y, 0);

vp2.ViewCenter = PC2d;

//vp2.ViewCenter = new Point2d(1282, 205);

vp2.On = true;
//freezing los layer dentro del viewport
ObjectIdCollection Layers = new ObjectIdCollection();
ObjectIdCollection Layers2 = new ObjectIdCollection();
LayerTable acLyrTbl;
acLyrTbl =
Trans.transaction.GetObject(Trans.database.LayerTableId, OpenMode.ForRead) as
LayerTable;
foreach (ObjectId acObjId in acLyrTbl)
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = Trans.transaction.GetObject(acObjId,
OpenMode.ForRead) as LayerTableRecord;

if (acLyrTblRec.Name == "FST-Schematic" || acLyrTblRec.Name


== "Vport")
{
Layers.Add(acLyrTblRec.ObjectId);
}
else
{
Layers2.Add(acLyrTblRec.ObjectId);
}
}
// vp2.FreezeLayersInViewport(Layers.GetEnumerator());
// vp2.ThawLayersInViewport(Layers2.GetEnumerator());
// vp2.Locked = true;
}

////cover
ObjectId Obj_Id = Trans.blockTable["AT&T_COVER"];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new BlockReference(new Point3d(9.5,
6.5, 0), Obj_Id))
{
Br.ScaleFactors = new Scale3d(1, 1, 1);

Br.Layer = "Vport2";

DynamicBlockReferencePropertyCollection DBRC =
Br.DynamicBlockReferencePropertyCollection;

foreach (DynamicBlockReferenceProperty prop in DBRC)


{
if (prop.PropertyName == "PAGE")
{
prop.Value = Page;
}
}

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

BlockTableRecord Btr =
(BlockTableRecord)blockTable["AT&T_COVER"].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj = id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef = new
AttributeReference())
{
attRef.SetAttributeFromBlock(attDef,
Br.BlockTransform);
attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);

Trans.transaction.AddNewlyCreatedDBObject(attRef, true);

}
}
}
}
}

////datos
Obj_Id = Trans.blockTable["BURIED STAMP"];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new BlockReference(new
Point3d(15.1306, 5.3922, 0), Obj_Id))
{
Br.ScaleFactors = new Scale3d(10 / 12, 10 / 12, 10 / 12);

Br.Layer = "Vport2";

DynamicBlockReferencePropertyCollection DBRC =
Br.DynamicBlockReferencePropertyCollection;

foreach (DynamicBlockReferenceProperty prop in DBRC)


{
prop.Value = Page;
}

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

BlockTableRecord Btr = (BlockTableRecord)blockTable["BURIED


STAMP"].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj = id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef = new
AttributeReference())
{
attRef.SetAttributeFromBlock(attDef,
Br.BlockTransform);
attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);

Trans.transaction.AddNewlyCreatedDBObject(attRef, true);

attRef.TextString = Page;
}
}
}
}
}

////detalles
Obj_Id = Trans.blockTable["Placement_Detail"];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
//using (BlockReference Br = new BlockReference(new
Point3d(16.4035, 9.4734, 0), Obj_Id))
using (BlockReference Br = new BlockReference(new
Point3d(16.2434, 10.1228, 0), Obj_Id))
{
//Br.ScaleFactors = new Scale3d(0.8, 0.8, 0.8);

Br.Layer = "Vport2";

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

//Br.Rotation = Math.PI / 180 * 270;

BlockTableRecord Btr =
(BlockTableRecord)blockTable["Placement_Detail"].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj = id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef = new
AttributeReference())
{
attRef.SetAttributeFromBlock(attDef,
Br.BlockTransform);

attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);
Trans.transaction.AddNewlyCreatedDBObject(attRef, true);

attRef.TextString = "";
}
}
}
}
}

Polyline Dest = new Polyline();

//rectangulo
Obj_Id = Trans.blockTable["vPORT2"];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new BlockReference(new
Point3d(10.2319, 7.7190, 0), Obj_Id))
{
Br.ScaleFactors = new Scale3d(1, 1, 1);

Br.Layer = "Vport2";

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

Br.Rotation = Math.PI / 180 * 0;

BlockTableRecord Btr =
(BlockTableRecord)blockTable["vPORT2"].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj = id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef = new
AttributeReference())
{
attRef.SetAttributeFromBlock(attDef,
Br.BlockTransform);

attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);

Trans.transaction.AddNewlyCreatedDBObject(attRef, true);
}
}
}

DBObjectCollection dBObjectCollection = new


DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Dest = Obj as Polyline;
}
}
}
}
List<string> ml = new List<string>();
////polilineas
///

foreach (Polyline Pl in Lpl)


{
List<Point3d> LCorInter = new List<Point3d>();

double Max = 0;

double Min = Pl.Length;

Point3dCollection MyCableIntersectionPoint = new


Point3dCollection();

foreach (Point3d Pd3 in CableIntersectionPoint)


{
if (Pl.GetClosestPointTo(Pd3, false) == Pd3)
{
if (Pl.GetDistAtPoint(Pd3) > Max)
Max = Pl.GetDistAtPoint(Pd3);
else if (Pl.GetDistAtPoint(Pd3) < Min)
Min = Pl.GetDistAtPoint(Pd3);

MyCableIntersectionPoint.Add(Pd3);
}
}

double Dc = Max - Min;

List<BlockReference> LVportVec = new List<BlockReference>();

foreach (BlockReference Br in LVp)


{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
LVportVec.Add(Br);
}
}
}
}

for (int i = 0; i < LVportVec.Count; i++)


{
for (int i2 = i; i2 < LVportVec.Count; i2++)
{
if
(Pl.GetDistAtPoint(Pl.GetClosestPointTo(LVportVec[i].Position, false)) >
Pl.GetDistAtPoint(Pl.GetClosestPointTo(LVportVec[i2].Position, false)))
{
BlockReference Tem = LVportVec[i];
LVportVec[i] = LVportVec[i2];
LVportVec[i2] = Tem;
}
}
}

for (int i = 0; i < LVportVec.Count; i++)


{
MText mText = new MText();
mText.TextHeight = 10;
mText.Contents = i.ToString();
mText.Location = LVportVec[i].Position;
//Trans.Insert(mText, true);

foreach (ObjectId attId in


LVportVec[i].AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
//MessageBox.Show(acAtt.TextString);
}
}
}

List<BlockReference> LFVportVec = new List<BlockReference>();


List<BlockReference> LFVportVecU = new List<BlockReference>();

for (int i = 0; i < LVportVec.Count; i++)


{
foreach (ObjectId attId in
LVportVec[i].AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
if (acAtt.TextString == Page)
{
if (i > 0)
{
LFVportVec.Add(LVportVec[i - 1]);
}

if (LVportVec.Count > (i + 1))


{
LFVportVec.Add(LVportVec[i + 1]);
}
}
}
}
}

//MessageBox.Show("New Cable");

foreach (BlockReference BR in LFVportVec)


{
foreach (ObjectId attId in BR.AttributeCollection)
{
var acAtt = Trans.transaction.GetObject(attId,
OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
// MessageBox.Show(acAtt.TextString);
}
}
}

/* for (int i = 0; i < CableIntersectionPoint.Count; i++)


{
for (int i2 = i; i2 < CableIntersectionPoint.Count; i2++)
{
if(Pl.GetDistAtPoint(CableIntersectionPoint[i]) >
Pl.GetDistAtPoint(CableIntersectionPoint[i2]))
{
Point3d Tem = CableIntersectionPoint[i];
CableIntersectionPoint[i] =
CableIntersectionPoint[i2];
CableIntersectionPoint[i2] = Tem;
}
}
}*/

ArrayList IntvsVport = new ArrayList();

foreach (Point3d point3D in MyCableIntersectionPoint)


{
double Dist = 1500;

string PaGe = "";


BlockReference Tembr;

foreach (BlockReference Br in LFVportVec)


{
if (!LFVportVecU.Contains(Br))
{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
foreach (Point3d P3f in
intersectionPoints)
{
if (new Line(point3D, P3f).Length <
Dist)
{
Dist = new Line(point3D,
P3f).Length;

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
PaGe =
acAtt.TextString;

//
MessageBox.Show(point3D.ToString() + "\n" +PaGe);
}
}
}
}
}
}
}
}
}

foreach (BlockReference Br in LFVportVec)


{
if (!LFVportVecU.Contains(Br))
{
DBObjectCollection dBObjectCollection = new
DBObjectCollection();

Br.Explode(dBObjectCollection);

foreach (DBObject Obj in dBObjectCollection)


{
if (Obj is Polyline)
{
Polyline polyline = Obj as Polyline;

Point3dCollection intersectionPoints = new


Point3dCollection();
polyline.IntersectWith(Pl,
Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);

if (intersectionPoints.Count > 0)
{
foreach (Point3d P3f in
intersectionPoints)
{
if (new Line(point3D, P3f).Length
== Dist)
{
LFVportVecU.Add(Br);

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{

//MessageBox.Show(acAtt.TextString);
}
}

}
}
}
}
}
}
}

IntvsVport.Add(point3D.ToString() + "\n" + PaGe);


}
//Matchlines

foreach (Point3d P in MyCableIntersectionPoint)


{
bool Der = false;

if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Poi.Regla_3(VpPolyOri, Dest, P),
false)) < Dest.GetDistanceAtParameter(1))
{
Der = true;

}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Poi.Regla_3(VpPolyOri, Dest, P),
false)) < Dest.GetDistanceAtParameter(2))
{
Der = true;
}

string BlockName = "MatchLine";

if (Der)
BlockName = "MatchLine2";

//if (Pl.GetClosestPointTo(P, false) == P)


{
Obj_Id = Trans.blockTable[BlockName];

// Insert the block into the current space


if (Obj_Id != ObjectId.Null)
{
using (BlockReference Br = new
BlockReference(Poi.Regla_3(VpPolyOri, Dest, P), Obj_Id))
{
Br.Layer = "Vport2";
Br.ScaleFactors = new Scale3d(0.8, 0.8, 0.8);
if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(1))
{
Br.Rotation = Math.PI / 180 * 0;

//Br.Position = new Point3d(Br.Position.X,


Br.Position.Y + 0.1463, 0);

if (Br.Position.X > 13.1038)


{
Br.Position = new Point3d(13.1038,
Br.Position.Y, 0);
}
else if (Br.Position.X < 7.6278)
{
Br.Position = new Point3d(7.6278,
Br.Position.Y, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());

}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(2))
{
Br.Rotation = Math.PI / 180 * 270;
//Br.Position = new Point3d(Br.Position.X +
0.1463, Br.Position.Y, 0);

if (Br.Position.Y < 6.1279)


{
Br.Position = new
Point3d(Br.Position.X, 6.1279, 0);
}
else if (Br.Position.Y > 9.6427)
{
Br.Position = new
Point3d(Br.Position.X, 9.6427, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
else if
(Dest.GetDistAtPoint(Dest.GetClosestPointTo(Br.Position, false)) <
Dest.GetDistanceAtParameter(3))
{
Br.Rotation = Math.PI / 180 * 0;

//Br.Position = new Point3d(Br.Position.X,


Br.Position.Y - 0.1463, 0);

if (Br.Position.X > 13.1038)


{
Br.Position = new Point3d(13.1038,
Br.Position.Y, 0);
}
else if (Br.Position.X < 7.6278)
{
Br.Position = new Point3d(7.6278,
Br.Position.Y, 0);
}

//MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
else
{
Br.Rotation = Math.PI / 180 * 270;

//Br.Position = new Point3d(Br.Position.X -


0.1463, Br.Position.Y, 0);

if (Br.Position.Y < 6.1279)


{
Br.Position = new
Point3d(Br.Position.X, 6.1279, 0);
}
else if (Br.Position.Y > 9.6427)
{
Br.Position = new
Point3d(Br.Position.X, 9.6427, 0);
}
// MessageBox.Show((Br.Rotation / Math.PI *
180).ToString());
}
string Pag = "";

foreach (string S in IntvsVport)


{
if (S.Contains(P.ToString()))
{
Pag = S.Split('\n')[1];
}
}

if (!ml.Contains(Pag))
{

BlockTable blockTable =
Trans.transaction.GetObject(Trans.database.BlockTableId, OpenMode.ForWrite) as
BlockTable;
BlockTableRecord blkTbRecPaper =
Trans.transaction.GetObject(blockTable[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
blkTbRecPaper.AppendEntity(Br);

BlockTableRecord Btr =
(BlockTableRecord)blockTable[BlockName].GetObject(OpenMode.ForWrite);

foreach (ObjectId id in Btr)


{
DBObject obj =
id.GetObject(OpenMode.ForWrite);
AttributeDefinition attDef = obj as
AttributeDefinition;
if (attDef != null && !attDef.Constant)
{
using (AttributeReference attRef =
new AttributeReference())
{

attRef.SetAttributeFromBlock(attDef, Br.BlockTransform);

attRef.Visible = true;

Br.AttributeCollection.AppendAttribute(attRef);

Trans.transaction.AddNewlyCreatedDBObject(attRef, true);

if (attRef.Tag ==
"DESCRIPTION")
{
attRef.TextString = "SEE
PAGE# ";
}
else if (attRef.Tag == "PAGE"
|| attRef.Tag == "REF#")
{
attRef.TextString = Pag;
}
else
{
attRef.TextString = "";
}
}
}
}

DynamicBlockReferencePropertyCollection
pcFST = Br.DynamicBlockReferencePropertyCollection;

foreach (DynamicBlockReferenceProperty dP
in pcFST)
{
if (dP.PropertyName == "Flip state1")
{
/* Trans.editor.WriteMessage(
$"\nName: {dP.PropertyName} " +
$"Type code: {dP.PropertyTypeCode}
" +
$"Unit type: {dP.UnitsType} " +
$"Allowed values: [{string.Join(",
", dP.GetAllowedValues())}]");*/

//dP.Value = "1";
}
}

bool Del = false;

foreach (ObjectId attId in


Br.AttributeCollection)
{
var acAtt =
Trans.transaction.GetObject(attId, OpenMode.ForWrite) as AttributeReference;
if (acAtt.Tag == "PAGE")
{
if (acAtt.TextString == "")
{
Del = true;
}
}
}

if (Del)
{
Br.Erase();
}
ml.Add(Pag);
}
}
}
}
}
}
////set vecinos

// Get the current document and database, and start a transaction


Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

using (Transaction acTrans =


acCurDb.TransactionManager.StartTransaction())
{
// Reference the Layout Manager
LayoutManager acLayoutMgr = LayoutManager.Current;

// Get the current layout and output its name in the Command Line
window
Layout acLayout =
acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout),
OpenMode.ForRead) as Layout;

DBDictionary acPlSet =
acTrans.GetObject(acCurDb.PlotSettingsDictionaryId,
OpenMode.ForRead) as
DBDictionary;

// Check to see if the page setup exists


if (acPlSet.Contains("11-17") == true)
{
PlotSettings plSet = acPlSet.GetAt("11-
17").GetObject(OpenMode.ForRead) as PlotSettings;

// Update the layout


acLayout.UpgradeOpen();
acLayout.CopyFrom(plSet);

// Save the new objects to the database


acTrans.Commit();
}
else
{
// Ignore the changes made
acTrans.Abort();
}
}

//Update the display*

acDoc.Editor.Regen();
//Trans.editor.SwitchToModelSpace();

SpaceAlign2(PLC);
LayoutManager.Current.CurrentLayout = "Model";
}

class CStreet
{
public void AddCl(CTransaction Trans)
{
WebClient Client = new WebClient();

GeoLocationData geo =
Trans.transaction.GetObject(Trans.database.GeoDataObject, OpenMode.ForWrite) as
GeoLocationData;

PromptPointOptions ppo = new PromptPointOptions("First Point:");


PromptPointResult psr = Trans.editor.GetPoint(ppo);
if (psr.Status == PromptStatus.OK)
{
PromptPointOptions ppo1 = new PromptPointOptions("Second Point:");
ppo1.BasePoint = psr.Value;
ppo1.UseBasePoint = true;
PromptPointResult psr1 = Trans.editor.GetPoint(ppo1);
if (psr1.Status == PromptStatus.OK)
{

List<double> X = new List<double>();


List<double> Y = new List<double>();
X.Add(geo.TransformToLonLatAlt(psr.Value).X);
X.Add(geo.TransformToLonLatAlt(psr1.Value).X);

//Application.ShowAlertDialog(geo.TransformToLonLatAlt(psr.Value).ToString());

//Application.ShowAlertDialog(geo.TransformToLonLatAlt(psr1.Value).ToString());
Y.Add(geo.TransformToLonLatAlt(psr.Value).Y);
Y.Add(geo.TransformToLonLatAlt(psr1.Value).Y);
string LongMin = X.Min().ToString("0.000");
string LatMin = Y.Min().ToString("0.000");
string LongMax = X.Max().ToString("0.000");
string LatMax = Y.Max().ToString("0.000");
if (File.Exists(@"C:\GenXCTool\Temp Arc\CL.txt"))
{
File.Delete(@"C:\GenXCTool\Temp Arc\CL.txt");
}
File.WriteAllText(@"C:\GenXCTool\Temp Arc\CL.txt",
Client.DownloadString("http://api.openstreetmap.org/api/0.6/map?bbox=" + LongMin +
"," + LatMin + "," + LongMax + "," + LatMax));
XmlDocument XDoc = new XmlDocument();
XDoc.Load(@"C:\GenXCTool\Temp Arc\CL.txt");
XmlNodeList xnNode = XDoc.GetElementsByTagName("node");
XmlNodeList xnWay = XDoc.GetElementsByTagName("way");
List<string> way = new List<string>();
string[] highway = new string[] { "motorway", "trunk",
"primary", "secondary", "tertiary", "unclassified", "residential", "road" };
bool flag = false;
bool flag0 = false;
foreach (XmlNode xWay in xnWay)
{

List<string> IdNode = new List<string>();

string Name = "";


string EOP = "";
string pre = "";
string Base = "";
string sux = "";
string IDWAY = "";
foreach (XmlAttribute xATT in xWay.Attributes)
{
if (xATT.Value == "id")
{
IDWAY = xATT.Value;

}
}
flag = false;
flag0 = false;
foreach (XmlNode xWayNode in xWay)
{
if (xWayNode.Name == "nd")
{

IdNode.Add(xWayNode.Attributes[0].Value);

}
if (xWayNode.Name == "tag")
{

if (xWayNode.Attributes[0].Value == "highway" &&


highway.Contains(xWayNode.Attributes[1].Value))
{
flag = true;
if (xWayNode.Attributes[1].Value ==
"residential")
{
EOP = "20.0";
}
}
if (xWayNode.Attributes[0].Value ==
"tiger:name_direction_prefix")
{
pre = xWayNode.Attributes[1].Value;

}
if (xWayNode.Attributes[0].Value ==
"tiger:name_base")
{
Base = xWayNode.Attributes[1].Value;

}
if (xWayNode.Attributes[0].Value ==
"tiger:name_type")
{
sux = xWayNode.Attributes[1].Value;

}
if (xWayNode ==
xWay.ChildNodes[xWay.ChildNodes.Count - 1])
{
flag0 = true;
}
}

if (flag && flag0)


{
Name = (pre + " " + Base + " " + sux).ToUpper();

Polyline pl = new Polyline();


foreach (string item in IdNode)
{
foreach (XmlNode xNo in xnNode)
{
bool flag2 = false;
double lon = 0.0;
double lat = 0.0;
foreach (XmlAttribute xATT in
xNo.Attributes)
{

if (xATT.Name == "id" && xATT.Value ==


item)
{
flag2 = true;

}
if (flag2)
{

if (xATT.Name == "lon")
{
lon =
Convert.ToDouble(xATT.Value);

}
if (xATT.Name == "lat")
{
lat =
Convert.ToDouble(xATT.Value);
}

}
if (flag2)
{

//Application.ShowAlertDialog(lat.ToString()+","+lon.ToString());
pl.AddVertexAt(pl.NumberOfVertices, new
Point2d(geo.TransformFromLonLatAlt(new Point3d(lon, lat, 0)).X,
geo.TransformFromLonLatAlt(new Point3d(lon, lat, 0)).Y), 0, 0, 0);
}

Trans.Insert(pl, true);
Trans.Hyper(pl, Name, EOP, "");

//dgvCenterLine.Rows.Add(pl.Handle.Value.ToString(),Name, pl.Hyperlinks[0].Name,
pl.Hyperlinks[0].SubLocation);
pl.Layer = "Streets";
}

}
}
}
}

You might also like