后台上传BIM模型-模型添加-格式转换-导入模型数据

这一块是上传模块~

 public string   UploadFile()
        {
            Om_model a = new Om_model();
            string result = string.Empty;
                try
                 {
                     string uploadPath = HttpContext.Current.Server.MapPath("~/UpFile/Entire/");
                     HttpRequest request = System.Web.HttpContext.Current.Request;
                     HttpFileCollection fileCollection = request.Files;
                     // 判断是否有文件
                     if (fileCollection.Count > 0)
                     {
                         // 获取文件
                         HttpPostedFile httpPostedFile = fileCollection[0];
                         string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
                        string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
                         string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
                    // 如果目录不存在则要先创建
                    if (!Directory.Exists(uploadPath))
                         {
                             Directory.CreateDirectory(uploadPath);
                         }
                         // 保存新的文件
                         while (File.Exists(filePath))
                         {
                             fileName = Guid.NewGuid().ToString() + fileExtension;
                             filePath = uploadPath + fileName;
                         }
                         httpPostedFile.SaveAs(filePath);
             a.fModel_EntireifcID = uploadPath + httpPostedFile.FileName;
                    //o.fModel_ShellIFCID = "~/UpFile/" + httpPostedFile.FileName;
                    result = "上传成功";
                    }
                 }
                 catch (Exception)
                 {
                     result = "上传失败";
                 }
            return result;
        }  

这一块是模型的格式转化,由ifc转换成wexBIM格式。显示GIS模型需要转化gltf格式的模型,添加到数据中

  #region     模型添加
        public int insert(Om_model a)
        {
            parentFacilityId = a.fModel_ParentFacilityID;
            parentModelName = a.fModel_Name;
            parentModelId = a.guid;
            string uploadPath = HttpContext.Current.Server.MapPath("~/UpFile/Entire/");
            string uploadPath1 = HttpContext.Current.Server.MapPath("~/UpFile/Shell/");
            a.fModel_EntireifcID = uploadPath + a.fModel_Path;
            a.fModel_ShellIFCID = uploadPath1 + a.fModel_Path1;
            // var IfcFilePath = @" F:/work/che/WDAL/Maint/UpFile/Entire/" + a.fModel_Path;
--格式转换
            if (a.fModel_Path!=null)
            {
                using (var model = IfcStore.Open(a.fModel_EntireifcID))
                {
                    var project = model.Instances.FirstOrDefault();

                    EntityToJson(project, true);
                }
                using (var model = IfcStore.Open(a.fModel_EntireifcID))
                {
                    // upath = GetSaveName(outDirectoryName, fileNameWithoutExtension, ".wexBIM");
                    var context = new Xbim3DModelContext(model);
                    context.CreateContext();
                    var extension = Path.GetExtension(a.fModel_Path);
                    var wexBimFilename = Path.ChangeExtension(extension, "wexBIM");
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(a.fModel_Path);
                    a.fModel_Path = fileNameWithoutExtension + wexBimFilename;
                    var webpath = HttpContext.Current.Server.MapPath("~/Files/Emage/");
                    a.fModel_EntireifcID = Path.GetFullPath(webpath + fileNameWithoutExtension + wexBimFilename);
                    using (var wexBiMfile = File.Create(a.fModel_EntireifcID))
                    {
                        using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile))
                        {
                            model.SaveAsWexBim(wexBimBinaryWriter);
                            wexBimBinaryWriter.Close();
                        }
                        wexBiMfile.Close();
                    }
                }
            }
