Example #1
0
        private IDataLink4 GetFreshConnection(ConnectionModel connectionModel, string databaseFile)
        {
            var dataLink = DataLinkManager.GetDataLink(databaseFile) as IDataLink4;

            _dataLinkConnections[databaseFile] = new Tuple <IDataLink4, DateTime>(dataLink, connectionModel.ConnectionExpiresInMinutes.GetExpiryDate());

            return(dataLink);
        }
Example #2
0
        public void Given_A_Bdix_File_When_I_Call_GetDataLink_A_Datalink_Is_Returned(string file)
        {
            //act
            var dataLink = DataLinkManager.GetDataLink(file);

            //assert
            Assert.IsNotNull(dataLink);
        }
Example #3
0
        private IRemoteDataServer CreateRemoteConnection(ConnectionModel connectionModel)
        {
            var securePassword = _passwordService.CreateSecurePassword(connectionModel.Password);

            return(DataLinkManager.GetRemoteDataServer(
                       connectionModel.ServerName,
                       connectionModel.RemotePort,
                       connectionModel.Binding,
                       connectionModel.UserName,
                       securePassword));
        }
        /// <summary>
        /// Method for connecting to Blaise data sets.
        /// </summary>
        /// /// <param name="hostname">The name of the hostname.</param>
        /// <param name="instrumentName">The name of the instrument.</param>
        /// <param name="serverPark">The name of the server park.</param>
        /// <returns> IDataLink4 object for the connected server park.</returns>
        public static IDataLink4 GetDataLink(string hostname, string instrumentName, string serverPark)
        {
            // Get authenication details from the app.config file.
            // For now we assume all Blaise servers will have the same authenication details.
            string userName = ConfigurationManager.AppSettings["BlaiseServerUserName"];
            string password = ConfigurationManager.AppSettings["BlaiseServerPassword"];
            string binding  = ConfigurationManager.AppSettings["BlaiseServerBinding"];
            int    port     = 8031;

            // Get the GIID of the instrument.
            Guid instrumentID = Guid.NewGuid();

            try
            {
                // Connect to the Blaise Server Manager.
                IConnectedServer serManConn = ServerManager.ConnectToServer(hostname, port, userName, GetPassword(password), binding);

                // Loop through the surveys installed on the server to find the GUID of the survey we are working on.
                bool foundSurvey = false;
                foreach (ISurvey survey in serManConn.GetServerPark(serverPark).Surveys)
                {
                    if (survey.Name == instrumentName)
                    {
                        instrumentID = survey.InstrumentID;
                        foundSurvey  = true;
                    }
                }
                if (foundSurvey == false)
                {
                    log.Error("Survey " + instrumentName + " not found on " + serverPark + "@" + hostname + ".");
                }

                // Connect to the data.
                IRemoteDataServer dataLinkConn = DataLinkManager.GetRemoteDataServer(hostname, 8033, binding, userName, GetPassword(password));

                return(dataLinkConn.GetDataLink(instrumentID, serverPark));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(null);
            }
        }
        /// <summary>
        /// Method for consuming and processing messages on the RabbitMQ queue.
        /// </summary>
        public void ConsumeMessage()
        {
            // Objects for working with Blaise data sets.
            IDataLink4 dl_source    = null;
            IDatamodel dm_source    = null;
            IDataLink4 dl_dest_sql  = null;
            IDataLink  dl_dest_file = null;

            // Functionality to be performed when a message is received. (digestion)
            consumer.Received += (model, ea) =>
            {
                // Extract the message and encode it.
                var body    = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                log.Info("Message received - " + message);

                MessageData data = null;
                try
                {
                    // Take the serialized JSON string and deserialize it into a MessageData object.
                    data = new JavaScriptSerializer().Deserialize <MessageData>(message);

                    // Connect to the Blaise source data set.
                    dl_source = GetDataLink(data.source_hostname, data.source_instrument, data.source_server_park);
                    dm_source = dl_source.Datamodel;

                    // Identify the primary key in the source data set.
                    var key = DataRecordManager.GetKey(dm_source, "PRIMARY");

                    // Assign the primary key the value of the 'serial_number' recieved from the RabbitMQ message.
                    key.Fields[0].DataValue.Assign(data.serial_number);

                    // Check if a case with this key exists in the source data set.
                    if (dl_source.KeyExists(key))
                    {
                        // Read in the case.
                        var case_record = dl_source.ReadRecord(key);

                        if (data.action == "delete")
                        {
                            dl_source.Delete(key);
                            SendStatus(MakeStatusJson(data, "Case Deleted"));
                        }
                        else
                        {
                            // Connect to the Blaise sql database destination data set  if provided in payload.
                            if ((data.dest_hostname != "" && data.dest_hostname != null) && (data.dest_server_park != "" && data.dest_server_park != null))
                            {
                                dl_dest_sql = GetDataLink(data.dest_hostname, data.dest_instrument, data.dest_server_park);

                                // Copy or move the case from the source to destination based on the 'action' received from the message.
                                switch (data.action)
                                {
                                // Copy action received.
                                case "copy":
                                    dl_dest_sql.Write(case_record);
                                    if (!dl_dest_sql.KeyExists(key))
                                    {
                                        SendStatus(MakeStatusJson(data, "Error"));
                                        log.Error(data.dest_instrument + " case " + data.serial_number + " NOT copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_server_park + "@" + data.dest_hostname + ".");
                                    }
                                    if (dl_dest_sql.KeyExists(key))
                                    {
                                        SendStatus(MakeStatusJson(data, "Case Copied"));
                                        log.Info(data.dest_instrument + " case " + data.serial_number + " copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_server_park + "@" + data.dest_hostname + ".");
                                    }
                                    break;

                                // Move action received.
                                case "move":
                                    dl_dest_sql.Write(case_record);
                                    dl_source.Delete(key);
                                    if (!dl_dest_sql.KeyExists(key))
                                    {
                                        SendStatus(MakeStatusJson(data, "Error"));
                                        log.Error(data.dest_instrument + " case " + data.serial_number + " NOT moved from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_server_park + "@" + data.dest_hostname + ".");
                                    }
                                    if ((dl_dest_sql.KeyExists(key)) && (dl_source.KeyExists(key)))
                                    {
                                        SendStatus(MakeStatusJson(data, "Warn"));
                                        log.Warn(data.dest_instrument + " case " + data.serial_number + " copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_server_park + "@" + data.dest_hostname + " but also still exists in " + data.source_server_park + "@" + data.source_hostname + ".");
                                    }
                                    if ((dl_dest_sql.KeyExists(key)) && (!dl_source.KeyExists(key)))
                                    {
                                        SendStatus(MakeStatusJson(data, "Case Moved"));
                                        log.Info(data.dest_instrument + " case " + data.serial_number + " moved from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_server_park + "@" + data.dest_hostname + ".");
                                    }
                                    break;

                                // Invalid action received.
                                default:
                                    SendStatus(MakeStatusJson(data, "Invalid Action"));
                                    log.Error("Invalid action requested - " + data.action);
                                    break;
                                }
                            }

                            // Connect to the Blaise file database destination data set if provided in payload.
                            if (data.dest_filepath != "" && data.dest_filepath != null)
                            {
                                // Check destination file database exists, and if not create it.
                                if (!File.Exists(data.dest_filepath + "\\" + data.dest_instrument + ".bdbx"))
                                {
                                    // Get source BMI and BDI to setup new file destination data set.
                                    string sourceBMI = GetSourceBMI(data.source_hostname, data.source_server_park, data.source_instrument);
                                    string sourceBDI = GetSourceBDI(data.source_hostname, data.source_server_park, data.source_instrument);

                                    // Create source directory from destination file path recieved in payload.
                                    Directory.CreateDirectory(data.dest_filepath);

                                    // Copy BMI from source to destination file path recieved in payload.
                                    File.Copy(sourceBMI, data.dest_filepath + "\\" + data.dest_instrument + ".bmix", true);

                                    // Create destination file data set.
                                    IDataInterface di = DataInterfaceManager.GetDataInterface();
                                    di.ConnectionInfo.DataSourceType   = DataSourceType.Blaise;
                                    di.ConnectionInfo.DataProviderType = DataProviderType.BlaiseDataProviderForDotNET;
                                    di.DataPartitionType = DataPartitionType.Stream;
                                    IBlaiseConnectionStringBuilder csb = DataInterfaceManager.GetBlaiseConnectionStringBuilder();
                                    csb.DataSource = data.dest_filepath + "\\" + data.dest_instrument + ".bdbx";
                                    di.ConnectionInfo.SetConnectionString(csb.ConnectionString);
                                    di.DatamodelFileName = data.dest_filepath + "\\" + data.dest_instrument + ".bmix";
                                    di.FileName          = data.dest_filepath + "\\" + data.dest_instrument + ".bdix";
                                    di.CreateTableDefinitions();
                                    di.CreateDatabaseObjects(null, true);
                                    di.SaveToFile(true);
                                }

                                // Connect to the Blaise file database destination data set.
                                dl_dest_file = DataLinkManager.GetDataLink(data.dest_filepath + "\\" + data.dest_instrument + ".bdix");

                                // Copy or move the case from the source to destination based on the 'action' received from the message.
                                switch (data.action)
                                {
                                // Copy action received.
                                case "copy":
                                    dl_dest_file.Write(case_record);
                                    if (dl_dest_file.ReadRecord(key) == null)
                                    {
                                        SendStatus(MakeStatusJson(data, "Error"));
                                        log.Error(data.dest_instrument + " case " + data.serial_number + " NOT copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_filepath + ".");
                                    }
                                    if (dl_dest_file.ReadRecord(key) != null)
                                    {
                                        SendStatus(MakeStatusJson(data, "Case Copied"));
                                        log.Info(data.dest_instrument + " case " + data.serial_number + " copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_filepath + ".");
                                    }
                                    break;

                                // Move action received.
                                case "move":
                                    dl_dest_file.Write(case_record);
                                    dl_source.Delete(key);
                                    if (dl_dest_file.ReadRecord(key) == null)
                                    {
                                        SendStatus(MakeStatusJson(data, "Error"));
                                        log.Error(data.dest_instrument + " case " + data.serial_number + " NOT moved from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_filepath + ".");
                                    }
                                    if ((dl_dest_file.ReadRecord(key) != null) && (dl_source.KeyExists(key)))
                                    {
                                        SendStatus(MakeStatusJson(data, "Warn"));
                                        log.Warn(data.dest_instrument + " case " + data.serial_number + " copied from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_filepath + " but also still exists in " + data.source_server_park + "@" + data.source_hostname + ".");
                                    }
                                    if ((dl_dest_file.ReadRecord(key) != null) && (!dl_source.KeyExists(key)))
                                    {
                                        SendStatus(MakeStatusJson(data, "Case Moved"));
                                        log.Info(data.dest_instrument + " case " + data.serial_number + " moved from " + data.source_server_park + "@" + data.source_hostname + " to " + data.dest_filepath + ".");
                                    }
                                    break;

                                // Invalid action received.
                                default:
                                    SendStatus(MakeStatusJson(data, "Invalid Action"));
                                    log.Error("Invalid action requested - " + data.action);
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        SendStatus(MakeStatusJson(data, "Case NOT Found"));
                        log.Error("Case " + data.serial_number.ToString() + " doesn't exist in source database.");
                    }
                }
                catch (Exception e)
                {
                    SendStatus(MakeStatusJson(data, "Error"));
                    log.Error(e);
                }
                // Remove from queue when done processing
                channel.BasicAck(ea.DeliveryTag, false);
            };

            // Consume and process any messages already held on the queue.
            string queueName = ConfigurationManager.AppSettings["HandlerQueueName"];

            channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
        }
Example #6
0
        public void SetDataLink() // This method can have any name
        {
            // Put your command code here
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //获取目录表格的容量
            int NumberPerPage = 1;
            PromptIntegerOptions GetNumberOption = new PromptIntegerOptions("\n输入每张表格的最大容量");

            GetNumberOption.AllowNegative = false;
            GetNumberOption.AllowZero     = false;
            PromptIntegerResult GetNumberResult = ed.GetInteger(GetNumberOption);

            if (GetNumberResult.Status == PromptStatus.OK)
            {
                NumberPerPage = GetNumberResult.Value;
            }
            else
            {
                return;
            }
            //获取图纸目录数据文件
            string DataFile = "";
            PromptOpenFileOptions fileoption = new PromptOpenFileOptions("\n输入链接数据文件路径");

            fileoption.InitialDirectory = System.IO.Path.GetDirectoryName(db.Filename);
            fileoption.Filter           = "Excel Documents (*.xlsx) |*.xlsx";
            PromptFileNameResult DataFileResult = ed.GetFileNameForOpen(fileoption);

            if (DataFileResult.Status == PromptStatus.OK)
            {
                DataFile = DataFileResult.StringResult;
            }
            else
            {
                return;
            }
            //获取数据表范围信息
            string       SheetName    = "图纸目录";
            string       StartCol     = "A";
            string       EndCol       = "E";
            int          StartRow     = 2;
            PromptResult GetSheetName = ed.GetString("\n输入链接数据表名称");

            if (GetSheetName.Status == PromptStatus.OK)
            {
                SheetName = GetSheetName.StringResult;
            }
            else
            {
                return;
            }
            PromptResult GetStartCol = ed.GetString("\n输入数据起始列");

            if (GetStartCol.Status == PromptStatus.OK)
            {
                StartCol = GetStartCol.StringResult;
            }
            else
            {
                return;
            }
            PromptResult GetEndCol = ed.GetString("\n输入数据结束列");

            if (GetEndCol.Status == PromptStatus.OK)
            {
                EndCol = GetEndCol.StringResult;
            }
            else
            {
                return;
            }
            PromptIntegerResult GetStartRow = ed.GetInteger("\n输入数据起始行");

            if (GetStartRow.Status == PromptStatus.OK)
            {
                StartRow = GetStartRow.Value;
            }
            else
            {
                return;
            }
            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                DBDictionary Layouts    = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                ArrayList    Layoutlist = new ArrayList();
                foreach (DBDictionaryEntry item in Layouts)
                {
                    if (item.Key != "Model")
                    {
                        Layoutlist.Add(item.Key);
                    }
                }
                //int NumberOfList = Layoutlist.Count;
                ArrayList TableIDs = new ArrayList();
                foreach (string name in Layoutlist)
                {
                    TypedValue[] Filter = new TypedValue[]
                    {
                        new TypedValue((int)DxfCode.Operator, "<and"),
                        new TypedValue((int)DxfCode.LayoutName, name),
                        new TypedValue((int)DxfCode.Start, "ACAD_TABLE"),
                        new TypedValue((int)DxfCode.Operator, "and>"),
                    };
                    PromptSelectionResult selresult = ed.SelectAll(new SelectionFilter(Filter));
                    if (selresult.Status == PromptStatus.OK)
                    {
                        ObjectId[] ids = selresult.Value.GetObjectIds();
                        TableIDs.Add(ids[0]);
                    }
                }
                int NumberOfTables = TableIDs.Count;

                /*
                 * ed.WriteMessage("\nLayout:{0}", Layoutlist.Count);
                 * foreach(string name in Layoutlist)
                 * {
                 *  ed.WriteMessage("\nLayoutname:{0}", name);
                 * }
                 * ed.WriteMessage("\nTables:{0}", TableIDs.Count);
                 */
                DataLinkManager dlm = db.DataLinkManager;
                try
                {
                    for (int i = 0; i < NumberOfTables; i++)
                    {
                        Autodesk.AutoCAD.DatabaseServices.DataLink dl = new Autodesk.AutoCAD.DatabaseServices.DataLink();
                        dl.DataAdapterId = "AcExcel";
                        dl.Name          = SheetName + (i + 1).ToString();
                        dl.Description   = SheetName + "数据链接" + (i + 1).ToString();
                        string location = string.Format("!{0}!{1}{2}:{3}{4}", SheetName, StartCol, (StartRow + i * NumberPerPage), EndCol, ((1 + i) * NumberPerPage) + StartRow - 1);
                        dl.ConnectionString = DataFile + location;
                        dl.DataLinkOption   = DataLinkOption.PersistCache;
                        dl.UpdateOption    |= (int)UpdateOption.AllowSourceUpdate | (int)UpdateOption.SkipFormat;
                        ObjectId dlId = dlm.AddDataLink(dl);
                        ed.WriteMessage("\n链接字符串:{0}", dl.ConnectionString);
                        Trans.AddNewlyCreatedDBObject(dl, true);
                        Table tb = (Table)Trans.GetObject((ObjectId)TableIDs[i], OpenMode.ForWrite);
                        tb.Cells[1, 0].DataLink = dlId;
                        tb.GenerateLayout();
                    }
                    Trans.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception Ex)
                {
                    ed.WriteMessage("\n出错啦!" + Ex.ToString());
                }
                finally
                {
                    Trans.Dispose();
                }
            }
        }
        static public void CADTablebyExcelSheet()
        {
            const string dlName = "从Excel导入表格";

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // 文件打开窗口
            OpenFileDialog ofd =
                new OpenFileDialog(
                    "选择需要链接的Excel表格文档!",
                    null,
                    "xls;xlsx",
                    "Excel链接到CAD",
                    OpenFileDialog.OpenFileDialogFlags.DoNotTransferRemoteFiles
                    );

            System.Windows.Forms.DialogResult dr = ofd.ShowDialog();

            if (dr != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            ed.WriteMessage("\n选择到的文件为\"{0}\".", ofd.Filename);

            PromptPointResult ppr = ed.GetPoint("\n请选择表格插入点: ");

            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }

            // 数据链接管理对象
            DataLinkManager dlm = db.DataLinkManager;

            // 判断数据链接是否已经存在 如果存在移除
            ObjectId dlId = dlm.GetDataLink(dlName);

            if (dlId != ObjectId.Null)
            {
                dlm.RemoveDataLink(dlId);
            }

            // 创建并添加新的数据链接

            DataLink dl = new DataLink();

            dl.DataAdapterId    = "AcExcel";
            dl.Name             = dlName;
            dl.Description      = "Excel fun with Through the Interface";
            dl.ConnectionString = ofd.Filename;
            dl.UpdateOption    |= (int)UpdateOption.AllowSourceUpdate;

            dlId = dlm.AddDataLink(dl);

            // 开启事务处理
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                trans.AddNewlyCreatedDBObject(dl, true);

                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;


                // 新建表格对象
                Table tb = new Table();
                tb.TableStyle = db.Tablestyle;
                tb.Position   = ppr.Value;
                tb.SetDataLink(0, 0, dlId, true);
                tb.GenerateLayout();

                BlockTableRecord btr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                btr.AppendEntity(tb);
                trans.AddNewlyCreatedDBObject(tb, true);
                trans.Commit();
            }

            // 强制恢复显示表格
            ed.Regen();
        }