private static System.Data.DataSet ReadDataReallyFast(string sWBName)
        {
            System.Data.DataSet ds = new System.Data.DataSet();

            if (System.IO.File.Exists(sWBName))
            {
                try
                {
                    using (var stream = System.IO.File.OpenRead(sWBName))
                    {
                        using (var reader = ExcelReaderFactory.CreateReader(stream))
                        {
                            ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                            {
                                ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                                {
                                    UseHeaderRow = true
                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
                }
            }
            else
            {
                BPSUtilities.WriteLog("Workbook '{0}' not found", sWBName);
            }

            return(ds);
        }
예제 #2
0
        private void SetPWVarsCE_NewDesignFileEvent(Bentley.MstnPlatformNET.AddIn sender, NewDesignFileEventArgs eventArgs)
        {
            if (eventArgs.WhenCode == NewDesignFileEventArgs.When.AfterDesignFileOpen)
            {
                string sFileName = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnFile().GetFileName();

                BPSUtilities.WriteLog($"Filename is '{sFileName}'");

                int iProjectNo = 0, iDocumentNo = 0;

                PWWrapper.aaApi_Initialize(0);

                if (mcmMain_GetDocumentIdByFilePath(sFileName, 1,
                                                    ref iProjectNo, ref iDocumentNo))
                {
                    BPSUtilities.WriteLog($"IDs: {iProjectNo}, {iDocumentNo}");

                    if (iProjectNo > 0 && iDocumentNo > 0)
                    {
                        UpdatePWEnvVars(iProjectNo, iDocumentNo);
                    }
                    else
                    {
                        BPSUtilities.WriteLog("No integrated session of ProjectWise.");
                    }
                }
                else
                {
                    BPSUtilities.WriteLog("No integrated session of ProjectWise.");
                }

                ListReferences(true);
            }
        }
        /// <summary>
        /// Calls the my Azure API to shorten the long URL into an adddress like shl.pw/2v and returns QR Code image of the shortened URL
        /// </summary>
        /// <param name="sLongURL">URL to shorten and generate image of</param>
        /// <param name="iSize">Size of image to generate with ZXing</param>
        /// <param name="iCropBorder">Sometimes too much white space around QR Code and needs cropping</param>
        /// <returns>The (optionally cropped) QRCode Image of the shortened URL from ZXing</returns>
        public static QREncoder GetQREncoderObject(string sLongURL)
        {
            string url = "https://pwqrazurefunctionapp.azurewebsites.net/api/ShortenURLPost?code=bxwoszCCCjEGB2KTqiw/tcNCoNCKMdu9jdcbB2xiXcUoxPhMHWRTDA==";

            try
            {
                // build WSG file link
                var linkToShorten = new ShortenThisURLWithAzure
                {
                    Input = sLongURL
                };

                HttpRequestMessage request       = new HttpRequestMessage(HttpMethod.Post, url);
                HttpClient         connectClient = new HttpClient();
                connectClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var body = JSONHelper.SerializeJSon <ShortenThisURLWithAzure>(linkToShorten);
                request.Content = new StringContent(body, Encoding.UTF8, "application/json");

                var    response        = connectClient.SendAsync(request).Result;
                string responseContent = response.Content.ReadAsStringAsync().Result;

                BPSUtilities.WriteLog(responseContent);

                // this is dumb
                ShortenedURLResponseFromAzure shortUrl = JSONHelper.DeserializeJSon <ShortenedURLResponseFromAzure>(responseContent.Replace("[", "").Replace("]", ""));

                if (shortUrl != null)
                {
                    if (!string.IsNullOrEmpty(shortUrl.ShortUrl))
                    {
                        BPSUtilities.WriteLog($"'{shortUrl.LongUrl}' shortened to '{shortUrl.ShortUrl}'");

                        QREncoder enc = new QREncoder();

                        enc.ErrorCorrection = ErrorCorrection.H;

                        // this leads to a 33 x 33 qrcode
                        enc.ModuleSize = 1;
                        enc.QuietZone  = 4;

                        enc.Encode(shortUrl.ShortUrl);

                        return(enc);
                    }
                }
                else
                {
                    BPSUtilities.WriteLog("Short URL not generated.");
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog("Error: " + ex.Message);
                BPSUtilities.WriteLog(ex.StackTrace);
            }

            return(null);
        }
예제 #4
0
        // private static PolyhedaListForm m_polyhedraListForm = null;

        protected override void ExitTool()
        {
            try
            {
                BPSUtilities.WriteLog("PlaceQRCode ExitTool");

                base.ExitTool();
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"PlaceQRCode ExitTool {ex.Message}\n{ex.StackTrace}");
            }
        }
 public static void InstallNewInstance(string sPolyhedronName)
 {
     try
     {
         BPSUtilities.WriteLog("InstallNewInstance");
         CreatePolyhedronX64 createPolyhedronTool = new CreatePolyhedronX64(0, 0, sPolyhedronName);
         createPolyhedronTool.InstallTool();
     }
     catch (Exception ex)
     {
         BPSUtilities.WriteLog($"InstallNewInstance {ex.Message}\n{ex.StackTrace}");
     }
 }
예제 #6
0
 public static void InstallNewInstance(string sUnparsed)
 {
     try
     {
         BPSUtilities.WriteLog("PlaceQRCode InstallNewInstance");
         PlaceQRCode qrCodeTool = new PlaceQRCode(0, 0, sUnparsed);
         qrCodeTool.InstallTool();
     }
     catch (Exception ex)
     {
         BPSUtilities.WriteLog($"PlaceQRCode InstallNewInstance {ex.Message}\n{ex.StackTrace}");
     }
 }
 public void StartDynamics()
 {
     try
     {
         if (!this.DynamicsStarted)
         {
             base.BeginDynamics();
         }
     }
     catch (Exception ex)
     {
         BPSUtilities.WriteLog($"StartDynamics {ex.Message}\n{ex.StackTrace}");
     }
 }
 protected override void OnRestartTool()
 {
     try
     {
         BPSUtilities.WriteLog("OnRestartTool");
         // throw new NotImplementedException();
         InstallNewInstance(PolyhedronName);
         m_haveFirstPoint = false;
         base.BeginDynamics();
     }
     catch (Exception ex)
     {
         BPSUtilities.WriteLog($"OnRestartTool {ex.Message}\n{ex.StackTrace}");
     }
 }
예제 #9
0
        private void ListReferences(bool bIntegrated)
        {
            BPSUtilities.WriteLog($"Active Model Name: {Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel().GetModelInfo().Name}");

            Bentley.DgnPlatformNET.DgnAttachmentCollection col = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnModel().GetDgnAttachments();

            int iAttachmentNo = 1;

            try
            {
                foreach (Bentley.DgnPlatformNET.DgnAttachment dgnAttachment in col.GetEnumerator().ConvertToList())
                {
                    BPSUtilities.WriteLog($"Attachment: {iAttachmentNo++}");

                    try
                    {
                        BPSUtilities.WriteLog($"Is Missing: {(dgnAttachment.IsMissingFile ? "True" : "False")}");
                        BPSUtilities.WriteLog($"Logical Name: {dgnAttachment.LogicalName}");
                        BPSUtilities.WriteLog($"Attachment Filename: {dgnAttachment.AttachFileName}");
                        BPSUtilities.WriteLog($"Attachment Model Name: {dgnAttachment.AttachModelName}");
                        BPSUtilities.WriteLog($"Attachment Attach Full File Spec: {dgnAttachment.GetAttachFullFileSpec(false)}");

                        Bentley.DgnPlatformNET.DgnDocumentMoniker dgnMoniker = dgnAttachment.GetAttachMoniker();

                        if (dgnMoniker != null)
                        {
                            BPSUtilities.WriteLog($"Parent Search Path: {dgnMoniker.ParentSearchPath}");
                            BPSUtilities.WriteLog($"Portable Name: {dgnMoniker.PortableName}");
                            BPSUtilities.WriteLog($"Provider Id: {dgnMoniker.ProviderId}");
                            BPSUtilities.WriteLog($"Saved File Name: {dgnMoniker.SavedFileName}");
                            BPSUtilities.WriteLog($"Short Display Name: {dgnMoniker.ShortDisplayName}");
                        }
                        else
                        {
                            BPSUtilities.WriteLog("No Document Moniker found.");
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"ListReferences Error: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"ListReferences Error: {ex.Message}");
            }
        }
        protected override void OnPostInstall()
        {
            try
            {
                BPSUtilities.WriteLog("OnPostInstall");

                NotificationManager.OutputPrompt("Enter data point to place polyhedron. Reset to exit.");
                // AccuSnap.SnapEnabled = true;
                // AccuSnap.LocateEnabled = true;
                base.OnPostInstall();

                m_haveFirstPoint = false;
                base.BeginDynamics();

                BPSUtilities.WriteLog($"OnPostInstall Dynamics {(this.DynamicsStarted ? "is" : "is not")} started.");
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"OnPostInstall {ex.Message}\n{ex.StackTrace}");
            }
        }
        // private static PolyhedaListForm m_polyhedraListForm = null;

        protected override void ExitTool()
        {
            try
            {
                BPSUtilities.WriteLog("ExitTool");
                PolyhedraCE.StaticElement.Dispose();
                PolyhedraCE.StaticElement = null;

                foreach (Bentley.DgnPlatformNET.Elements.Element elm in PolyhedraCE.ListOfPolyhedra.Values)
                {
                    elm.Dispose();
                }

                PolyhedraCE.ListOfPolyhedra.Clear();

                base.ExitTool();
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"ExitTool {ex.Message}\n{ex.StackTrace}");
            }
        }
예제 #12
0
        private bool mcmMain_GetDocumentIdByFilePath(string sFileName, int iValidateWithChkl,
                                                     ref int iProjectNo, ref int iDocumentNo)
        {
            bool bRetVal = false;

            Guid[] docGuids  = new Guid[1];
            int    iNumGuids = 0;

            try
            {
                IntPtr pGuid = IntPtr.Zero;

                int iRetVal = PWWrapper.aaApi_GetGuidsFromFileName(ref pGuid, ref iNumGuids, sFileName, iValidateWithChkl);

                if (iNumGuids == 1)
                {
                    Guid docGuid = (Guid)System.Runtime.InteropServices.Marshal.PtrToStructure(pGuid, typeof(Guid));

                    if (1 == PWWrapper.aaApi_GUIDSelectDocument(ref docGuid))
                    {
                        bRetVal = true;

                        iProjectNo =
                            PWWrapper.aaApi_GetDocumentNumericProperty(PWWrapper.DocumentProperty.ProjectID, 0);
                        iDocumentNo =
                            PWWrapper.aaApi_GetDocumentNumericProperty(PWWrapper.DocumentProperty.ID, 0);
                    }
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"Error: {ex.Message}\n{ex.StackTrace}");
            }

            return(bRetVal);
        }
        public static bool DataSetToXLSX(DataSet ds, string sWBName)
        {
            bool bRetVal = false;

            try
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

                var wb = new XLWorkbook();

                try
                {
                    UriParser.Register(new PWUriParser(GenericUriParserOptions.AllowEmptyAuthority |
                                                       GenericUriParserOptions.DontCompressPath | GenericUriParserOptions.DontConvertPathBackslashes |
                                                       GenericUriParserOptions.DontUnescapePathDotsAndSlashes | GenericUriParserOptions.GenericAuthority |
                                                       GenericUriParserOptions.NoFragment), "pw", 5800);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Error: {0}\n{1}", ex.Message, ex.StackTrace));
                }

                foreach (DataTable dt in ds.Tables)
                {
                    if (dt.TableName.Length > 30)
                    {
                        dt.TableName = dt.TableName.Substring(0, 30);
                    }

                    var ws = wb.Worksheets.Add(dt.TableName);

                    // ws.Cell("A1").Value = dt.TableName;

                    int iColumnIndex = 1;
                    int iRowIndex    = 1;

                    SortedList <string, int> slColumnsToColumnIndices = new SortedList <string, int>(StringComparer.CurrentCultureIgnoreCase);

                    foreach (DataColumn dc in dt.Columns)
                    {
                        if (!slColumnsToColumnIndices.ContainsKey(dc.ColumnName))
                        {
                            slColumnsToColumnIndices.Add(dc.ColumnName, iColumnIndex);
                        }
                        ws.Cell(iRowIndex, iColumnIndex++).Value = dc.ColumnName;
                    }

                    iColumnIndex = 1;
                    iRowIndex    = 2;

                    foreach (DataRow dr in dt.Rows)
                    {
                        foreach (DataColumn dc in dt.Columns)
                        {
                            string sColumnValue = dr[dc.ColumnName].ToString();

                            if (sColumnValue.StartsWith("pw://") || sColumnValue.StartsWith("pw:\\\\") ||
                                sColumnValue.StartsWith("http://") || sColumnValue.StartsWith("http:\\\\") ||
                                sColumnValue.StartsWith("https://") || sColumnValue.StartsWith("https:\\\\") ||
                                sColumnValue.StartsWith("file://") || sColumnValue.StartsWith("file:\\\\") ||
                                sColumnValue.StartsWith("ftp://") || sColumnValue.StartsWith("ftp:\\\\"))
                            {
                                if (sColumnValue.Contains("|"))
                                {
                                    string[] sParts = sColumnValue.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                                    if (sParts.Length > 0)
                                    {
                                        Uri hyperlink = new Uri(Uri.EscapeUriString(sParts[0]));
                                        // Uri hyperlink = new Uri("http://www.bentley.com");

                                        if (sParts.Length == 2)
                                        {
                                            ws.Cell(iRowIndex, iColumnIndex).Value       = sParts[1];
                                            ws.Cell(iRowIndex, iColumnIndex++).Hyperlink = new XLHyperlink(hyperlink);
                                        }
                                        else
                                        {
                                            ws.Cell(iRowIndex, iColumnIndex).Value       = sParts[0];
                                            ws.Cell(iRowIndex, iColumnIndex++).Hyperlink = new XLHyperlink(hyperlink);
                                        }
                                    }
                                }
                                else
                                {
                                    Uri hyperlink = new Uri(Uri.EscapeUriString(sColumnValue));
                                    // Uri hyperlink = new Uri("http://www.bentley.com");

                                    ws.Cell(iRowIndex, iColumnIndex).Value       = sColumnValue;
                                    ws.Cell(iRowIndex, iColumnIndex++).Hyperlink = new XLHyperlink(hyperlink);
                                }
                            }
                            else
                            {
                                ws.Cell(iRowIndex, iColumnIndex++).Value = dr[dc.ColumnName];
                            }
                        }

                        iColumnIndex = 1;
                        iRowIndex++;
                    }

                    var rngTable = ws.Range(1, 1, iRowIndex - 1, dt.Columns.Count);

                    // headers
                    var rngHeaders = rngTable.Range(1, 1, 1, dt.Columns.Count); // The address is relative to rngTable (NOT the worksheet)
                    rngHeaders.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    rngHeaders.Style.Font.Bold            = true;
                    rngHeaders.Style.Fill.BackgroundColor = XLColor.Aqua;

                    rngTable.Style.Border.BottomBorder = XLBorderStyleValues.Thin;

                    // title
                    //rngTable.Cell(1, 1).Style.Font.Bold = true;
                    //rngTable.Cell(1, 1).Style.Fill.BackgroundColor = XLColor.CornflowerBlue;
                    //rngTable.Cell(1, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                    //rngTable.Row(1).Merge();

                    //Add a thick outside border
                    rngTable.Style.Border.OutsideBorder = XLBorderStyleValues.Thick;

                    // You can also specify the border for each side with:
                    // rngTable.FirstColumn().Style.Border.LeftBorder = XLBorderStyleValues.Thick;
                    // rngTable.LastColumn().Style.Border.RightBorder = XLBorderStyleValues.Thick;
                    // rngTable.FirstRow().Style.Border.TopBorder = XLBorderStyleValues.Thick;
                    // rngTable.LastRow().Style.Border.BottomBorder = XLBorderStyleValues.Thick;

                    ws.Columns(1, dt.Columns.Count).AdjustToContents();
                } // for each table

                // string sWBName = Guid.NewGuid().ToString() + ".xlsx";

                wb.SaveAs(sWBName);

                bRetVal = true;

                // BPSUtilities.WriteLog("Wrote " + sWBName);
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
            }

            return(bRetVal);
        }
        protected override void OnDynamicFrame(Bentley.DgnPlatformNET.DgnButtonEvent ev)
        {
            try
            {
                if (PolyhedraCE.StaticElement == null)
                {
                    if (!string.IsNullOrEmpty(PolyhedronName))
                    {
                        if (PolyhedraCE.ListOfPolyhedra.ContainsKey(PolyhedronName))
                        {
                            BPSUtilities.WriteLog($"Found cell for '{PolyhedronName}'");
                            PolyhedraCE.StaticElement = PolyhedraCE.ListOfPolyhedra[PolyhedronName];
                        }
                        else
                        {
                            m_haveFirstPoint = false;
                            BPSUtilities.WriteLog($"Cell for '{PolyhedronName}' not found.");
                            this.EndDynamics();
                        }
                    }
                    else
                    {
                        BPSUtilities.WriteLog("Polyhedron Name not set.");
                        m_haveFirstPoint = false;
                        this.EndDynamics();
                    }
                }

                try
                {
                    Bentley.DgnPlatformNET.Elements.CellHeaderElement cellElem = (Bentley.DgnPlatformNET.Elements.CellHeaderElement)(PolyhedraCE.StaticElement);
                    if (cellElem.CellName != PolyhedronName)
                    {
                        BPSUtilities.WriteLog($"Current cell is {cellElem.CellName}");

                        if (!string.IsNullOrEmpty(PolyhedronName))
                        {
                            if (PolyhedraCE.ListOfPolyhedra.ContainsKey(PolyhedronName))
                            {
                                BPSUtilities.WriteLog($"Found cell for '{PolyhedronName}'");

                                if (PolyhedraCE.StaticElement != null)
                                {
                                    PolyhedraCE.StaticElement.Dispose();
                                }

                                PolyhedraCE.StaticElement = PolyhedraCE.ListOfPolyhedra[PolyhedronName];
                            }
                            else
                            {
                                m_haveFirstPoint = false;
                                BPSUtilities.WriteLog($"Cell for '{PolyhedronName}' not found.");
                                this.EndDynamics();
                            }
                        }
                        else
                        {
                            BPSUtilities.WriteLog("Polyhedron Name not set.");
                            m_haveFirstPoint = false;
                            this.EndDynamics();
                        }
                    }
                }
                catch (Exception ex)
                {
                    BPSUtilities.WriteLog($"Error casting cell {ex.Message}");
                }

                if (PolyhedraCE.StaticElement != null)
                {
                    RedrawElems redrawElems = new RedrawElems();
                    redrawElems.SetDynamicsViewsFromActiveViewSet(Bentley.MstnPlatformNET.Session.GetActiveViewport());
                    redrawElems.DrawMode    = DgnDrawMode.TempDraw;
                    redrawElems.DrawPurpose = DrawPurpose.Dynamics;

                    try
                    {
                        DMatrix3d invertedViewportRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                        if (ev.Viewport.GetRotation().TryInvert(out invertedViewportRotation))
                        {
                            DMatrix3d cellRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                            List <Bentley.DgnPlatformNET.Elements.Element> listChildElements = new List <Bentley.DgnPlatformNET.Elements.Element>();

                            foreach (Bentley.DgnPlatformNET.Elements.Element child in PolyhedraCE.StaticElement.GetChildren())
                            {
                                listChildElements.Add(child);
                            }

                            Bentley.DgnPlatformNET.Elements.CellHeaderElement copiedElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), PolyhedronName,
                                                                                                                    new DPoint3d(0, 0, 0), cellRotation, listChildElements);

                            if (copiedElement != null)
                            {
                                if (copiedElement.IsValid)
                                {
                                    if (!m_haveFirstPoint)
                                    {
                                        DPoint3d translation = ev.Point;

                                        DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                        DPoint3d[] blkPts = new DPoint3d[4];

                                        DPoint3d low = DPoint3d.Zero, high = DPoint3d.Zero;

                                        ev.Viewport.GetViewCorners(out low, out high);

                                        // rotate points to orthogonal
                                        blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(low)));

                                        blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(high)));

                                        blkPts[2].Z = blkPts[0].Z;

                                        DPoint3d ext = DPoint3d.Subtract(blkPts[2], blkPts[0]);

                                        double dScale = Math.Max(0.15 * Math.Abs(ext.Magnitude / uorPerMaster()), 1.0);

                                        DPoint3d dPtScale = ev.Viewport.GetScale();

                                        // dScale = dPtScale.Magnitude;

                                        // BPSUtilities.WriteLog($"Scale: {dScale}, View: {ev.ViewNumber}");

                                        invertedViewportRotation.ScaleInPlace(dScale);

                                        // works
                                        DTransform3d translateAndRotateToUpInViewWithViewBasedScale =
                                            DTransform3d.FromMatrixAndTranslation(invertedViewportRotation, translation);

                                        TransformInfo transformInfo = new TransformInfo(translateAndRotateToUpInViewWithViewBasedScale);

                                        // works
                                        copiedElement.ApplyTransform(transformInfo);
                                    }
                                    else
                                    {
                                        // now to work on rotation and scale
                                        DPoint3d translation = m_firstPoint;

                                        DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                        DPoint3d[] blkPts = new DPoint3d[4];

                                        // rotate points to orthogonal
                                        blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                                        blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                                        blkPts[2].Z = blkPts[0].Z;

                                        DPoint3d ext = DPoint3d.Subtract(blkPts[2], blkPts[0]);

                                        DVector3d angleVec = new DVector3d(ext);

                                        double dScale = Math.Max(0.1, Math.Abs(ext.Magnitude / uorPerMaster()));

                                        invertedViewportRotation.ScaleInPlace(dScale);

                                        DMatrix3d scaleRotateInViewRotateAroundPoint = DMatrix3d.Multiply(invertedViewportRotation, DMatrix3d.Rotation(2, angleVec.AngleXY));

                                        DTransform3d translateAndRotatetoUpInViewAndScale =
                                            DTransform3d.FromMatrixAndTranslation(scaleRotateInViewRotateAroundPoint, translation);

                                        TransformInfo transformInfo2 = new TransformInfo(translateAndRotatetoUpInViewAndScale);

                                        copiedElement.ApplyTransform(transformInfo2);
                                    }

                                    redrawElems.DoRedraw(copiedElement);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                    }
                    //    if (!m_haveFirstPoint)
                    //{
                    //    BPSUtilities.WriteLog("Don't have first point.");
                    //    // move it around on cursor
                    //    redrawElems.DoRedraw(GetTransformedElement(m_element, ev));
                    //}
                    //else
                    //{
                    //    BPSUtilities.WriteLog("Do have first point.");
                    //    redrawElems.DoRedraw(GetTransformedElement(m_element, ev));
                    //}
                }
                else
                {
                    BPSUtilities.WriteLog("Element is null");
                    this.EndDynamics();
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"OnDynamicFrame: {ex.Message}\n{ex.StackTrace}");
            }
        }
예제 #15
0
        public static void UpdatePWEnvVars(int lProjectNo, int lDocumentNo)
        {
            if (1 == PWWrapper.aaApi_SelectDocument(lProjectNo, lDocumentNo))
            {
                Bentley.DgnPlatformNET.ConfigurationVariableLevel level = Bentley.DgnPlatformNET.ConfigurationVariableLevel.Application;

                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_VAULTID", $"{lProjectNo}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCID", $"{lDocumentNo}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_ORIGINALNO",
                                                                           $"{PWWrapper.aaApi_GetDocumentNumericProperty(PWWrapper.DocumentProperty.OriginalNumber, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCNAME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.Name, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_FILENAME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.FileName, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCDESC",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.Desc, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCVERSION",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.Version, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCCREATETIME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.CreateTime, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCUPDATETIME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.UpdateTime, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCFILEUPDATETIME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.FileUpdateTime, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCLASTRTLOCKTIME",
                                                                           $"{PWWrapper.aaApi_GetDocumentStringProperty(PWWrapper.DocumentProperty.LastRtLockTime, 0)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCWORKFLOW",
                                                                           $"{PWWrapper.GetWorkflowName(PWWrapper.aaApi_GetDocumentNumericProperty(PWWrapper.DocumentProperty.WorkFlowID, 0))}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCWORKFLOWSTATE",
                                                                           $"{PWWrapper.GetStateName(PWWrapper.aaApi_GetDocumentNumericProperty(PWWrapper.DocumentProperty.StateID, 0))}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_VAULTPATHNAME",
                                                                           $"{PWWrapper.GetProjectNamePath2(lProjectNo)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_FULLFILEPATHNAME",
                                                                           $"{PWWrapper.GetDocumentNamePath(lProjectNo, lDocumentNo)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCGUID",
                                                                           $"{PWWrapper.GetGuidStringFromIds(lProjectNo, lDocumentNo)}", level);
                Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_DOCLINK",
                                                                           $"{PWWrapper.GetDocumentURL(lProjectNo, lDocumentNo)}", level);

                if (1 == PWWrapper.aaApi_SelectProject(lProjectNo))
                {
                    Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_VAULTNAME",
                                                                               $"{PWWrapper.aaApi_GetProjectStringProperty(PWWrapper.ProjectProperty.Name, 0)}", level);
                    Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable("PWVAR_VAULTDESC",
                                                                               $"{PWWrapper.aaApi_GetProjectStringProperty(PWWrapper.ProjectProperty.Desc, 0)}", level);
                }

                System.Collections.Generic.SortedList <string, string> slProps = PWWrapper.GetProjectPropertyValuesInList(lProjectNo);

                foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in slProps)
                {
                    Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable($"PWVAR_PROJPROP_{kvp.Key.ToUpper().Replace(" ", "_")}",
                                                                               kvp.Value, level);
                }

                System.Collections.Generic.SortedList <string, string> slAttrs = PWWrapper.GetAllAttributeColumnValuesInList(lProjectNo, lDocumentNo);

                foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in slAttrs)
                {
                    Bentley.DgnPlatformNET.ConfigurationManager.DefineVariable($"PWVAR_ATTR_{kvp.Key.ToUpper().Replace(" ", "_")}",
                                                                               kvp.Value, level);
                }
            } // document selected
            else
            {
                BPSUtilities.WriteLog("Could not select document.");
            }
        }
        public CreatePolyhedronX64(int toolId, int prompt, string sPolyhedronName) : base(toolId, prompt)
        {
            try
            {
                // m_points = new List<DPoint3d>();

                PolyhedronName = sPolyhedronName;

                // string sXMLFileName = string.Empty;

                BPSUtilities.WriteLog($"CreatePolyhedronX64 Initialized '{PolyhedronName}'");

                string sOutputXML2 = Path.Combine(Path.GetTempPath(), $"{BPSUtilities.GetARandomString(8, BPSUtilities.LOWER_CASE)}.xml");

                if (PolyhedraCE.ListOfPolyhedra.Count == 0)
                {
                    string sOutputXML = Path.Combine(Path.GetTempPath(), $"{BPSUtilities.GetARandomString(8, BPSUtilities.LOWER_CASE)}.xml");

                    try
                    {
                        System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();

                        foreach (string sResName in thisExe.GetManifestResourceNames())
                        {
                            if (sResName.ToLower().EndsWith(".polyhedra.xml"))
                            {
                                using (var resourceStream = thisExe.GetManifestResourceStream(sResName))
                                {
                                    resourceStream.CopyTo(new System.IO.FileStream(sOutputXML, FileMode.Create));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                    }

                    File.Copy(sOutputXML, sOutputXML2);

                    try
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(sOutputXML2);

                        XmlNode root = xmlDoc.DocumentElement;

                        // need form to list available polyhedra

                        XmlNodeList nodeList = root.SelectNodes(".//polyhedron");

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

                        foreach (XmlNode node in nodeList)
                        {
                            string sPolyName = node.Attributes["name"].Value;
                            listPolyhedrons.Add(sPolyName);
                        }

                        foreach (string sPolyName in listPolyhedrons)
                        {
                            try
                            {
                                BPSUtilities.WriteLog($"Processing '{sPolyName}'...");

                                Bentley.DgnPlatformNET.Elements.Element elm = SetPolyhedron(sPolyName, sOutputXML2);

                                if (elm != null)
                                {
                                    PolyhedraCE.ListOfPolyhedra.AddWithCheck(sPolyName, elm);
                                    // elm.AddToModel();
                                    BPSUtilities.WriteLog($"Added '{sPolyName}'");
                                }
                                else
                                {
                                    BPSUtilities.WriteLog($"Error creating '{sPolyName}'");
                                }
                            }
                            catch (Exception ex)
                            {
                                BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                    }
                }
                else
                {
                }

                BPSUtilities.WriteLog($"List contains {PolyhedraCE.ListOfPolyhedra.Count} entries.");

                BPSUtilities.WriteLog($"CreatePolyhedronX64: Dynamics {(this.DynamicsStarted ? "is" : "is not")} started.");
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"CreatePolyhedronX64 {ex.Message}\n{ex.StackTrace}");
            }
        }
예제 #17
0
        protected override void OnPostInstall()
        {
            try
            {
                BPSUtilities.WriteLog("PlaceQRCode OnPostInstall");

                NotificationManager.OutputPrompt("Enter data point for corner of QR Code. Reset to exit.");
                // AccuSnap.SnapEnabled = true;
                // AccuSnap.LocateEnabled = true;
                base.OnPostInstall();

                m_haveFirstPoint = false;
                // base.BeginDynamics();
                m_firstPoint = DPoint3d.Zero;

                if (!string.IsNullOrEmpty(LongURL))
                {
                    QRCodeEncoderLibrary.QREncoder enc = QRCodeImageFunctions.GetQREncoderObject(LongURL);

                    BPSUtilities.WriteLog($"QRCodeDimension: {enc.QRCodeDimension}");

                    if (enc.QRCodeDimension > 0)
                    {
                        DPoint3d[] blkPts = new DPoint3d[4];

                        blkPts[0] = blkPts[1] = blkPts[2] = blkPts[3] = DPoint3d.Zero;

                        blkPts[0].X = enc.QuietZone;
                        blkPts[0].Y = enc.QuietZone;

                        blkPts[1].X = enc.QuietZone + 1.0;
                        blkPts[1].Y = enc.QuietZone;
                        blkPts[2].X = enc.QuietZone + 1.0;
                        blkPts[2].Y = enc.QuietZone + 1.0;
                        blkPts[3].X = enc.QuietZone;
                        blkPts[3].Y = enc.QuietZone + 1.0;

                        DPoint3d[] blkPts2 = new DPoint3d[4];

                        DVector3d yVec = new DVector3d(0, 1, 0);
                        DVector3d xVec = new DVector3d(1, 0, 0);

                        DMatrix3d cellRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                        List <Bentley.DgnPlatformNET.Elements.Element> listChildElements = new List <Bentley.DgnPlatformNET.Elements.Element>();

                        // bool[,] pixels = enc.ConvertQRCodeMatrixToPixels();

                        for (int i = 0; i < enc.QRCodeDimension; i++)
                        {
                            // reset row
                            for (int index = 0; index < 4; index++)
                            {
                                blkPts2[index] = blkPts[index];
                            }

                            // move up
                            for (int index = 0; index < 4; index++)
                            {
                                blkPts2[index] = DPoint3d.Add(blkPts2[index], yVec, (double)i);
                            }

                            for (int j = 0; j < enc.QRCodeDimension; j++)
                            {
                                if (enc.QRCodeMatrix[i, j])
                                {
                                    Bentley.DgnPlatformNET.Elements.ShapeElement shapeElement =
                                        new Bentley.DgnPlatformNET.Elements.ShapeElement(Session.Instance.GetActiveDgnModel(), null, blkPts2);

                                    ElementPropertiesSetter pSetter = new ElementPropertiesSetter();

                                    pSetter.SetColor((uint)Bentley.MstnPlatformNET.Settings.GetActiveFillColor().Index);
                                    pSetter.SetFillColor((uint)Bentley.MstnPlatformNET.Settings.GetActiveFillColor().Index);
                                    shapeElement.AddSolidFill((uint)Bentley.MstnPlatformNET.Settings.GetActiveFillColor().Index, true);

                                    pSetter.Apply(shapeElement);

                                    if (shapeElement.IsValid)
                                    {
                                        listChildElements.Add(shapeElement);
                                    }
                                }

                                // move across
                                for (int index = 0; index < 4; index++)
                                {
                                    blkPts2[index] = DPoint3d.Add(blkPts2[index], xVec);
                                }
                            }
                        }

                        DPoint3d[] blkPts3 = new DPoint3d[5];

                        blkPts3[0] = blkPts3[1] = blkPts3[2] = blkPts3[3] = blkPts3[4] = DPoint3d.Zero;

                        blkPts3[1].X = 2 * enc.QuietZone + enc.QRCodeDimension;
                        blkPts3[2].X = 2 * enc.QuietZone + enc.QRCodeDimension;
                        blkPts3[2].Y = 2 * enc.QuietZone + enc.QRCodeDimension;
                        blkPts3[3].Y = 2 * enc.QuietZone + enc.QRCodeDimension;

                        Bentley.DgnPlatformNET.Elements.LineStringElement border = new LineStringElement(Session.Instance.GetActiveDgnModel(), null, blkPts3);

                        ElementPropertiesSetter pSetter2 = new ElementPropertiesSetter();

                        pSetter2.SetColor((uint)Bentley.MstnPlatformNET.Settings.GetActiveFillColor().Index);

                        pSetter2.Apply(border);

                        listChildElements.Add(border);

                        Bentley.DgnPlatformNET.Elements.CellHeaderElement codeElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), "QRCode",
                                                                                                              new DPoint3d(0, 0, 0), cellRotation, listChildElements);

                        // scale down to one...

                        DMatrix3d rotMatrix = DMatrix3d.Identity;

                        rotMatrix.ScaleInPlace((double)1.0 / (double)enc.QRCodeDimension);

                        DTransform3d translateAndScale =
                            DTransform3d.FromMatrixAndTranslation(rotMatrix, DPoint3d.Zero);

                        TransformInfo transformInfo = new TransformInfo(translateAndScale);

                        codeElement.ApplyTransform(transformInfo);

                        CodeElement = codeElement;

                        // might want to tag with the URL...

                        if (CodeElement.IsValid)
                        {
                            base.BeginDynamics();
                        }
                    }
                }

                BPSUtilities.WriteLog($"PlaceQRCode OnPostInstall Dynamics {(this.DynamicsStarted ? "is" : "is not")} started.");
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"PlaceQRCode OnPostInstall {ex.Message}\n{ex.StackTrace}");
            }
        }
        protected override bool OnDataButton(DgnButtonEvent ev)
        {
            try
            {
                if (m_haveFirstPoint)
                {
                    // we're going to write the element

                    base.EndDynamics();

                    // now to work on rotation and scale
                    DPoint3d translation = m_firstPoint;

                    DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                    DPoint3d[] blkPts = new DPoint3d[4];

                    // rotate points to orthogonal
                    blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                    blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                    blkPts[2].Z = blkPts[0].Z;

                    DPoint3d ext = DPoint3d.Subtract(blkPts[2], blkPts[0]);

                    DVector3d angleVec = new DVector3d(ext);

                    double dScale = Math.Max(0.1, Math.Abs(ext.Magnitude / uorPerMaster()));

                    //RedrawElems redrawElems = new RedrawElems();
                    //redrawElems.SetDynamicsViewsFromActiveViewSet(Bentley.MstnPlatformNET.Session.GetActiveViewport());
                    //redrawElems.DrawMode = DgnDrawMode.Normal;
                    //redrawElems.DrawPurpose = DrawPurpose.ForceRedraw;

                    try
                    {
                        DMatrix3d invertedViewportRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                        if (ev.Viewport.GetRotation().TryInvert(out invertedViewportRotation))
                        {
                            DMatrix3d cellRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                            List <Bentley.DgnPlatformNET.Elements.Element> listChildElements = new List <Bentley.DgnPlatformNET.Elements.Element>();

                            foreach (Bentley.DgnPlatformNET.Elements.Element child in PolyhedraCE.StaticElement.GetChildren())
                            {
                                listChildElements.Add(child);
                            }

                            Bentley.DgnPlatformNET.Elements.CellHeaderElement copiedElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), PolyhedronName,
                                                                                                                    new DPoint3d(0, 0, 0), cellRotation, listChildElements);

                            if (copiedElement != null)
                            {
                                if (copiedElement.IsValid)
                                {
                                    invertedViewportRotation.ScaleInPlace(dScale);

                                    DMatrix3d scaleRotateInViewRotateAroundPoint = DMatrix3d.Multiply(invertedViewportRotation, DMatrix3d.Rotation(2, angleVec.AngleXY));

                                    DTransform3d translateAndRotatetoUpInViewAndScale =
                                        DTransform3d.FromMatrixAndTranslation(scaleRotateInViewRotateAroundPoint, translation);

                                    TransformInfo transformInfo2 = new TransformInfo(translateAndRotatetoUpInViewAndScale);

                                    copiedElement.ApplyTransform(transformInfo2);

                                    copiedElement.AddToModel();

                                    BPSUtilities.WriteLog("Added element to model");

                                    RedrawElems redrawElems = new RedrawElems();
                                    redrawElems.SetDynamicsViewsFromActiveViewSet(ev.Viewport);
                                    redrawElems.DrawMode    = DgnDrawMode.Normal;
                                    redrawElems.DrawPurpose = DrawPurpose.ForceRedraw;

                                    redrawElems.DoRedraw(copiedElement);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"OnDataBurron {ex.Message}\n{ex.StackTrace}");
                    }

                    m_haveFirstPoint = false;

                    m_firstPoint = new DPoint3d(0, 0, 0);

                    base.BeginDynamics();

                    return(true);
                }

                m_haveFirstPoint = true;

                m_firstPoint = ev.Point;

                base.BeginDynamics();
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"OnDataButton {ex.Message}\n{ex.StackTrace}");
            }

            return(true);
        }
        /// <summary>
        /// Calls the my Azure API to shorten the long URL into an adddress like shl.pw/2v and returns QR Code image of the shortened URL
        /// </summary>
        /// <param name="sLongURL">URL to shorten and generate image of</param>
        /// <param name="iSize">Size of image to generate with ZXing</param>
        /// <param name="iCropBorder">Sometimes too much white space around QR Code and needs cropping</param>
        /// <returns>The (optionally cropped) QRCode Image of the shortened URL from ZXing</returns>
        public static Image GetQRCodeImage(string sLongURL, int iSize, int iCropBorder)
        {
            string url = "https://pwqrazurefunctionapp.azurewebsites.net/api/ShortenURLPost?code=bxwoszCCCjEGB2KTqiw/tcNCoNCKMdu9jdcbB2xiXcUoxPhMHWRTDA==";

            Image img = null;

            try
            {
                // build WSG file link
                var linkToShorten = new ShortenThisURLWithAzure
                {
                    Input = sLongURL
                };

                HttpRequestMessage request       = new HttpRequestMessage(HttpMethod.Post, url);
                HttpClient         connectClient = new HttpClient();
                connectClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var body = JSONHelper.SerializeJSon <ShortenThisURLWithAzure>(linkToShorten);
                request.Content = new StringContent(body, Encoding.UTF8, "application/json");

                var    response        = connectClient.SendAsync(request).Result;
                string responseContent = response.Content.ReadAsStringAsync().Result;

                BPSUtilities.WriteLog(responseContent);

                // this is dumb
                ShortenedURLResponseFromAzure shortUrl = JSONHelper.DeserializeJSon <ShortenedURLResponseFromAzure>(responseContent.Replace("[", "").Replace("]", ""));

                if (shortUrl != null)
                {
                    if (!string.IsNullOrEmpty(shortUrl.ShortUrl))
                    {
                        BPSUtilities.WriteLog($"'{shortUrl.LongUrl}' shortened to '{shortUrl.ShortUrl}'");

                        img = (Image)CreateQRCode(shortUrl.ShortUrl, iSize);

                        BPSUtilities.WriteLog($"Original QR Code size is {img.Width} x {img.Height}.");

                        if (img.Width > iSize)
                        {
                            Image img3 = ResizeImage(img, iSize, iSize, ImageFormat.Png);
                            img = img3;
                        }

                        BPSUtilities.WriteLog(string.Format("QR Code is {0} X {1}.", img.Width, img.Height, iCropBorder));
                    }
                }
                else
                {
                    BPSUtilities.WriteLog("Short URL not generated.");
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog("Error: " + ex.Message);
                BPSUtilities.WriteLog(ex.StackTrace);
            }

            return(img);
        }
        public Bentley.DgnPlatformNET.Elements.Element SetPolyhedron(string sPolyhedronName, string sXMLFileName)
        {
            BPSUtilities.WriteLog($"Creating '{sPolyhedronName}' from '{sXMLFileName}'");

            List <DPoint3d>    points       = new List <DPoint3d>();
            List <List <int> > faceVertices = new List <List <int> >();
            List <DPoint3d>    rgbColors    = new List <DPoint3d>();

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(sXMLFileName);

                XmlNode polyhedronNode = null;

                XmlNode root = xmlDoc.DocumentElement;

                if (sPolyhedronName.Length > 0)
                {
                    polyhedronNode =
                        root.SelectSingleNode(String.Format("polyhedron[@name = \"{0}\"]", sPolyhedronName));
                }

                if (polyhedronNode != null)
                {
                    BPSUtilities.WriteLog($"Vertices: {polyhedronNode.Attributes["vertices"].Value}");

                    int iNumVertices = Int32.Parse(polyhedronNode.Attributes["vertices"].Value);

                    BPSUtilities.WriteLog($"Faces: {polyhedronNode.Attributes["faces"].Value}");

                    int iNumFaces = Int32.Parse(polyhedronNode.Attributes["faces"].Value);

                    XmlNode vertices = polyhedronNode.SelectSingleNode("vertices");

                    if (vertices != null)
                    {
                        foreach (XmlNode vertex in vertices.ChildNodes)
                        {
                            // BPSUtilities.WriteLog(vertex.InnerText);
                            string[] split = vertex.InnerText.Trim().Split(new Char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                            string[] values = new string[3];

                            int iValIndex = 0;

                            foreach (string s in split)
                            {
                                if (s.Length > 0 && iValIndex < 3)
                                {
                                    values[iValIndex++] = s;
                                }
                            }

                            try
                            {
                                points.Add(new DPoint3d(Double.Parse(values[0]), Double.Parse(values[1]), Double.Parse(values[2])));
                            }
                            catch (Exception ex)
                            {
                                BPSUtilities.WriteLog($"X: {values[0]},Y: {values[1]},Z: {values[2]}");

                                BPSUtilities.WriteLog($"Error parsing point, {ex.Message}");
                            }
                        }
                    }
                    else
                    {
                        BPSUtilities.WriteLog("Vertices node not found.");
                    }

                    XmlNode faces = polyhedronNode.SelectSingleNode("faces");

                    int iFaceCount = 0;

                    if (faces != null)
                    {
                        foreach (XmlNode face in faces.ChildNodes)
                        {
                            // BPSUtilities.WriteLog($"vertexcount: {face.Attributes["vertexcount"].Value}");

                            int iVtxCount = Int32.Parse(face.Attributes["vertexcount"].Value);

                            string[] split = face.InnerText.Trim().Split(new Char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                            List <int> listVertices = new List <int>();

                            foreach (string s in split)
                            {
                                try
                                {
                                    listVertices.Add(int.Parse(s));
                                }
                                catch (Exception ex)
                                {
                                    BPSUtilities.WriteLog($"Error parsing '{s}' {ex.Message}");
                                    BPSUtilities.WriteLog($"Face list '{face.InnerText}'");
                                }
                            }

                            faceVertices.Add(listVertices);

                            string[] colorSplit =
                                face.Attributes["RGB"].Value.Trim().Split(new Char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                            if (colorSplit.Length == 3)
                            {
                                try
                                {
                                    rgbColors.Add(new DPoint3d(Double.Parse(colorSplit[0]),
                                                               Double.Parse(colorSplit[1]),
                                                               Double.Parse(colorSplit[2])));
                                }
                                catch (Exception ex)
                                {
                                    BPSUtilities.WriteLog($"Error parsing RGB, {ex.Message}");
                                    BPSUtilities.WriteLog($"R: {colorSplit[0]}, G: {colorSplit[1]}, B: {colorSplit[2]}");
                                }
                            }

                            iFaceCount++;
                        } // foreach face
                    }
                }         // found a node
                else
                {
                    BPSUtilities.WriteLog("Node not found.");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                return(null);
            }

            if (points.Count > 0 && faceVertices.Count > 0 && rgbColors.Count > 0)
            {
                return(CreatePolyhedronCell(sPolyhedronName, points, faceVertices, rgbColors));
            }

            return(null);
        }
예제 #21
0
        protected override void OnDynamicFrame(Bentley.DgnPlatformNET.DgnButtonEvent ev)
        {
            RedrawElems redrawElems = new RedrawElems();

            redrawElems.SetDynamicsViewsFromActiveViewSet(Bentley.MstnPlatformNET.Session.GetActiveViewport());
            redrawElems.DrawMode    = DgnDrawMode.TempDraw;
            redrawElems.DrawPurpose = DrawPurpose.Dynamics;

            try
            {
                DMatrix3d invertedViewportRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                if (ev.Viewport.GetRotation().TryInvert(out invertedViewportRotation))
                {
                    if (CodeElement != null)
                    {
                        if (CodeElement.IsValid)
                        {
                            List <Bentley.DgnPlatformNET.Elements.Element> listChildElements = CodeElement.GetChildren().GetEnumerator().ConvertToList();

                            Bentley.DgnPlatformNET.Elements.CellHeaderElement codeElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), "QRCode",
                                                                                                                  DPoint3d.Zero, DMatrix3d.Identity, listChildElements);

                            if (codeElement.IsValid)
                            {
                                if (m_haveFirstPoint)
                                {
                                    // now to work on rotation and scale
                                    DPoint3d translation = m_firstPoint;

                                    DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                    DPoint3d[] blkPts = new DPoint3d[4];

                                    // rotate points to orthogonal
                                    blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                                    blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                                    blkPts[2].Z = blkPts[0].Z;

                                    DPoint3d ext = DPoint3d.Subtract(blkPts[2], blkPts[0]);

                                    DVector3d angleVec = new DVector3d(ext);

                                    // double dScale = Math.Max(0.1, Math.Abs(ext.Magnitude / uorPerMaster()));

                                    invertedViewportRotation.ScaleInPlace(ext.Magnitude);

                                    DVector3d xVec = new DVector3d(1, 0, 0);

                                    DVector3d yVec = new DVector3d(0, 1, 0);

                                    Angle angle = Angle.Zero;

                                    //// UR and LR
                                    if (angleVec.AngleTo(xVec).Radians >= 0.0 && angleVec.AngleTo(xVec).Radians <= (Angle.PI.Radians / 2.0))
                                    {
                                        if (angleVec.AngleTo(yVec).Radians >= 0.0 && angleVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                        {
                                            angle = Angle.Zero;
                                        }
                                        else
                                        {
                                            angle.Radians = Angle.NEGATIVE_PI.Radians / 2.0;
                                        }
                                    }
                                    // UL and LL
                                    else
                                    {
                                        if (angleVec.AngleTo(yVec).Radians >= 0.0 && angleVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                        {
                                            angle.Radians = Angle.PI.Radians / 2.0;
                                        }
                                        else
                                        {
                                            angle.Radians = Angle.PI.Radians;
                                        }
                                    }

                                    DMatrix3d scaleRotateInViewRotateAroundPoint = DMatrix3d.Multiply(invertedViewportRotation,
                                                                                                      // DMatrix3d.Rotation(2, angleVec.AngleXY));
                                                                                                      DMatrix3d.Rotation(2, angle));

                                    // DMatrix3d scaleRotateInViewRotateAroundPoint = DMatrix3d.Multiply(invertedViewportRotation,
                                    // DMatrix3d.Rotation(2, angleVec.AngleXY));

                                    DTransform3d translateAndRotatetoUpInViewAndScale =
                                        DTransform3d.FromMatrixAndTranslation(scaleRotateInViewRotateAroundPoint, translation);

                                    TransformInfo transformInfo2 = new TransformInfo(translateAndRotatetoUpInViewAndScale);

                                    codeElement.ApplyTransform(transformInfo2);

                                    // below works great for drawing a block
                                    //DPoint3d[] blkPts = new DPoint3d[4];

                                    //DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                    //// rotate points to orthogonal
                                    //blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                                    //blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                                    //blkPts[2].Z = blkPts[0].Z;

                                    //blkPts[1].X = blkPts[0].X;
                                    //blkPts[1].Y = blkPts[2].Y;
                                    //blkPts[1].Z = blkPts[0].Z;

                                    //blkPts[3].X = blkPts[2].X;
                                    //blkPts[3].Y = blkPts[0].Y;
                                    //blkPts[3].Z = blkPts[0].Z;

                                    //DVector3d dVec = new DVector3d(blkPts[0], blkPts[2]);

                                    //double dWidth = blkPts[0].Distance(blkPts[1]);
                                    //double dHeight = blkPts[0].Distance(blkPts[3]);

                                    //double dDelta = Math.Abs(dWidth);

                                    //if (Math.Abs(dHeight) > Math.Abs(dWidth))
                                    //    dDelta = Math.Abs(dHeight);

                                    //blkPts[3] = blkPts[2] = blkPts[1] = blkPts[0];

                                    //DVector3d xVec = new DVector3d(1, 0, 0);

                                    //DVector3d yVec = new DVector3d(0, 1, 0);

                                    //double xFactor = 1.0, yFactor = 1.0;

                                    //// UR and LR
                                    //if (dVec.AngleTo(xVec).Radians >= 0.0 && dVec.AngleTo(xVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //{
                                    //    if (dVec.AngleTo(yVec).Radians >= 0.0 && dVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X + dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y + dDelta;
                                    //    }
                                    //    else
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X + dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y - dDelta;
                                    //        yFactor = -1.0;
                                    //    }
                                    //}
                                    //// UL and LL
                                    //else
                                    //{
                                    //    if (dVec.AngleTo(yVec).Radians >= 0.0 && dVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X - dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y + dDelta;
                                    //        xFactor = -1.0;
                                    //    }
                                    //    else
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X - dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y - dDelta;
                                    //        xFactor = -1.0;
                                    //        yFactor = -1.0;
                                    //    }
                                    //}

                                    //blkPts[1].X = blkPts[0].X;
                                    //blkPts[1].Y = blkPts[2].Y;
                                    //blkPts[1].Z = blkPts[0].Z;

                                    //blkPts[3].X = blkPts[2].X;
                                    //blkPts[3].Y = blkPts[0].Y;
                                    //blkPts[3].Z = blkPts[0].Z;

                                    //DPoint3d[] blkPts2 = new DPoint3d[4];

                                    //blkPts2[0] = blkPts2[1] = blkPts2[2] = blkPts2[3] = blkPts[0];

                                    //for (int i = 0; i < 4; i++)
                                    //{
                                    //    blkPts[i] = new DPoint3d(invertedViewportRotation.Multiply(new DVector3d(blkPts[i])));
                                    //}

                                    //Bentley.DgnPlatformNET.Elements.ShapeElement shapeElement =
                                    //    new Bentley.DgnPlatformNET.Elements.ShapeElement(Session.Instance.GetActiveDgnModel(), null, blkPts);

                                    //blkPts2[0].X += (xFactor) * dDelta / 4.0;
                                    //blkPts2[0].Y += (yFactor) * dDelta / 4.0;

                                    //blkPts2[2].X += (xFactor) * 3.0 * (dDelta / 4.0);
                                    //blkPts2[2].Y += (yFactor) * 3.0 * (dDelta / 4.0);

                                    //blkPts2[1].X = blkPts2[0].X;
                                    //blkPts2[1].Y = blkPts2[2].Y;
                                    //blkPts2[1].Z = blkPts2[0].Z;

                                    //blkPts2[3].X = blkPts2[2].X;
                                    //blkPts2[3].Y = blkPts2[0].Y;
                                    //blkPts2[3].Z = blkPts2[0].Z;

                                    //for (int i = 0; i < 4; i++)
                                    //{
                                    //    blkPts2[i] = new DPoint3d(invertedViewportRotation.Multiply(new DVector3d(blkPts2[i])));
                                    //}

                                    //Bentley.DgnPlatformNET.Elements.ShapeElement shapeElement2 =
                                    //    new Bentley.DgnPlatformNET.Elements.ShapeElement(Session.Instance.GetActiveDgnModel(), null, blkPts2);

                                    //redrawElems.DoRedraw(shapeElement);
                                    //redrawElems.DoRedraw(shapeElement2);
                                }
                                else
                                {
                                    // picking something arbitrary to use as scale factor
                                    invertedViewportRotation.ScaleInPlace(Bentley.MstnPlatformNET.Settings.TextHeight);

                                    DTransform3d scaleAndRotateToUpInView = DTransform3d.FromMatrixAndTranslation(invertedViewportRotation, ev.Point);

                                    TransformInfo transformInfo = new TransformInfo(scaleAndRotateToUpInView);

                                    codeElement.ApplyTransform(transformInfo);
                                }

                                redrawElems.DoRedraw(codeElement);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
            }
        }
        // man, this is slow.  Would love to find another way...
        private static System.Data.DataSet ReadData(string sWBName)
        {
            System.Data.DataSet ds = new System.Data.DataSet();

            if (System.IO.File.Exists(sWBName))
            {
                try
                {
                    try
                    {
                        UriParser.Register(new PWUriParser(GenericUriParserOptions.AllowEmptyAuthority |
                                                           GenericUriParserOptions.DontCompressPath | GenericUriParserOptions.DontConvertPathBackslashes |
                                                           GenericUriParserOptions.DontUnescapePathDotsAndSlashes | GenericUriParserOptions.GenericAuthority |
                                                           GenericUriParserOptions.NoFragment), "pw", 5800);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("Error: {0}\n{1}", ex.Message, ex.StackTrace));
                    }

                    var wb = new XLWorkbook(sWBName);

                    foreach (var ws in wb.Worksheets)
                    {
                        if (ds.Tables.Contains(ws.Name))
                        {
                            continue;
                        }

                        // BPSUtilities.WriteLog("Reading table '{0}'...", ws.Name);

                        DataTable dt = new DataTable(ws.Name);

                        int iIndex = 1;

                        while (!string.IsNullOrEmpty(ws.Row(1).Cell(iIndex).Value.ToString()))
                        {
                            string sColumnName = ws.Row(1).Cell(iIndex).Value.ToString();

                            try
                            {
                                dt.Columns.Add(new DataColumn(sColumnName, ws.Row(2).Cell(iIndex).Value.GetType()));
                            }
                            catch
                            {
                                try
                                {
                                    dt.Columns.Add(new DataColumn(sColumnName, Type.GetType("System.String")));
                                }
                                catch (Exception ex)
                                {
                                    BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);

                                    // logic will really be screwed up if column cant' get added
                                    return(null);
                                }
                            }

                            iIndex++;
                        } // for each column

                        if (dt.Columns.Count == 0)
                        {
                            continue;
                        }

                        int iNumCols = dt.Columns.Count;

                        int iRow = 2;

                        while (!ws.Row(iRow).IsEmpty())
                        {
                            DataRow dr = dt.NewRow();

                            for (int iCol = 1; iCol <= iNumCols; iCol++)
                            {
                                try
                                {
                                    IXLCell cell = ws.Row(iRow).Cell(iCol);

                                    if (cell.Hyperlink != null)
                                    {
                                        if (cell.Hyperlink.ExternalAddress != null)
                                        {
                                            dr[iCol - 1] = cell.Hyperlink.ExternalAddress.OriginalString;
                                        }
                                        else
                                        {
                                            dr[iCol - 1] = cell.Value;
                                        }
                                    }
                                    else
                                    {
                                        dr[iCol - 1] = cell.Value;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    string.Format("Error: {0}\n{1}", ex.Message, ex.StackTrace);
                                }
                            }

                            try
                            {
                                dt.Rows.Add(dr);
                            }
                            catch (Exception ex)
                            {
                                BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
                            }

                            iRow++;
                            // BPSUtilities.WriteLog("{0}: {1}", dt.TableName, iRow);
                        } // for each row

                        try
                        {
                            // BPSUtilities.WriteLog("Read {0} rows.", dt.Rows.Count);
                            ds.Tables.Add(dt);
                        }
                        catch (Exception ex)
                        {
                            BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
                        }
                    }
                }
                catch (Exception ex)
                {
                    BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
                }
            }
            else
            {
                BPSUtilities.WriteLog("Workbook '{0}' not found", sWBName);
            }

            return(ds);
        }
        // should create on 0,0,0 center
        private Bentley.DgnPlatformNET.Elements.Element CreatePolyhedronCell(string sPolyhedronName,
                                                                             List <DPoint3d> points, List <List <int> > faces, List <DPoint3d> colors)
        {
            try
            {
                List <Bentley.DgnPlatformNET.Elements.Element> listElements = new List <Bentley.DgnPlatformNET.Elements.Element>();

                if (points.Count > 0 && faces.Count > 0)
                {
                    int iFaceIndex = 0;

                    foreach (List <int> listVertices in faces)
                    {
                        List <DPoint3d> listPoints = new List <DPoint3d>();

                        foreach (int iVertexIndex in listVertices)
                        {
                            DPoint3d pt = points[iVertexIndex];
                            pt.ScaleInPlace(uorPerMaster());
                            listPoints.Add(pt);
                        }

                        DPoint3d color = colors.ToArray()[iFaceIndex++];

                        Bentley.DgnPlatformNET.Elements.ShapeElement shapeElement =
                            new Bentley.DgnPlatformNET.Elements.ShapeElement(Session.Instance.GetActiveDgnModel(), null, listPoints.ToArray());

                        DVector3d normal    = new DVector3d();
                        DPoint3d  somePoint = new DPoint3d();
                        DPoint3d  defNormal = listPoints.ToArray()[0];

                        shapeElement.IsPlanar(out normal, out somePoint, ref defNormal);

                        uint iColorIndex = (uint)listPoints.Count - 1;

                        ElementPropertiesSetter pSetter = new ElementPropertiesSetter();

                        pSetter.SetColor(iColorIndex);
                        pSetter.SetFillColor(iColorIndex);
                        shapeElement.AddSolidFill(iColorIndex, false);

                        pSetter.Apply(shapeElement);

                        listElements.Add(shapeElement);
                    }
                }

                if (listElements.Count > 0)
                {
                    DMatrix3d rotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity
                    Bentley.DgnPlatformNET.Elements.CellHeaderElement cellHeaderElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), sPolyhedronName,
                                                                                                                new DPoint3d(0, 0, 0), rotation, listElements);

                    return(cellHeaderElement);
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"CreatePolyhedronCell {ex.Message}\n{ex.StackTrace}");
            }


            return(null);
        }
예제 #24
0
        protected override bool OnDataButton(DgnButtonEvent ev)
        {
            try
            {
                if (m_haveFirstPoint)
                {
                    // we're going to write the element

                    base.EndDynamics();

                    if (CodeElement != null)
                    {
                        if (CodeElement.IsValid)
                        {
                            List <Bentley.DgnPlatformNET.Elements.Element> listChildElements = CodeElement.GetChildren().GetEnumerator().ConvertToList();

                            Bentley.DgnPlatformNET.Elements.CellHeaderElement codeElement = new CellHeaderElement(Session.Instance.GetActiveDgnModel(), "QRCode",
                                                                                                                  DPoint3d.Zero, DMatrix3d.Identity, listChildElements);

                            if (codeElement.IsValid)
                            {
                                DMatrix3d invertedViewportRotation = new DMatrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1);   // Identity

                                if (ev.Viewport.GetRotation().TryInvert(out invertedViewportRotation))
                                {
                                    // now to work on rotation and scale
                                    DPoint3d translation = m_firstPoint;

                                    DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                    DPoint3d[] blkPts = new DPoint3d[4];

                                    // rotate points to orthogonal
                                    blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                                    blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                                    blkPts[2].Z = blkPts[0].Z;

                                    DPoint3d ext = DPoint3d.Subtract(blkPts[2], blkPts[0]);

                                    DVector3d angleVec = new DVector3d(ext);

                                    // double dScale = Math.Max(0.1, Math.Abs(ext.Magnitude / uorPerMaster()));

                                    invertedViewportRotation.ScaleInPlace(ext.Magnitude);

                                    DVector3d xVec = new DVector3d(1, 0, 0);

                                    DVector3d yVec = new DVector3d(0, 1, 0);

                                    Angle angle = Angle.Zero;

                                    //// UR and LR
                                    if (angleVec.AngleTo(xVec).Radians >= 0.0 && angleVec.AngleTo(xVec).Radians <= (Angle.PI.Radians / 2.0))
                                    {
                                        if (angleVec.AngleTo(yVec).Radians >= 0.0 && angleVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                        {
                                            angle = Angle.Zero;
                                        }
                                        else
                                        {
                                            angle.Radians = Angle.NEGATIVE_PI.Radians / 2.0;
                                        }
                                    }
                                    // UL and LL
                                    else
                                    {
                                        if (angleVec.AngleTo(yVec).Radians >= 0.0 && angleVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                        {
                                            angle.Radians = Angle.PI.Radians / 2.0;
                                        }
                                        else
                                        {
                                            angle.Radians = Angle.PI.Radians;
                                        }
                                    }

                                    DMatrix3d scaleRotateInViewRotateAroundPoint = DMatrix3d.Multiply(invertedViewportRotation,
                                                                                                      // DMatrix3d.Rotation(2, angleVec.AngleXY));
                                                                                                      DMatrix3d.Rotation(2, angle));

                                    DTransform3d translateAndRotatetoUpInViewAndScale =
                                        DTransform3d.FromMatrixAndTranslation(scaleRotateInViewRotateAroundPoint, translation);

                                    TransformInfo transformInfo2 = new TransformInfo(translateAndRotatetoUpInViewAndScale);

                                    codeElement.ApplyTransform(transformInfo2);

                                    //DPoint3d[] blkPts = new DPoint3d[4];

                                    //DMatrix3d viewMatrix = ev.Viewport.GetRotation();

                                    //// rotate points to orthogonal
                                    //blkPts[0] = new DPoint3d(viewMatrix.Multiply(new DVector3d(m_firstPoint)));

                                    //blkPts[2] = new DPoint3d(viewMatrix.Multiply(new DVector3d(ev.Point)));

                                    //blkPts[2].Z = blkPts[0].Z;

                                    //blkPts[1].X = blkPts[0].X;
                                    //blkPts[1].Y = blkPts[2].Y;
                                    //blkPts[1].Z = blkPts[0].Z;

                                    //blkPts[3].X = blkPts[2].X;
                                    //blkPts[3].Y = blkPts[0].Y;
                                    //blkPts[3].Z = blkPts[0].Z;

                                    //DVector3d dVec = new DVector3d(blkPts[0], blkPts[2]);

                                    //double dWidth = blkPts[0].Distance(blkPts[1]);
                                    //double dHeight = blkPts[0].Distance(blkPts[3]);

                                    //double dDelta = Math.Max(Math.Abs(dWidth), Math.Abs(dHeight));

                                    //blkPts[3] = blkPts[2] = blkPts[1] = blkPts[0];

                                    //DVector3d xVec = new DVector3d(1, 0, 0);

                                    //DVector3d yVec = new DVector3d(0, 1, 0);

                                    //// UR and LR
                                    //if (dVec.AngleTo(xVec).Radians >= 0.0 && dVec.AngleTo(xVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //{
                                    //    if (dVec.AngleTo(yVec).Radians >= 0.0 && dVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X + dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y + dDelta;
                                    //    }
                                    //    else
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X + dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y - dDelta;
                                    //    }
                                    //}
                                    //// UL and LL
                                    //else
                                    //{
                                    //    if (dVec.AngleTo(yVec).Radians >= 0.0 && dVec.AngleTo(yVec).Radians <= (Angle.PI.Radians / 2.0))
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X - dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y + dDelta;
                                    //    }
                                    //    else
                                    //    {
                                    //        blkPts[2].X = blkPts[0].X - dDelta;
                                    //        blkPts[2].Y = blkPts[0].Y - dDelta;
                                    //    }
                                    //}

                                    //blkPts[1].X = blkPts[0].X;
                                    //blkPts[1].Y = blkPts[2].Y;
                                    //blkPts[1].Z = blkPts[0].Z;

                                    //blkPts[3].X = blkPts[2].X;
                                    //blkPts[3].Y = blkPts[0].Y;
                                    //blkPts[3].Z = blkPts[0].Z;

                                    //for (int i = 0; i < 4; i++)
                                    //{
                                    //    blkPts[i] = new DPoint3d(invertedViewportRotation.Multiply(new DVector3d(blkPts[i])));
                                    //}

                                    //Bentley.DgnPlatformNET.Elements.ShapeElement shapeElement =
                                    //    new Bentley.DgnPlatformNET.Elements.ShapeElement(Session.Instance.GetActiveDgnModel(), null, blkPts);

                                    RedrawElems redrawElems = new RedrawElems();
                                    redrawElems.SetDynamicsViewsFromActiveViewSet(Bentley.MstnPlatformNET.Session.GetActiveViewport());
                                    redrawElems.DrawMode    = DgnDrawMode.Normal;
                                    redrawElems.DrawPurpose = DrawPurpose.ForceRedraw;

                                    codeElement.AddToModel();

                                    redrawElems.DoRedraw(codeElement);

                                    m_haveFirstPoint = false;

                                    m_firstPoint = new DPoint3d(0, 0, 0);

                                    base.BeginDynamics();

                                    return(true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    m_haveFirstPoint = true;

                    m_firstPoint = ev.Point;

                    // base.BeginDynamics();
                }
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog($"OnDataButton {ex.Message}\n{ex.StackTrace}");
            }

            return(true);
        }
        public static void SaveReport(string unparsed)
        {
            string sReportFile = Path.Combine(Path.GetTempPath(), $"{BPSUtilities.GetARandomString(8, "abcdefghijklmnopqrstuvwxyz")}.rpt");

            try
            {
                Bentley.DgnPlatformNET.ConfigurationManager.WriteActiveConfigurationSummary(sReportFile);
            }
            catch (Exception ex)
            {
                BPSUtilities.WriteLog("Error: {0}\n{1}", ex.Message, ex.StackTrace);
            }

            if (File.Exists(sReportFile))
            {
                StringBuilder sbDSN = new StringBuilder(1024);

                bool bCheckPW = false;

                if (PWWrapper.aaApi_GetActiveDatasourceName(sbDSN, sbDSN.Capacity))
                {
                    bCheckPW = true;
                }

                DataSet ds = new DataSet();
                ds.Tables.Add(new DataTable("ConfigurationVariables"));

                ds.Tables[0].Columns.Add(new DataColumn("Name", typeof(string)));
                ds.Tables[0].Columns.Add(new DataColumn("Level", typeof(string)));
                ds.Tables[0].Columns.Add(new DataColumn("Value", typeof(string)));
                ds.Tables[0].Columns.Add(new DataColumn("ExpandedValue", typeof(string)));
                ds.Tables[0].Columns.Add(new DataColumn("InvalidPWPaths", typeof(string)));

                SortedList <string, int> slVariableLevels = new SortedList <string, int>()
                {
                    { "Application", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.Application },
                    { "Predefined", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.Predefined },
                    { "Organization", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.Organization },
                    { "WorkSpace", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.WorkSpace },
                    { "System Environment", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.SystemEnvironment },
                    { "System", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.System },
                    { "User", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.User },
                    { "WorkSet", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.WorkSet },
                    { "Role", (int)Bentley.DgnPlatformNET.ConfigurationVariableLevel.Role }
                };

                using (StreamReader sr = new StreamReader(sReportFile))
                {
                    while (!sr.EndOfStream)
                    {
                        string sLine = sr.ReadLine();

                        if (sLine.StartsWith("%level"))
                        {
                            DataRow dr = ds.Tables[0].NewRow();

                            string[] sSplits = sLine.Split(new string[1] {
                                "  "
                            }, StringSplitOptions.RemoveEmptyEntries);

                            if (sSplits.Length > 1)
                            {
                                dr["Level"] = sSplits[1];

                                string sLine2 = sr.ReadLine();

                                string[] sSplits2 = sLine2.Split(new string[1] {
                                    " = "
                                }, StringSplitOptions.RemoveEmptyEntries);

                                if (sSplits2.Length > 1)
                                {
                                    dr["Name"]  = sSplits2[0].Trim();
                                    dr["Value"] = sSplits2[1].Trim();

                                    string sExpandedValue = string.Empty;

                                    if (slVariableLevels.ContainsKey(sSplits[1]))
                                    {
                                        sExpandedValue = Bentley.DgnPlatformNET.ConfigurationManager.GetVariable(sSplits2[0].Trim(),
                                                                                                                 (Bentley.DgnPlatformNET.ConfigurationVariableLevel)slVariableLevels[sSplits[1]]);
                                    }
                                    else
                                    {
                                        sExpandedValue = Bentley.DgnPlatformNET.ConfigurationManager.GetVariable(sSplits2[0].Trim());
                                    }

                                    dr["ExpandedValue"] = sExpandedValue;

                                    if (sExpandedValue.Contains("pw:") && bCheckPW)
                                    {
                                        string[] sSplits3 = sExpandedValue.Split(";".ToCharArray());

                                        SortedList <string, string> slUniqueValues = new SortedList <string, string>();

                                        foreach (string sSplit in sSplits3)
                                        {
                                            slUniqueValues.AddWithCheck(sSplit, sSplit);
                                        }

                                        StringBuilder sbInvalidPaths = new StringBuilder();

                                        foreach (string de in slUniqueValues.Keys)
                                        {
                                            if (de.ToLower().StartsWith("pw:"))
                                            {
                                                if (GetFolderNo(de.ToString()) < 1)
                                                {
                                                    if (sbInvalidPaths.Length > 0)
                                                    {
                                                        sbInvalidPaths.Append(";");
                                                    }

                                                    sbInvalidPaths.Append(de);
                                                }
                                            }
                                        }

                                        dr["InvalidPWPaths"] = sbInvalidPaths.ToString();
                                    }

                                    ds.Tables[0].Rows.Add(dr);
                                }
                            }
                        }
                    } // for each pair of lines in the file
                }

                if (!string.IsNullOrEmpty(unparsed))
                {
                    if (!unparsed.ToLower().EndsWith(".xlsx"))
                    {
                        unparsed += ".xlsx";
                    }
                }
                else
                {
                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.Title        = "Select Configuration File Report Output Location";
                    dlg.Filter       = "XLSX Files|*.xlsx|All Files|*.*";
                    dlg.DefaultExt   = ".xlsx";
                    dlg.AddExtension = true;

                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        unparsed = dlg.FileName;
                    }
                }

                if (ds.Tables[0].Rows.Count > 0 && !string.IsNullOrEmpty(unparsed))
                {
                    try
                    {
                        XLSXDataSetTools.DataSetToXLSXFast(ds, unparsed);

                        if (File.Exists(unparsed))
                        {
                            MessageBox.Show($"Wrote '{unparsed}'", "SetPWVarsCE");
                        }
                    }
                    catch (Exception ex)
                    {
                        BPSUtilities.WriteLog($"{ex.Message}\n{ex.StackTrace}");
                        MessageBox.Show($"Error writing '{unparsed}'", "SetPWVarsCE");
                    }
                }
            }
        }
        public static void Place(string unparsed)
        {
            if (string.IsNullOrEmpty(unparsed))
            {
                string sFileName = Bentley.MstnPlatformNET.Session.Instance.GetActiveDgnFile().GetFileName();

                BPSUtilities.WriteLog($"Filename is '{sFileName}'");

                int iProjectNo = 0, iDocumentNo = 0;

                PWWrapper.aaApi_Initialize(0);

                if (mcmMain_GetDocumentIdByFilePath(sFileName, 1,
                                                    ref iProjectNo, ref iDocumentNo))
                {
                    BPSUtilities.WriteLog($"IDs: {iProjectNo}, {iDocumentNo}");

                    if (iProjectNo > 0 && iDocumentNo > 0)
                    {
                        int GMAIL_PROJECTWISE_WEB_VIEW_SETTING = -5250;

                        string sWebViewURL = PWWrapper.GetPWStringSetting(GMAIL_PROJECTWISE_WEB_VIEW_SETTING);

                        string sProjectGUIDString  = PWWrapper.GetProjectGuidStringFromId(iProjectNo);
                        string sDocumentGUIDString = PWWrapper.GetGuidStringFromIds(iProjectNo, iDocumentNo);

                        if (!string.IsNullOrEmpty(sWebViewURL))
                        {
                            unparsed = $"{sWebViewURL}?project={sProjectGUIDString}&item={sDocumentGUIDString}";
                        }
                        else
                        {
                            BPSUtilities.WriteLog("No web view link address set.");
                        }
                    }
                    else
                    {
                        BPSUtilities.WriteLog("No integrated session of ProjectWise.");
                    }
                }
                else
                {
                    BPSUtilities.WriteLog("No integrated session of ProjectWise.");
                }

                if (string.IsNullOrEmpty(unparsed))
                {
                    unparsed = "www.bentley.com";
                }

                BPSUtilities.WriteLog($"Make code for this: {unparsed}");

                PlaceQRCode.InstallNewInstance(unparsed);
            }
            else
            {
                BPSUtilities.WriteLog($"Make code for this: {unparsed}");

                PlaceQRCode.InstallNewInstance(unparsed);
            }
        }