--格式转换
            if (a.fModel_Path1!=null)
            {
                    var extension = Path.GetExtension(a.fModel_Path1);
                    var wexBimFilename = Path.ChangeExtension(extension, "gltf");
                    var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(a.fModel_Path1);
                    var webpath = HttpContext.Current.Server.MapPath("~/Files/Smage/");
           --用 doc操作命令进行文件格式转换
                    //启动命令行
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.FileName = "cmd.exe";
                    p.StartInfo.UseShellExecute = false; //不使用操作系统shell启动
                    p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                    p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                    p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                    p.StartInfo.CreateNoWindow = false;//不显示程序窗口
                    p.Start();//启动程序
                  string timestamp = DateTime.Now.ToString("s");
                    timestamp = System.Text.RegularExpressions.Regex.Replace(timestamp, "[/:/-]", "");
                    p.StandardInput.WriteLine(@"f:");
                    p.StandardInput.WriteLine(@" cd  f:\work\che\Maint\UpFile\Shell");
                p.StandardInput.WriteLine("ren\t" + fileNameWithoutExtension.ToString() + ".ifc" + "\t" + timestamp + ".ifc");
                p.StandardInput.WriteLine("ren\t" + fileNameWithoutExtension.ToString() + ".ifc" + "\t" + timestamp + ".ifc");
                p.StandardInput.WriteLine("IfcConvert\t" + timestamp + ".ifc");
                p.StandardInput.WriteLine(@"cd   F:\work\che\Maint\UpFile\Shell\node-v12.13.1-win-x64\node_modules\obj2gltf\bin");
                p.StandardInput.WriteLine(@"node   obj2gltf.js   -i    F:\work\che\Maint\UpFile\Shell\" + timestamp + ".obj \t" + @"  -o   F:\work\che\Maint\Files\Smage\" + timestamp + ".gltf");
                p.StandardInput.WriteLine("exit"); //需要有这句,不然程序会挂机
                string res= p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                    p.Close();

                    a.fModel_ShellIFCID = Path.GetFullPath(webpath + timestamp + ".gltf");
                    a.fModel_Path1 = timestamp + ".gltf";
            }
            string sql = string.Format("insert into Om_model(fModel_Type,fModel_Name,fModel_Uploader,fModel_UploadTime,fModel_ParentFacilityID,fArea_Name,fModel_Longitude,fModel_Latitude,fModel_Level,fModel_Heading,fModel_Pitch,fModel_Roll,fModel_Remark,fModel_ShellIFCID,fModel_EntireifcID,fModel_Path,fModel_Path1) values({0},'{1}','{2}','{3}',{4},'{5}',{6},{7},{8},{9},{10},{11},'{12}','{13}','{14}','{15}','{16}')", a.fModel_Type, a.fModel_Name, a.fModel_Uploader, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), a.fModel_ParentFacilityID, a.fArea_Name, a.fModel_Longitude, a.fModel_Latitude, a.fModel_Level, a.fModel_Heading, a.fModel_Pitch, a.fModel_Roll, a.fModel_Remark, a.fModel_ShellIFCID, a.fModel_EntireifcID, a.fModel_Path, a.fModel_Path1);
            return Dapperhelper.dapper.Execute(sql);
        }
   

这一块是为了过滤一些没必要的模型数据。

 if (entity is IIfcColumn ||
entity is IIfcBeam ||
entity is IIfcSlab ||
entity is IIfcPipeFitting ||
entity is IIfcFlowFitting ||
entity is IIfcFlowSegment ||
entity is IIfcCurtainWall ||
entity is IIfcMember ||
entity is IIfcPlate ||
entity is IIfcRailing ||
entity is IIfcStair ||
entity is IIfcStairFlight ||
entity is IIfcWall ||
entity is IIfcWallStandardCase ||
entity is IIfcRailing ||
entity is IIfcRailing ||
entity is IIfcOpeningElement)

导入模型的数据


模型导入数据类
        private dynamic EntityToJson(IPersistEntity entity, bool iterate = false, bool check = false, int parentId = 0, string parentName = "", double elevation = 0)
        {
            dynamic json = new ExpandoObject();
            //13 parent object id
            json.parentObjId = parentId;

            //14 parent object name
            json.parentObjName = parentName;

            if (entity is IIfcRoot)
            {
                SetName(json, ((IIfcRoot)entity).Name);

                //19 elevation
                if (entity is IIfcBuildingStorey)
                {
                    json.elevation = double.Parse(((IIfcBuildingStorey)entity).Elevation.Value.ToString());
                }
                else
                {
                    json.elevation = elevation;
                }

            }

            if ((entity is IIfcBuildingStorey) || (entity is IIfcSpace) || (entity is IIfcDistributionElement))
            {
                if (true)
                {
                    //type Classification
                    IIfcValue category = GetProperty((IIfcProduct)entity, "CATEGORY");
                    json.classificationCode = "not defined";
                    json.classificationName = "not defined";
                    if (category != null)
                    {
                        string classification = category.ToString();
                        int commaIndex = classification.IndexOf(':');
                        if (commaIndex > 0)
                        {
                            json.classificationCode = classification.Substring(0, commaIndex);
                            json.classificationName = classification.Substring(commaIndex + 2, classification.Length - commaIndex - 2);
                        }
                    }
                    //02 IFCGUID
                    json.id = entity.EntityLabel;

                    //03 name
                    var name = GetProperty((IIfcProduct)entity, "NAME");
                    if (name != null)
                    {
                        json.name = name.Value;
                    }
                    else
                    {
                        name = ((IIfcProduct)entity).Name;
                        json.name = name.Value;
                    }

                    //04 type
                    string nameString = name.ToString();
                    int markIndex = nameString.IndexOf(":");
                    //若命名不完整
                    if (markIndex == -1)
                    {
                        //房间、楼层用原Ifc标签
                        if (entity is IIfcSpace || entity is IIfcBuildingStorey)
                            json.type = entity.GetType().Name;
                        else
                        {
                            var type = GetProperty((IIfcProduct)entity, "CATEGORY");
                            //其它的,若没有COBie.CATEGORY,用Ifc标签
                            if (type == null)
                            {
                                json.type = entity.GetType().Name;
                            }
                            //若有,则和Name一致
                            else
                            {
                                json.type = json.name;
                            }
                        }
                    }
                    else
                    {
                        json.type = nameString.Substring(0, markIndex + 1 + nameString.Substring(markIndex + 1).IndexOf(":"));
                    }

                    if (entity is IIfcDistributionElement)
                    {
                        //05 specification
                        var spec = GetProperty((IIfcProduct)entity, "DESCRIPTION");
                        json.spec = spec != null ? spec.Value : "n/a";

                        //06 manufacturer
                        var manu = GetProperty((IIfcProduct)entity, "MANUFACTURER");
                        json.manu = manu != null ? (manu.ToString().Length > 0 ? manu.Value : manus[GetRandom(0, 3)]) : manus[GetRandom(0, 3)];

                        //07 asembly date
                        var asblyDate = GetProperty((IIfcProduct)entity, "INSTALLATIONDATE");
                        DateTime outDateTime = new DateTime();
                        if (asblyDate != null)
                        {
                            json.asblyDate = DateTime.TryParse(asblyDate.Value.ToString(), out outDateTime) ? asblyDate.Value.ToString() : DateTime.Now.ToShortDateString().ToString();
                        }
                        else
                            json.asblyDate = DateTime.Now.ToShortDateString().ToString();

                        //08 expire date
                        var expLife = GetProperty((IIfcProduct)entity, "EXPECTEDLIFE");
                        DateTime datetime = DateTime.Parse(json.asblyDate);
                        int outInt = new int();
                        if (expLife != null)
                        {
                            json.expDate = int.TryParse(expLife.Value.ToString(), out outInt) ? datetime.AddYears(Convert.ToInt32(expLife.Value)).ToShortDateString().ToString() : datetime.AddYears(40).ToShortDateString().ToString();
                        }
                        else
                            json.expDate = datetime.AddYears(40).ToShortDateString().ToString();

                        //09 cycle
                        var cycle = GetProperty((IIfcProduct)entity, "DURATIONUNIT");
                        json.cycle = 30;

                        //10 cost
                        var cost = GetProperty((IIfcProduct)entity, "REPLACEMENTCOST");
                        float outCost = new float();
                        if (cost != null)
                        {
                            json.cost = float.TryParse(cost.Value.ToString(), out outCost) ? cost.Value : GetRandom(0, 2000);
                        }
                        else
                            json.cost = GetRandom(0, 2000);

                        //15 RPN
                        json.RPN = 0;

                        //18 Space
                        var space = GetSpace((IIfcDistributionElement)entity);
                        json.space = space?.Name.Value;



                        //19 System
                        var system = GetSystem((IIfcProduct)entity);
                        json.systemName = system?.Name;
                      //  json.systemIFCGUID = system?.EntityLabel;

                        //20 Floor
                        var floor = GetFloor((IIfcDistributionElement)entity);
                        json.floor = floor?.Name.Value;
                        json.floorID = floor?.EntityLabel;

                        insertEquipIntoObjTable(json);
                        insertType(json);

                    }
                    else if (entity is IIfcSpace)
                    {
                        var floor = ((IIfcSpace)entity).Decomposes.Select(r => r.RelatingObject).OfType().FirstOrDefault();
                        json.floor = floor?.Name;
                        json.floorID = floor?.EntityLabel;
                        var space =((IIfcSpace)entity).Decomposes.Select(r => r.RelatingObject).OfType().FirstOrDefault(); ;
                        json.space = space?.Name;
                        insertSpaceIntoObjTable(json);
                    }
                    else
                        insertFloorIntoObjTable(json);

                    count++;
                }
            }

            if (iterate)
            {
                if (entity is IIfcObjectDefinition)
                {
                    var decomposedBy = new List();
                    foreach (var r in ((IIfcObjectDefinition)entity).IsDecomposedBy)
                    {
                        foreach (var e in r.RelatedObjects)
                        {
                            decomposedBy.Add(EntityToJson(e, iterate, check, json.parentObjId, json.name, json.elevation));
                        }
                    }
                    if (decomposedBy.Any())
                    {
                        json.decomposedBy = decomposedBy;
                    }
                }
                if (entity is IIfcSpatialStructureElement)
                {
                    var contains = new List();
                    foreach (var r in ((IIfcSpatialStructureElement)entity).ContainsElements)
                    {
                        foreach (var e in r.RelatedElements)
                        {
                            contains.Add(EntityToJson(e, iterate, check, json.parentObjId, json.name, json.elevation));
                        }
                    }
                    if (contains.Any())
                    {
                        json.contains = contains;
                    }
                }
            }
            return json;
        }
        private int  insertFloorIntoObjTable(dynamic json)
        {
            string _sql = string.Format("insert into OM_Object(version,fObject_IFguid,fObject_Name,fObject_Type,fObject_ParentModelId,fObject_ParentFacilityId,fObject_ParentObjId,fObject_ParentObjName,fArea_Name,fObject_ParentModelName,fObject_Elevation,fObject_FacilityType) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')",
                0,
                json.id,
                json.name,
                json.type,
                parentModelId,
                parentFacilityId,
                json.parentObjId,
                json.parentObjName,
                parentFacilityName,
                parentModelName,
                Math.Round(json.elevation, 2),
                "建筑设施"
                );
            _sql.Replace("'", " ");
            return SqlHelper.ExecuteNonQuery(SqlHelper.Conn, CommandType.Text, _sql);
        }

        private int  insertSpaceIntoObjTable(dynamic json)
        {
            string _sql = string.Format("insert into OM_Object(version,fObject_IFguid,fObject_Name,fObject_Type,fObject_ParentModelId,fObject_ParentFacilityId,fObject_ParentObjId,fObject_ParentObjName,fArea_Name,fObject_ParentModelName,fObject_Elevation,fObject_FacilityType,fObject_FloorName,fObject_FloorIFguid,fObject_Space) values('{0}','{1}','{2}','{3}',{4},{5},{6},'{7}','{8}','{9}',{10},'{11}','{12}',{13},'{14}')",
                0,
                json.id,
                json.name,
                json.type,
                parentModelId,
                parentFacilityId,
                json.parentObjId,
                json.parentObjName,
             parentFacilityName,
             parentModelName,
                Math.Round(json.elevation, 2),
                "建筑设施",
                json.floor,
                json.floorID,
               json.space
                );
            _sql.Replace("'", " ");
            return SqlHelper.ExecuteNonQuery(SqlHelper.Conn, CommandType.Text, _sql);
        }

        private int insertEquipIntoObjTable(dynamic json)
        {
            string _sql = string.Format("insert into OM_Object(version,fObject_IFguid,fObject_Name,fObject_Type,fObject_Spec,fObject_Manufactor,fObject_AsblyDate,fObject_ExpDate,fObject_Cycle,fObject_Cost,fObject_ParentModelId,fObject_ParentFacilityId,fObject_ParentObjId,fObject_ParentObjName,fObject_RPN,fArea_Name,fObject_ParentModelName,fObject_Space   ,fObject_Elevation,fObject_FacilityType,fObject_UpperSysName,fObject_FloorName,fObject_FloorIFguid) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}')",
               0,
               json.id,
               json.name,
               json.type,
               json.spec,
               json.manu,
               json.asblyDate,
               json.expDate,
               json.cycle,
               json.cost,
               parentModelId,
               parentFacilityId,
               json.parentObjId,
               json.parentObjName,
               json.RPN,
               parentFacilityName,
              parentModelName,
                json.space,
               Math.Round(json.elevation, 2),
               "建筑设施",
               json.systemName,
               json.floor,
               json.floorID
               );
            _sql.Replace("'", " ");
       return  SqlHelper.ExecuteNonQuery(SqlHelper.Conn, CommandType.Text, _sql);
          
        }
        public int insertType(dynamic json)
        {
            //查询对象类型表中是否有相同记录,如没有则添加
            string typeExistSql = "select * from OM_ObjectType where fObjectType_Name = '" + json.type + "'";
            //   DataSet reader = SqlHelper.GetDataSet(SqlHelper.Conn, CommandType.Text, string.Format(typeExistSql));
            //   if (reader.Tables.Count>0 )
            SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.Conn, CommandType.Text, string.Format(typeExistSql));
            if (!reader.HasRows)
            {
                //string typefID = System.Text.RegularExpressions.Regex.Replace(System.Guid.NewGuid().ToString().ToUpper(), "[-]", "");
                Om_objecttype o = new Om_objecttype();
                string typeInsertSql = string.Format("insert into OM_ObjectType (guid,version,fObjectType_Name,fObjectType_ClassificationCode,fObjectType_Classification,fObjectType_IsFSI,fObjectType_hasFModels,fObjectType_Error) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')",
                  o.guid,   
                0,
                json.type,
                json.classificationCode,
                json.classificationName,
                0,
                0,
                0
                );
                typeInsertSql.Replace("'", " ");
                return SqlHelper.ExecuteNonQuery(SqlHelper.Conn, CommandType.Text, typeInsertSql);
            }
            else
            {
               return  0;
            }

        }
        private int GetRandom(int supValue, int UpValue)
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            int iSeed = BitConverter.ToInt32(buffer, 0);
            Random random = new Random(iSeed);
            return random.Next(supValue, UpValue);
        }

        private void SetName(dynamic json, IfcLabel? name)
        {
            if (name != null)
            {
                json.name = name.Value.Value;
            }
        }
        private IIfcValue GetProperty(IIfcProduct product, string name)
        {
            return
            //get all relations which can define property and quantity sets
            product.IsDefinedBy

            //Search across all property and quantity sets. You might also want to search in a specific property set
            .SelectMany(r => r.RelatingPropertyDefinition.PropertySetDefinitions)

            //Only consider property sets in this case.
            .OfType()

            //Get all properties from all property sets
            .SelectMany(pset => pset.HasProperties)

            //lets only consider single value properties. There are also enumerated properties,
            //table properties, reference properties, complex properties and other
            .OfType()

            //lets make the name comparison more fuzzy. This might not be the best practise
            .Where(p =>
            string.Equals(p.Name, name, System.StringComparison.OrdinalIgnoreCase) ||
            p.Name.ToString().ToLower().Contains(name.ToLower()))

            //only take the first. In reality you should handle this more carefully.
            .FirstOrDefault()?.NominalValue;
        }
        private IIfcSpace GetSpace(IIfcDistributionElement element)
        {
            return
            //get all relations which can define property and quantity sets
            element.ContainedInStructure?

            .Select(r => r.RelatingStructure)

            .OfType()

            .FirstOrDefault();
        }
        //测试20190606
        private IIfcGroup GetSystem(IIfcProduct element)
        {
            return

            element.HasAssignments?

            .OfType()

            .Select(r => r.RelatingGroup)

            .FirstOrDefault();
        }
        private IIfcBuildingStorey GetFloor(IIfcDistributionElement product)
        {
            var space = GetSpace(product);

            if (space == null)
            {
                return product.ContainedInStructure?.Select(r => r.RelatingStructure).OfType().FirstOrDefault();
            }
            else
            {
                return
                //get all relations which can define property and quantity sets
                space

                .Decomposes

                .Select(r => r.RelatingObject)

                .OfType()

                .FirstOrDefault();
            }


        }

你可能感兴趣的:(c#,BIM)