コード例 #1
0
        public Step7ProjectV11(string projectfile, CultureInfo culture = null)
        {
            if (culture == null)
                Culture = CultureInfo.CurrentCulture;
            else
                Culture = culture;

            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += currentDomain_AssemblyResolve;

            ProjectFile = projectfile;

            if (ProjectFile.ToLower().EndsWith("zip") || ProjectFile.ToLower().EndsWith("zap13"))
            {
                ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".ap11");
                if (string.IsNullOrEmpty(ProjectFile))               
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".ap12");
                if (string.IsNullOrEmpty(ProjectFile))
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".ap13");
                if (string.IsNullOrEmpty(ProjectFile))
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".al11");
                if (string.IsNullOrEmpty(ProjectFile))
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".al12");
                if (string.IsNullOrEmpty(ProjectFile))
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".al13");

                if (string.IsNullOrEmpty(projectfile))
                    throw new Exception("Zip-File contains no valid TIA Project !");
                this._ziphelper = new ZipHelper(projectfile);
            }

           
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(_ziphelper.GetReadStream(projectfile));

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("x", "http://www.siemens.com/2007/07/Automation/CommonServices/DataInfoValueData");

                var nd = xmlDoc.SelectSingleNode("x:Data", nsmgr);
                this.ProjectName = nd.Attributes["Name"].Value;
            }
            catch (Exception) 
            { }

            DataFile = Path.GetDirectoryName(projectfile) + "\\System\\PEData.plf";
            ProjectFolder = projectfile.Substring(0, projectfile.LastIndexOf(Path.DirectorySeparatorChar)) + Path.DirectorySeparatorChar;

            //BinaryParseTIAFile();
            //LoadProject();
            LoadViaOpennessDlls();

            currentDomain.AssemblyResolve -= currentDomain_AssemblyResolve;            
        }        
コード例 #2
0
 public static void ExtractZip(string zipFile, string dstDir)
 {
     Console.WriteLine("解压文件:{0}", zipFile);
     ZipHelper.UnzipFile(zipFile, dstDir);
 }
コード例 #3
0
        /// <summary>
        /// This Function Returens a Step7 Project Instance for every Project Folder in the Path.
        /// </summary>
        /// <param name="dirname"></param>
        /// <returns></returns>
        static public Project[] GetStep7ProjectsFromDirectory(string dirname)
        {
            List <Project> retVal = new List <Project>();

            try
            {
                string[] fls = System.IO.Directory.GetFiles(dirname, "*.s5d");
                foreach (var fl in fls)
                {
                    retVal.Add(new Step5Project(fl, false));
                }
            }
            catch (Exception)
            {
            }
            try
            {
                foreach (string subd in System.IO.Directory.GetDirectories(dirname))
                {
                    try
                    {
                        string[] fls = System.IO.Directory.GetFiles(subd, "*.s7p");
                        if (fls.Length > 0)
                        {
                            retVal.Add(new Step7ProjectV5(fls[0], false));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.s7l");
                        if (fls.Length > 0)
                        {
                            retVal.Add(new Step7ProjectV5(fls[0], false));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.ap11");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.ap12");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.ap13");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.ap14");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV14SP1ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.ap15");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV15ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.al11");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.al12");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.al13");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV13ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.al14");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV14SP1ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.al15");
                        if (fls.Length > 0)
                        {
                            retVal.Add(createV15ProjectInstance(fls[0]));
                        }

                        fls = System.IO.Directory.GetFiles(subd, "*.s5d");
                        if (fls.Length > 0)
                        {
                            retVal.Add(new Step5Project(fls[0], false));
                        }
                    }
                    catch (Exception)
                    { }
                }

                foreach (var ending in "*.zip;*.zap13".Split(';'))
                {
                    string[] zips = System.IO.Directory.GetFiles(dirname, ending);
                    foreach (string zip in zips)
                    {
                        string entr = ZipHelper.GetFirstZipEntryWithEnding(zip, ".s7p");
                        if (entr != null)
                        {
                            retVal.Add(new Step7ProjectV5(zip, false));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, ".s7l");
                        if (entr != null)
                        {
                            retVal.Add(new Step7ProjectV5(zip, false));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.ap11");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.ap12");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.ap13");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.ap14");
                        if (entr != null)
                        {
                            retVal.Add(createV14SP1ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.ap15");
                        if (entr != null)
                        {
                            retVal.Add(createV15ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.al11");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.al12");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.al13");
                        if (entr != null)
                        {
                            retVal.Add(createV13ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.al14");
                        if (entr != null)
                        {
                            retVal.Add(createV14SP1ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, "*.al15");
                        if (entr != null)
                        {
                            retVal.Add(createV15ProjectInstance(entr));
                        }

                        entr = ZipHelper.GetFirstZipEntryWithEnding(zip, ".s5d");
                        if (entr != null)
                        {
                            retVal.Add(new Step5Project(zip, false));
                        }
                    }
                }
            }
            catch (Exception)
            { }

            return(retVal.ToArray());
        }
コード例 #4
0
        public JsonResult GrantCarDerate(string vid, string qid, string sellerName, string derateName, int number)
        {
            try
            {
                if (number <= 0)
                {
                    throw new MyException("发放优免券数量不正确");
                }

                if (string.IsNullOrWhiteSpace(SystemDefaultConfig.SystemDomain))
                {
                    throw new MyException("获取系统域名失败");
                }
                ParkDerateQRcode qrCode = ParkDerateQRcodeServices.QueryByRecordId(qid);
                if (qrCode == null)
                {
                    throw new MyException("优免券规则不存在");
                }

                ParkDerate derate = ParkDerateServices.Query(qrCode.DerateID);
                if (derate == null)
                {
                    throw new MyException("获取优免规则失败");
                }

                if (derate.DerateType == DerateType.SpecialTimePeriodPayment)
                {
                    string     errorMsg = string.Empty;
                    ParkSeller seller   = ParkSellerServices.GetSeller(derate.SellerID, out errorMsg);
                    if (derate == null)
                    {
                        throw new MyException("获取优免规则失败");
                    }

                    decimal totalAmount = qrCode.DerateValue * number;
                    if ((seller.Creditline + seller.Balance) < totalAmount)
                    {
                        throw new MyException("商家余额不足");
                    }
                }

                BaseVillage village = VillageServices.QueryVillageByRecordId(vid);
                if (village == null)
                {
                    throw new MyException("获取小区信息失败");
                }

                string        folderName   = string.Format("{0}_{1}_{2}", sellerName, derateName, IdGenerator.Instance.GetId().ToString());
                List <string> carDerateIds = new List <string>();
                for (int i = 0; i < number; i++)
                {
                    string carDerateId = GuidGenerator.GetGuidString();
                    string content     = string.Format("{0}/QRCodeDerate/Index?vid={1}&qid={2}&did={3}&sign={4}", SystemDefaultConfig.SystemDomain, vid, qid, carDerateId, GetSignature(vid, qid, carDerateId));
                    string result      = QRCodeServices.GenerateQRCode(village.CPID, content, 430, carDerateId, folderName);
                    if (string.IsNullOrWhiteSpace(result))
                    {
                        throw new MyException("创建二维码失败");
                    }
                    carDerateIds.Add(carDerateId);
                }
                string filePath    = string.Format("/Uploads/{0}", folderName);
                string zipFilePath = string.Format("{0}/{1}_{2}.zip", filePath, sellerName, derateName);
                string mapPath     = Server.MapPath("~/");

                ZipHelper.ZipFiles(string.Format("{0}/{1}", mapPath, filePath), string.Format("{0}/{1}", mapPath, zipFilePath));
                if (carDerateIds.Count != number)
                {
                    throw new MyException("二维码数量与待创建的数量不匹配");
                }

                bool grantResult = ParkDerateQRcodeServices.GrantCarDerate(carDerateIds, zipFilePath, qid);
                if (!grantResult)
                {
                    throw new MyException("发放券失败");
                }

                return(Json(MyResult.Success("", zipFilePath)));
            }
            catch (MyException ex)
            {
                return(Json(MyResult.Error(ex.Message)));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptions(ex, "发放优免券失败");
                return(Json(MyResult.Error("发放优免券失败")));
            }
        }
コード例 #5
0
ファイル: TestController.cs プロジェクト: kingshhh/fxtcode
        //
        // GET: /Test/

        public ActionResult Index()
        {
            //获取正式数据文件根目录
            string basePath2 = CommonUtility.GetConfigSetting("upload_DataAcquisition");
            string folder2   = System.Web.Hosting.HostingEnvironment.MapPath(basePath2);
            var    path      = folder2 + "/fff664ab41fa4abb9d4d_1_4118.zip";

            ZipHelper.UnZipFile(folder2, path);

            //var p = _unitOfWork.ProjectRepository.Insert(new Project() { ProjectName = "测试" ,PurposeCode=0,CityID = 6,AreaID = 72});

            //_unitOfWork.AllotFlowRepository.Insert(new AllotFlow() { DatId = p.ProjectId ,CityId = 6,FxtCompanyId = 25,DatType = 0,StateCode = 0,CreateTime = DateTime.Now});
            //_unitOfWork.Commit();

            //var a = _unitOfWork.AllotFlowRepository.Get().FirstOrDefault();
            //Project p = a.Project;
            //int d = 1;


            //GeocodingResponse response = GeocodingManager.Search(new GeocodingRequest()
            //{
            //    ak = "264a5ba3e9065323d2a030af536c5d70",
            //    output = OutputType.json,
            //    pois = 0,
            //    location = "22.55932000000000,114.04508000000000"
            //});

            //BaiduAPI.NearRequest r = new BaiduAPI.NearRequest();
            //r.apikey = "264a5ba3e9065323d2a030af536c5d70";
            //r.keyWord = "学校";
            //r.location = new BaiduAPI.Location() { lat = 116.305145m, lng = 39.982368m };
            //r.tag = BaiduAPI.TagType.全部;
            //r.radius = 30;
            //r.cityName = "北京";
            //r.sort_rule = 0;
            //r.number = 10;
            //r.page = 1;
            //r.output = BaiduAPI.OutputType.json;
            //r.coord_type = BaiduAPI.CoordType.bd09ll;
            //r.out_coord_type = BaiduAPI.CoordType.bd09ll;
            //BaiduAPI.NearManager.Search(r);

            //BaiduAPI.PlaceRequest rq = new BaiduAPI.PlaceRequest();
            //rq.ak = "WjUg5aNHrFolqN5Utm0GFwVl";
            //rq.query = "学校$银行$公交";
            //rq.scope = BaiduAPI.ScopeType.Details;
            //rq.output = BaiduAPI.OutputType.json;
            //rq.region = "全国";
            //rq.page_num = 0;
            //rq.page_size = 20000;
            //rq.location = "22.55932,114.04508";
            //rq.radius = 3000;
            //BaiduAPI.PlaceResponse rs = BaiduAPI.PlaceAPIManger.SearchPOI(rq);


            //LNKPPhotoManager.test();
            //ProjectApi.test();
            //IList<SYSCode> sys = new Class1().getlist();
            //string json = JsonConvert.SerializeObject(sys);
            //json = json.TrimEnd('}') + ",\"aaa\":333}";
            //string json = "{\"Id\":1109,\"Code\":1109001,\"CodeName\":\"待分配\",\"aaa\":333}";
            //SYSCode sys2 = JsonConvert.DeserializeObject<SYSCode>(json);

            //string url = "http://localhost:50887/API/FxtMobileAPI.svc/Entrance/A";
            //HttpClient web = new HttpClient();
            //var par = new
            //{
            //    sinfo = (new { appid = "", apppwd = "", signname = "", time = "", code = "" }).ToJson(),
            //    info = (new
            //    {
            //        appinfo = "",
            //        uinfo = "",
            //        funinfo = new { type = "test", code = 1109001 }
            //    }).ToJson()
            //};
            //HttpResponseMessage hrm = web.PostAsJsonAsync(url, par).Result;
            //string str = hrm.Content.ReadAsStringAsync().Result;

            // DATProject p = new DATProject();
            // Dictionary<string, string> projectKey = new Dictionary<string, string>();
            // projectKey.Add("build_lng", "X,decimal?,null,物业精度");//物业经度
            // projectKey.Add("build_lat", "Y,decimal?,null,物业纬度");//物业纬度
            // projectKey.Add("locale_lng", "AllotFlowX,decimal?,not null,查勘员现场经度(插入表Dat_AllotFlow)");//查勘员现场经度
            // projectKey.Add("locale_lat", "AllotFlowY,decimal?,not null,查勘员现场纬度(插入表Dat_AllotFlow)");//查勘员现场纬度
            // projectKey.Add("project_name", "ProjectName,string,not null,楼盘名称");//楼盘名称
            // projectKey.Add("cityid", "CityID,int,not null,城市ID(选择)");//城市ID
            // projectKey.Add("areaid", "AreaID,int,not null,行政区ID(选择)");//行政区ID
            // projectKey.Add("address", "Address,string,not null,物业地址");//物业地址
            // projectKey.Add("complete_date", "EndDate,DateTime?,not null,竣工时间");//竣工时间
            // projectKey.Add("orientation_east", "East,string,null,四至朝向-东");//四至朝向-东
            // projectKey.Add("orientation_west", "West,string,null,四至朝向-西");//四至朝向-西
            // projectKey.Add("orientation_south", "South,string,null,四至朝向-南");//四至朝向-南
            // projectKey.Add("orientation_north", "North,string,null,四至朝向-北");//四至朝向-北
            // projectKey.Add("project_area", "BuildingArea,decimal?,not null,建筑面积");//建筑面积
            // projectKey.Add("floor_area", "LandArea,decimal?,not null,占地面积");//占地面积
            // projectKey.Add("plot_ratio", "CubageRate,decimal?,not null,容积率");//容积率
            // projectKey.Add("greening_rate", "GreenRate,decimal?,not null,绿化率");//绿化率
            // projectKey.Add("manager_company", "manager_company,string,null,物业管理公司(插入表LNK_P_Company,CompanyType=2001004)");//物业管理公司
            // projectKey.Add("manager_fees", "ManagerPrice,nvarchar,not null,物业管理费");//物业管理费
            // projectKey.Add("developers", "developers,string,null,开发商(插入表LNK_P_Company,CompanyType=2001001)");//开发商
            // projectKey.Add("parking_num", "ParkingNumber,int,not null,车位数");//车位数
            // projectKey.Add("house_num", "TotalNum,int,not null,总户数or总套数");//总户数or总套数
            // projectKey.Add("open_time", "SaleDate,DateTime?,not null,开盘时间");//开盘时间
            // projectKey.Add("start_time", "BuildingDate,DateTime?,not null,开工时间");//开工时间
            // projectKey.Add("collection_date", "Dat_AllotSurvey$StateDate,DateTime,not null,采集时间");//采集时间
            // projectKey.Add("detail", "Detail,string,null,楼盘备注");//楼盘备注
            // projectKey.Add("remarks", "AllotFlowRemark,string,null,任务备注(插入表Dat_AllotFlow)");//任务备注
            // projectKey.Add("fxtprojectid", "FxtProjectId,int,null,正式库的楼盘ID");//正式库的楼盘ID


            // Dictionary<string, string> appendageKey = new Dictionary<string, string>();
            // appendageKey.Add("appendagecode", "SYS_Code$AppendageCode$2008,int,not null,配套类型(学校;医院..)(选择)");
            // appendageKey.Add("p_aname", "P_AName,string,not null,配套名字");
            // appendageKey.Add("classcode", "SYS_Code$ClassCode$1012,int,not null,配套等级");


            // Dictionary<string, string> buildingKey = new Dictionary<string, string>();
            // buildingKey.Add("build_name", "BuildingName,string,not null,楼栋名称");//楼栋名称
            // buildingKey.Add("build_card_name", "Doorplate,string,null,门牌号");//门牌号
            // buildingKey.Add("build_nick_name", "OtherName,string,null,楼栋别称");//楼栋别称
            // buildingKey.Add("build_struct", "SYS_Code$StructureCode$2010,int?,not null,建筑结构(选择)");//建筑结构
            // buildingKey.Add("position", "SYS_Code$LocationCode$2011,int?,not null,位置(选择)");//位置
            // buildingKey.Add("average_price", "AveragePrice,decimal?,not null,楼栋均价");//楼栋均价
            // buildingKey.Add("complete_date", "BuildDate,DateTime?,not null,楼栋竣工时间(建筑时间)");//楼栋竣工时间(建筑时间)
            // buildingKey.Add("lift", "IsElevator,int,not null,是否带电梯");//是否带电梯
            // buildingKey.Add("house_lift", "ElevatorRate,string,null,梯户数(梯户比)");//梯户数(梯户比)
            // buildingKey.Add("price_commtent", "PriceDetail,string,null,价格说明");//价格说明
            // buildingKey.Add("remarks", "Remark,string,null,备注");//备注
            // projectKey.Add("fxtbuildingid", "FxtBuildingId,int,null,正式库的楼栋ID");//正式库的楼栋ID

            // Dictionary<string, string> houseKey = new Dictionary<string, string>();
            // houseKey.Add("unit", "UnitNo,string,null,单元名称");//单元名称
            // houseKey.Add("roomNO", "HouseName,string,not null,房号");//房号
            // houseKey.Add("orientation", "SYS_Code$FrontCode$2004,string,not null,朝向(选择)");//朝向
            // houseKey.Add("area", "BuildArea,decimal?,not null,面积");//面积
            // houseKey.Add("houseStruct", "SYS_Code$HouseTypeCode$4001,int?,not null,户型(选择)");//户型结构
            // houseKey.Add("remarks", "Remark,string,null,备注");//备注
            // projectKey.Add("fxthouseid", "FxtHouseId,int,null,正式库的房号ID");//正式库的房号ID

            // StringBuilder sb = new StringBuilder();
            // sb.Append("{");
            // foreach (KeyValuePair<string, string> kvp in projectKey)
            // {
            //     string[] values = kvp.Value.Split(',');
            //     string name = (values[0].Contains("$") ? values[0].Split('$')[1] : values[0]).ToLower();
            //     string value = values[1] + "," + values[2] + "," + values[3];
            //     value = "\"(" + value + ")\"";
            //     sb.Append(name).Append("=").Append(value).Append(",");
            // }
            // sb.Append("appendage").Append("==new[]{ new {");

            // foreach (KeyValuePair<string, string> kvp in appendageKey)
            // {
            //     string[] values = kvp.Value.Split(',');
            //     string name = (values[0].Contains("$") ? values[0].Split('$')[1] : values[0]).ToLower();
            //     string value = values[1] + "," + values[2] + "," + values[3];
            //     value = "\"(" + value + ")\"";
            //     sb.Append(name).Append("=").Append(value).Append(",");
            // }
            // sb.Append("}}");
            // sb.Append(",buildingList==new[]{  new {");

            // foreach (KeyValuePair<string, string> kvp in buildingKey)
            // {
            //     string[] values = kvp.Value.Split(',');
            //     string name = (values[0].Contains("$") ? values[0].Split('$')[1] : values[0]).ToLower();
            //     string value = values[1] + "," + values[2] + "," + values[3];
            //     value = "\"(" + value + ")\"";
            //     sb.Append(name).Append("=").Append(value).Append(",");
            // }
            // sb.Append("houseList==new[]{ new {");

            // foreach (KeyValuePair<string, string> kvp in houseKey)
            // {
            //     string[] values = kvp.Value.Split(',');
            //     string name = (values[0].Contains("$") ? values[0].Split('$')[1] : values[0]).ToLower();
            //     string value = values[1] + "," + values[2] + "," + values[3];
            //     value = "\"(" + value + ")\"";
            //     sb.Append(name).Append("=").Append(value).Append(",");
            // }
            // sb.Append("}}");
            // sb.Append("}}");
            // sb.Append("}");
            // string str = sb.ToString();
            // var obj = new
            // {
            //     x = "(decimal?,null,物业精度)",
            //     y = "(decimal?,null,物业纬度)",
            //     allotflowx = "(decimal?,not null,查勘员现场经度(插入表Dat_AllotFlow))",
            //     allotflowy = "(decimal?,not null,查勘员现场纬度(插入表Dat_AllotFlow))",
            //     projectname = "(string,not null,楼盘名称)",
            //     cityid = "(int,not null,城市ID(选择))",
            //     areaid = "(int,not null,行政区ID(选择))",
            //     address = "(string,not null,物业地址)",
            //     enddate = "(DateTime?,not null,竣工时间)",
            //     east = "(string,null,四至朝向-东)",
            //     west = "(string,null,四至朝向-西)",
            //     south = "(string,null,四至朝向-南)",
            //     north = "(string,null,四至朝向-北)",
            //     buildingarea = "(decimal?,not null,建筑面积)",
            //     landarea = "(decimal?,not null,占地面积)",
            //     cubagerate = "(decimal?,not null,容积率)",
            //     greenrate = "(decimal?,not null,绿化率)",
            //     manager_company = "(string,null,物业管理公司(插入表LNK_P_Company)",
            //     managerprice = "(nvarchar,not null,物业管理费)",
            //     developers = "(string,null,开发商(插入表LNK_P_Company)",
            //     parkingnumber = "(int,not null,车位数)",
            //     totalnum = "(int,not null,总户数or总套数)",
            //     saledate = "(DateTime?,not null,开盘时间)",
            //     buildingdate = "(DateTime?,not null,开工时间)",
            //     statedate = "(DateTime,not null,采集时间)",
            //     detail = "(string,null,楼盘备注)",
            //     allotflowremark = "(string,null,任务备注(插入表Dat_AllotFlow))",
            //     fxtprojectid = "(int,null,正式库的楼盘ID)",
            //     appendage =new[]{  new
            //     {
            //         appendagecode = "(int,not null,配套类型(学校;医院..)(选择)",
            //         p_aname = "(string,not null,配套名字)",
            //         classcode = "(int,not null,配套等级)(选择)"
            //     }},
            //     buildingList = new[]{ new {
            //                                            buildingname = "(string,not null,楼栋名称)",
            //                                            doorplate = "(string,null,门牌号)",
            //                                            othername = "(string,null,楼栋别称)",
            //                                            structurecode = "(int?,not null,建筑结构(选择))",
            //                                            locationcode = "(int?,not null,位置(选择))",
            //                                            averageprice = "(decimal?,not null,楼栋均价)",
            //                                            builddate = "(DateTime?,not null,楼栋竣工时间(建筑时间))",
            //                                            iselevator = "(int,not null,是否带电梯)",
            //                                            elevatorrate = "(string,null,梯户数(梯户比))",
            //                                            pricedetail = "(string,null,价格说明)",
            //                                            remark = "(string,null,备注)",
            //                                            fxtbuildingid="(int,null,正式库的楼栋ID)",
            //                                            houseList =new[]{ new {
            //                                                              unitno = "(string,null,单元名称)",
            //                                                              housename = "(string,not null,房号)",
            //                                                              frontcode = "(string,not null,朝向(选择))",
            //                                                              buildarea = "(decimal?,not null,面积)",
            //                                                              housetypecode = "(int?,not null,户型(选择))",
            //                                                              remark = "(string,null,备注)" ,
            //                                                              fxthouseid="(int,null,正式库的房号ID)"
            //                                                             } }
            //                                            }
            //                       }
            // };
            // string json = new  { data = obj }.ToJson();
            //{"data":{
            //         "x":"(decimal?,null,物业精度)",
            //         "y":"(decimal?,null,物业纬度)",
            //         "allotflowx":"(decimal?,not null,查勘员现场经度(插入表Dat_AllotFlow))",
            //         "allotflowy":"(decimal?,not null,查勘员现场纬度(插入表Dat_AllotFlow))",
            //         "projectname":"(string,not null,楼盘名称)",
            //         "cityid":"(int,not null,城市ID(选择))",
            //         "areaid":"(int,not null,行政区ID(选择))",
            //         "address":"(string,not null,物业地址)",
            //         "enddate":"(DateTime?,not null,竣工时间)",
            //         "east":"(string,null,四至朝向-东)",
            //         "west":"(string,null,四至朝向-西)",
            //         "south":"(string,null,四至朝向-南)",
            //         "north":"(string,null,四至朝向-北)",
            //         "buildingarea":"(decimal?,not null,建筑面积)",
            //         "landarea":"(decimal?,not null,占地面积)",
            //         "cubagerate":"(decimal?,not null,容积率)",
            //         "greenrate":"(decimal?,not null,绿化率)",
            //         "manager_company":"(string,null,物业管理公司(插入表LNK_P_Company)",
            //         "managerprice":"(nvarchar,not null,物业管理费)",
            //         "developers":"(string,null,开发商(插入表LNK_P_Company)",
            //         "parkingnumber":"(int,not null,车位数)",
            //         "totalnum":"(int,not null,总户数or总套数)",
            //         "saledate":"(DateTime?,not null,开盘时间)",
            //         "buildingdate":"(DateTime?,not null,开工时间)",
            //         "statedate":"(DateTime,not null,采集时间)",
            //         "detail":"(string,null,楼盘备注)",
            //         "allotflowremark":"(string,null,任务备注(插入表Dat_AllotFlow))",
            //         "fxtprojectid":"(int,null,正式库的楼盘ID)",
            //         "appendage":[
            //                         {
            //                         "appendagecode":"(int,not null,配套类型(学校;医院..)(选择)",
            //                         "p_aname":"(string,not null,配套名字)",
            //                         "classcode":"(int,not null,配套等级)(选择)"
            //                         },
            //                         ...
            //                     ],
            //         "buildinglist":[
            //                             {
            //                             "buildingname":"(string,not null,楼栋名称)",
            //                             "doorplate":"(string,null,门牌号)",
            //                             "othername":"(string,null,楼栋别称)",
            //                             "structurecode":"(int?,not null,建筑结构(选择))",
            //                             "locationcode":"(int?,not null,位置(选择))",
            //                             "averageprice":"(decimal?,not null,楼栋均价)",
            //                             "builddate":"(DateTime?,not null,楼栋竣工时间(建筑时间))",
            //                             "iselevator":"(int,not null,是否带电梯)",
            //                             "elevatorrate":"(string,null,梯户数(梯户比))",
            //                             "pricedetail":"(string,null,价格说明)",
            //                             "remark":"(string,null,备注)",
            //                             "fxtbuildingid":"(int,null,正式库的楼栋ID)",
            //                             "houselist":[
            //                                           {
            //                                            "unitno":"(string,null,单元名称)",
            //                                            "housename":"(string,not null,房号)",
            //                                            "frontcode":"(string,not null,朝向(选择))",
            //                                            "buildarea":"(decimal?,not null,面积)",
            //                                            "housetypecode":"(int?,not null,户型(选择))",
            //                                            "remark":"(string,null,备注)",
            //                                            "fxthouseid":"(int,null,正式库的房号ID)"
            //                                            },
            //                                            ...
            //                                          ]
            //                              },
            //                              ...
            //                         ]
            //         }
            //  }

            return(View());
        }
コード例 #6
0
        public void ResolveNativeLibrariesInManagedReferences([Values(true, false)] bool useShortFileNames)
        {
            var lib = new XamarinAndroidLibraryProject()
            {
                ProjectName     = "Lib",
                ProjectGuid     = Guid.NewGuid().ToString(),
                OtherBuildItems =
                {
                    new BuildItem(AndroidBuildActions.EmbeddedNativeLibrary, "libs/armeabi-v7a/libfoo.so")
                    {
                        TextContent = () => string.Empty,
                        Encoding    = Encoding.ASCII,
                        Timestamp   = DateTimeOffset.Now,
                    }
                },
                Sources =
                {
                    new BuildItem.Source("Class1.cs")
                    {
                        TextContent = () => @"
using System;
namespace Lib
{
	public class Class1
	{
		public Class1 ()
		{
		}
	}
}"
                    },
                },
            };

            lib.SetProperty(lib.ActiveConfigurationProperties, "UseShortFileNames", useShortFileNames);
            var so = lib.OtherBuildItems.First(x => x.Include() == "libs/armeabi-v7a/libfoo.so");

            var lib2 = new XamarinAndroidLibraryProject()
            {
                ProjectName     = "Lib2",
                ProjectGuid     = Guid.NewGuid().ToString(),
                OtherBuildItems =
                {
                    new BuildItem(AndroidBuildActions.EmbeddedNativeLibrary, "libs/armeabi-v7a/libfoo2.so")
                    {
                        TextContent = () => string.Empty,
                        Encoding    = Encoding.ASCII,
                        Timestamp   = DateTimeOffset.Now,
                    },
                    new BuildItem.ProjectReference(@"..\Lib\Lib.csproj",     "Lib", lib.ProjectGuid)
                    {
                    }
                },
                Sources =
                {
                    new BuildItem.Source("Class2.cs")
                    {
                        TextContent = () => @"
using System;
namespace Lib2
{
	public class Class2
	{
		public Class2 ()
		{
			var c = new Lib.Class1 ();
		}
	}
}"
                    },
                },
            };

            lib2.SetProperty(lib.ActiveConfigurationProperties, "UseShortFileNames", useShortFileNames);
            var path = Path.Combine(Root, "temp", $"ResolveNativeLibrariesInManagedReferences_{useShortFileNames}");

            using (var libbuilder = CreateDllBuilder(Path.Combine(path, "Lib"))) {
                Assert.IsTrue(libbuilder.Build(lib), "lib 1st. build failed");

                using (var libbuilder2 = CreateDllBuilder(Path.Combine(path, "Lib2"))) {
                    Assert.IsTrue(libbuilder2.Build(lib2), "lib 1st. build failed");

                    var app = new XamarinAndroidApplicationProject()
                    {
                        ProjectName     = "App",
                        OtherBuildItems =
                        {
                            new BuildItem.ProjectReference(@"..\Lib2\Lib2.csproj", "Lib2", lib2.ProjectGuid),
                        }
                    };
                    app.SetProperty(app.ActiveConfigurationProperties, "UseShortFileNames", useShortFileNames);
                    using (var builder = CreateApkBuilder(Path.Combine(path, "App"))) {
                        builder.Verbosity = LoggerVerbosity.Diagnostic;
                        Assert.IsTrue(builder.Build(app), "app 1st. build failed");

                        var libfoo = ZipHelper.ReadFileFromZip(Path.Combine(Root, builder.ProjectDirectory, app.OutputPath, app.PackageName + ".apk"),
                                                               "lib/armeabi-v7a/libfoo.so");
                        Assert.IsNotNull(libfoo, "libfoo.so should exist in the .apk");

                        so.TextContent = () => "newValue";
                        so.Timestamp   = DateTimeOffset.Now;
                        Assert.IsTrue(libbuilder.Build(lib), "lib 2nd. build failed");
                        Assert.IsTrue(libbuilder2.Build(lib2), "lib 2nd. build failed");
                        Assert.IsTrue(builder.Build(app), "app 2nd. build failed");

                        Assert.IsNotNull(libfoo, "libfoo.so should exist in the .apk");

                        Assert.AreEqual(so.TextContent().Length, new FileInfo(Path.Combine(Root, libbuilder.ProjectDirectory, lib.IntermediateOutputPath,
                                                                                           useShortFileNames ? "nl" : "native_library_imports", "armeabi-v7a", "libfoo.so")).Length,
                                        "intermediate size mismatch");
                        libfoo = ZipHelper.ReadFileFromZip(Path.Combine(Root, builder.ProjectDirectory, app.OutputPath, app.PackageName + ".apk"),
                                                           "lib/armeabi-v7a/libfoo.so");
                        Assert.AreEqual(so.TextContent().Length, libfoo.Length, "compressed size mismatch");
                        var libfoo2 = ZipHelper.ReadFileFromZip(Path.Combine(Root, builder.ProjectDirectory, app.OutputPath, app.PackageName + ".apk"),
                                                                "lib/armeabi-v7a/libfoo2.so");
                        Assert.IsNotNull(libfoo2, "libfoo2.so should exist in the .apk");
                        Directory.Delete(path, recursive: true);
                    }
                }
            }
        }
コード例 #7
0
        public void BuildAotApplicationAndÜmläüts(string supportedAbis, bool enableLLVM, bool expectedResult)
        {
            var path = Path.Combine("temp", string.Format("BuildAotApplication AndÜmläüts_{0}_{1}_{2}", supportedAbis, enableLLVM, expectedResult));
            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease        = true,
                BundleAssemblies = false,
                AotAssemblies    = true,
            };

            proj.SetProperty(KnownProperties.TargetFrameworkVersion, "v5.1");
            proj.SetAndroidSupportedAbis(supportedAbis);
            proj.SetProperty("EnableLLVM", enableLLVM.ToString());
            bool checkMinLlvmPath = enableLLVM && (supportedAbis == "armeabi-v7a" || supportedAbis == "x86");

            if (checkMinLlvmPath)
            {
                // Set //uses-sdk/@android:minSdkVersion so that LLVM uses the right libc.so
                proj.AndroidManifest = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<manifest xmlns:android=""http://schemas.android.com/apk/res/android"" android:versionCode=""1"" android:versionName=""1.0"" package=""{proj.PackageName}"">
	<uses-sdk android:minSdkVersion=""{Xamarin.Android.Tools.XABuildConfig.NDKMinimumApiAvailable}"" />
	<application android:label=""{proj.ProjectName}"">
	</application>
</manifest>";
            }
            using (var b = CreateApkBuilder(path)) {
                if (!b.CrossCompilerAvailable(supportedAbis))
                {
                    Assert.Ignore($"Cross compiler for {supportedAbis} was not available");
                }
                if (!b.GetSupportedRuntimes().Any(x => supportedAbis == x.Abi))
                {
                    Assert.Ignore($"Runtime for {supportedAbis} was not available.");
                }
                b.ThrowOnBuildFailure = false;
                Assert.AreEqual(expectedResult, b.Build(proj), "Build should have {0}.", expectedResult ? "succeeded" : "failed");
                if (!expectedResult)
                {
                    return;
                }
                //NOTE: Windows has shortened paths such as: C:\Users\myuser\ANDROI~3\ndk\PLATFO~1\AN3971~1\arch-x86\usr\lib\libc.so
                if (checkMinLlvmPath && !IsWindows)
                {
                    // LLVM passes a direct path to libc.so, and we need to use the libc.so
                    // which corresponds to the *minimum* SDK version specified in AndroidManifest.xml
                    // Since we overrode minSdkVersion=16, that means we should use libc.so from android-16.
                    StringAssertEx.ContainsRegex(@"\s*\[aot-compiler stdout].*android-16.arch-.*.usr.lib.libc\.so", b.LastBuildOutput, "AOT+LLVM should use libc.so from minSdkVersion!");
                }
                foreach (var abi in supportedAbis.Split(new char [] { ';' }))
                {
                    var libapp = Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath,
                                              "bundles", abi, "libmonodroid_bundle_app.so");
                    Assert.IsFalse(File.Exists(libapp), abi + " libmonodroid_bundle_app.so should not exist");
                    var assemblies = Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath,
                                                  "aot", abi, "libaot-UnnamedProject.dll.so");
                    Assert.IsTrue(File.Exists(assemblies), "{0} libaot-UnnamedProject.dll.so does not exist", abi);
                    var apk = Path.Combine(Root, b.ProjectDirectory,
                                           proj.IntermediateOutputPath, "android", "bin", "UnnamedProject.UnnamedProject.apk");
                    using (var zipFile = ZipHelper.OpenZip(apk)) {
                        Assert.IsNotNull(ZipHelper.ReadFileFromZip(zipFile,
                                                                   string.Format("lib/{0}/libaot-UnnamedProject.dll.so", abi)),
                                         "lib/{0}/libaot-UnnamedProject.dll.so should be in the UnnamedProject.UnnamedProject.apk", abi);
                        Assert.IsNotNull(ZipHelper.ReadFileFromZip(zipFile,
                                                                   "assemblies/UnnamedProject.dll"),
                                         "UnnamedProject.dll should be in the UnnamedProject.UnnamedProject.apk");
                    }
                }
                Assert.AreEqual(expectedResult, b.Build(proj), "Second Build should have {0}.", expectedResult ? "succeeded" : "failed");
                Assert.IsTrue(
                    b.Output.IsTargetSkipped("_CompileJava"),
                    "the _CompileJava target should be skipped");
                Assert.IsTrue(
                    b.Output.IsTargetSkipped("_BuildApkEmbed"),
                    "the _BuildApkEmbed target should be skipped");
            }
        }
コード例 #8
0
        static void Main(string[] args)
        {
            var bytes = ZipHelper.MakeZipArchiveBytes();

            Console.WriteLine($"Bytes length = {bytes.Length}");
        }
コード例 #9
0
    private void DrawAssetUI()
    {
        GUILayout.BeginHorizontal("HelpBox");
        EditorGUILayout.LabelField("== 快捷功能 ==");
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Build Lua To StreamingAsset", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30)))
        {
            ColaEditHelper.BuildLuaToStreamingAsset();
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Zip Lua", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30)))
        {
            var result = ZipHelper.Zip("Assets/Lua", Path.Combine(Application.dataPath, "../output/luaout.zip"));
            Debug.Log("Zip Lua结果:" + result);
        }
        if (GUILayout.Button("UnZip Lua", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30)))
        {
            var filePath = Path.Combine("Assets", "../output/luaout.zip");
            if (File.Exists(filePath))
            {
                var result = ZipHelper.UnZip(filePath, Path.Combine("Assets", "../output"));
                Debug.Log("UnZip Lua结果:" + result);
            }
            else
            {
                Debug.LogError("解压错误!要解压的文件不存在!路径:" + filePath);
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("筛选出MD5码变化的lua文件", GUILayout.ExpandWidth(true), GUILayout.MaxHeight(30)))
        {
            var md5Dic         = new Dictionary <string, string>();
            var luaMd5FilePath = ColaEditHelper.TempCachePath + "/LuaMD5.txt";
            if (File.Exists(luaMd5FilePath))
            {
                using (var sm = new StreamReader(luaMd5FilePath, Encoding.UTF8))
                {
                    var fileLines = sm.ReadToEnd().Split('\n');
                    foreach (var item in fileLines)
                    {
                        if (string.IsNullOrEmpty(item))
                        {
                            continue;
                        }
                        var lineContent = item.Split('|');
                        if (lineContent.Length == 2)
                        {
                            md5Dic[lineContent[0]] = lineContent[1];
                        }
                        else
                        {
                            Debug.LogError("LuaMD5.txt格式错误!内容为: " + lineContent);
                        }
                    }
                }
            }

            var luaFiles = new List <string>(Directory.GetFiles(LuaLogicPath, "*.lua", SearchOption.AllDirectories));
            var fLength  = (float)luaFiles.Count;

            int diffCnt = 0;
            for (int i = 0; i < luaFiles.Count; i++)
            {
                var    fileName = luaFiles[i];
                string curMd5   = FileHelper.GetMD5Hash(fileName);
                if (md5Dic.ContainsKey(fileName) && curMd5 == md5Dic[fileName])
                {
                    continue;
                }
                diffCnt++;
                string destPath = Regex.Replace(fileName, "^Assets", "output");
                FileHelper.EnsureParentDirExist(destPath);
                File.Copy(fileName, destPath, true);
                md5Dic[fileName] = curMd5;
                EditorUtility.DisplayProgressBar("正在分析Lua差异化..", fileName, i / fLength);
            }

            var sb = new StringBuilder();
            foreach (var item in md5Dic)
            {
                sb.AppendFormat("{0}|{1}", item.Key, item.Value).AppendLine();
            }
            FileHelper.WriteString(luaMd5FilePath, sb.ToString());
            EditorUtility.ClearProgressBar();

            Debug.LogFormat("Lua差异化分析完毕!共有{0}个差异化文件!", diffCnt);
        }
        GUILayout.EndHorizontal();
    }
コード例 #10
0
        private void DoWork()
        {
            JLog.Instance.AppInfo("仿真线程已启动.....");
            while (true)
            {
                #region 提取仿真数据
                Monitor.Enter(PLADatas);

                if (PLADatas.Count >= 1)
                {
                    _CurProcData = PLADatas.Dequeue();
                }
                else
                {
                    _CurProcData = null;
                }
                Monitor.Exit(PLADatas);
                #endregion
                if (_CurProcData != null)
                {
                    CreateNewEAWSHandle();
                    XmlFilePackageInfo xmlFilePage = new XmlFilePackageInfo();
                    //生成XML文件
                    JLog.Instance.AppInfo("开始生成XML文件....");
                    var _BuilLTEXMLResult = LteNodeBuildFactory.BuilLTEXMLFilesInterface(_CurProcData.BaseInfo, _CurProcData.CellSectors, _CurProcData.Savedir,
                                                                                         out xmlFilePage);
                    if (_BuilLTEXMLResult) //生成成功
                    {
                        #region 导入前EAWS仿真

                        string Taskname    = GetTaskName(_CurProcData.ProjectName);
                        string SchemaName  = GlobalInfo.Instance.ConfigParam.EAWSSchemaName;
                        string SaveDirName = Guid.NewGuid().ToString();
//#if WEB
//                        string SaveFileDir = HttpContext.Current.Server.MapPath(string.Format("~/FTPDir/{0}", SaveDirName));
//                        JLog.Instance.AppInfo(string.Format("FTP目录:{0}",SaveFileDir));
//#else
                        string SaveFileDir = Path.Combine(GlobalInfo.Instance.ConfigParam.FTPDir, SaveDirName);
//#endif
                        if (!System.IO.Directory.Exists(SaveFileDir))
                        {
                            System.IO.Directory.CreateDirectory(SaveFileDir);
                        }

                        if (!String.IsNullOrEmpty(Taskname))
                        {
                            //获取带号

                            var ProjectInfo = GlobalInfo.Instance.ConfigParam.ProjectNames
                                              .FirstOrDefault(
                                Fo => Fo.ProjectName == _CurProcData.ProjectName);
                            if (ProjectInfo == null)
                            {
                                JLog.Instance.AppInfo(string.Format("配置文件中没有找到工程名为:{0}的工程",
                                                                    _CurProcData.ProjectName));
                                continue;
                            }
                            var ProjNo = ProjectInfo.UtmID;
                            JLog.Instance.AppInfo(string.Format("工程投影带号为:{0}", ProjNo));
                            _CurProcData.GetExtend(_CurProcData.BaseInfo.Lng, _CurProcData.BaseInfo.Lat,
                                                   out _CurProcData.RegionBound.EastMin,
                                                   out _CurProcData.RegionBound.Eastmax,
                                                   out _CurProcData.RegionBound.NorthMin,
                                                   out _CurProcData.RegionBound.NorthMax,
                                                   _CurProcData.CoverRadius * 1000, ProjNo);
                            JLog.Instance.AppInfo(string.Format("工程坐标范围为:{0}",
                                                                _CurProcData.RegionBound.ToString()));
                            _bllEAWs.UpdateRegionREQ(_CurProcData.RegionBound, SchemaName,
                                                     Taskname);
                            DoNextTask = false;
                            _ReSet.WaitOne(600000);
                            JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                            if (DoNextTask)
                            {
                                JLog.Instance.AppInfo("编辑仿真范围完成");

                                #region 启动仿真

                                DoNextTask = false;
                                JLog.Instance.AppInfo("发送启动仿真请求");
                                _bllEAWs.StartTaskREQ(SchemaName, Taskname);
                                DoNextTask = false;
                                _ReSet.WaitOne(60000);
                                if (DoNextTask)
                                {
                                    JLog.Instance.AppInfo("启动仿真任务完成,等待任务执行完成");
                                    DoNextTask = false;
                                    _ReSet.WaitOne(3600000);
                                    JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                                    if (DoNextTask)
                                    {
                                        JLog.Instance.AppInfo("仿真任务执行完成");

                                        #region 压缩上传文件
                                        if (!string.IsNullOrEmpty(EAWSReleaseSaveDir))
                                        {
                                            EAWSReleaseSaveDir = string.Format(@"{0}\{1}", EAWSReleaseSaveDir,
                                                                               ProjectInfo.TaskName);
                                        }
                                        else
                                        {
                                            JLog.Instance.AppInfo("BLLEAWS返回的仿真结果保存路径为空,执行中断");
                                            continue;
                                        }
//#if WEB
//                                        EAWSReleaseSaveDir = HttpContext.Current.Server.MapPath(string.Format("~/ResultDir/{0}",_CurProcData.ProjectName));
//#endif
                                        JLog.Instance.AppInfo(string.Format("仿真结果保存路径:{0}", EAWSReleaseSaveDir));


                                        string ArarFileName = "A.rar";// string.Format(, Guid.NewGuid().ToString());
                                        ZipHelper.Zip(
                                            Path.Combine(SaveFileDir,
                                                         ArarFileName), EAWSReleaseSaveDir, "*****@*****.**",
                                            ZipHelper.CompressLevel.Level6);
                                        JLog.Instance.AppInfo("压缩文件成功");
                                        #endregion

                                        #region 导入XML文件,生成
                                        JLog.Instance.AppInfo("开始生成XML成功,开始...");
                                        //导入XML文件
                                        if (ExecuteCommand(AutoEDSInputCommand(xmlFilePage.InputLocationFileFullName, _CurProcData.ProjectName),
                                                           60000))
                                        {
                                            if (
                                                ExecuteCommand(AutoEDSInputCommand(xmlFilePage.InputLTENodeFileFullName, _CurProcData.ProjectName),
                                                               60000))
                                            {
                                                JLog.Instance.AppInfo("导入XML文件执行完成,判断导入位置数据是否成功...");
                                                if (InputXmlSuccess(_CurProcData.BaseInfo.Stationiid, _CurProcData.ProjectName))
                                                //判断导入是否成功,导入成功执行
                                                {
                                                    JLog.Instance.AppInfo("导入XML文件执行成功,启动EAWS仿真...");

                                                    #region 启动EAWS仿真

                                                    //string Taskname = GetTaskName(_CurProcData.ProjectName);
                                                    //string SchemaName = GlobalInfo.Instance.ConfigParam.EAWSSchemaName;
                                                    if (!String.IsNullOrEmpty(Taskname))
                                                    {
                                                        //获取带号
                                                        JLog.Instance.AppInfo(string.Format("工程投影带号为:{0}", ProjNo));
                                                        _CurProcData.GetExtend(_CurProcData.BaseInfo.Lng, _CurProcData.BaseInfo.Lat,
                                                                               out _CurProcData.RegionBound.EastMin,
                                                                               out _CurProcData.RegionBound.Eastmax,
                                                                               out _CurProcData.RegionBound.NorthMin,
                                                                               out _CurProcData.RegionBound.NorthMax,
                                                                               _CurProcData.CoverRadius * 1000, ProjNo);
                                                        JLog.Instance.AppInfo(string.Format("工程坐标范围为:{0}",
                                                                                            _CurProcData.RegionBound.ToString()));
                                                        _bllEAWs.UpdateRegionREQ(_CurProcData.RegionBound, SchemaName,
                                                                                 Taskname);
                                                        DoNextTask = false;
                                                        _ReSet.WaitOne(600000);
                                                        JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                                                        if (DoNextTask)
                                                        {
                                                            JLog.Instance.AppInfo("编辑仿真范围完成");

                                                            #region 启动仿真

                                                            DoNextTask = false;
                                                            JLog.Instance.AppInfo("发送启动仿真请求");
                                                            _bllEAWs.StartTaskREQ(SchemaName, Taskname);
                                                            DoNextTask = false;
                                                            _ReSet.WaitOne(60000);
                                                            if (DoNextTask)
                                                            {
                                                                JLog.Instance.AppInfo("启动仿真任务完成,等待任务执行完成");
                                                                DoNextTask = false;
                                                                _ReSet.WaitOne(3600000);
                                                                JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                                                                if (DoNextTask)
                                                                {
                                                                    JLog.Instance.AppInfo("仿真任务执行完成");

                                                                    #region 压缩上传文件
                                                                    if (!string.IsNullOrEmpty(EAWSReleaseSaveDir))
                                                                    {
                                                                        EAWSReleaseSaveDir = string.Format(@"{0}\{1}", EAWSReleaseSaveDir,
                                                                                                           ProjectInfo.TaskName);
                                                                    }
                                                                    else
                                                                    {
                                                                        JLog.Instance.AppInfo("BLLEAWS返回的仿真结果保存路径为空,执行中断");
                                                                        continue;
                                                                    }
                                                                    JLog.Instance.AppInfo(string.Format("仿真结果保存路径:{0}", EAWSReleaseSaveDir));
                                                                    string BrarFileName = "B.rar";
                                                                    ZipHelper.Zip(
                                                                        Path.Combine(SaveFileDir,
                                                                                     BrarFileName), EAWSReleaseSaveDir, "*****@*****.**",
                                                                        ZipHelper.CompressLevel.Level6);
                                                                    #endregion
                                                                    Thread.Sleep(60000);
                                                                    #region 解压文件
                                                                    RepackageFile(SaveFileDir);
                                                                    #endregion

                                                                    #region 调用浪潮接口上传
                                                                    JLog.Instance.AppInfo("通知浪潮下载");
                                                                    Inspur.InspurRequestApiModel sendmodel = new Inspur.InspurRequestApiModel()
                                                                    {
                                                                        flow_id = _CurProcData.WorkOrder,
                                                                        name    = SaveDirName,
                                                                        remark  = ""
                                                                    };
                                                                    var sendxml  = XMLHelper.SerializeToXmlStr(sendmodel, true);
                                                                    var s        = new Inspur.InspurService.TaircomServiceImplService();
                                                                    var recxml   = s.SycAirCom(sendxml);
                                                                    var recModel =
                                                                        XMLHelper.XmlDeserialize <Inspur.InspurResponeseApiModel>(
                                                                            recxml);
                                                                    if (recModel.is_archive.Equals("0"))
                                                                    {
                                                                        JLog.Instance.AppInfo("浪潮返回调用成功消息");
                                                                    }
                                                                    else
                                                                    {
                                                                        JLog.Instance.AppInfo("浪潮返回调用失败消息");
                                                                    }
                                                                    #endregion

                                                                    if (_CurProcData.BaseInfo.SaveType == EnumSaveType.Delete)
                                                                    //需要删除基站的,执行删除程序
                                                                    {
                                                                        JLog.Instance.AppInfo("执行删除xml操作");

                                                                        #region 执行删除xml操作

                                                                        if (
                                                                            !ExecuteCommand(
                                                                                AutoEDSDeleteCommand(
                                                                                    xmlFilePage.DeleteLTENodeFileFullName,
                                                                                    _CurProcData.ProjectName),
                                                                                60000))
                                                                        {
                                                                            JLog.Instance.AppInfo("执行删除xml操作失败");
                                                                        }
                                                                        else
                                                                        {
                                                                            JLog.Instance.AppInfo("执行删除xml操作成功");
                                                                            if (!ExecuteCommand(AutoEDSDeleteCommand(xmlFilePage.DeleteLocationFileFullName, _CurProcData.ProjectName), 60000))
                                                                            {
                                                                                JLog.Instance.AppInfo("执行删除xml操作失败");
                                                                            }
                                                                        }
                                                                        #endregion
                                                                    }
                                                                    continue;
                                                                }
                                                                JLog.Instance.Info("仿真任务执行失败,无需执行下一步,退出");
                                                                continue;
                                                            }
                                                            JLog.Instance.Info("启动仿真失败,无需执行下一步,退出");
                                                            continue;
                                                            #endregion
                                                        }
                                                        JLog.Instance.AppInfo("编辑仿真范围失败,无需执行下一步");
                                                        continue;
                                                    }
                                                    JLog.Instance.AppInfo("配置文件中没有找到相应的工程信息,中断");
                                                    continue;
                                                    #endregion
                                                }
                                                JLog.Instance.AppInfo("导入XML文件执行失败,不执行仿真任务");
                                                continue;
                                            }
                                            JLog.Instance.AppInfo("执行导入LTENode命令失败");
                                            continue;
                                        }
                                        JLog.Instance.AppInfo("执行导入location命令失败");
                                        continue;
                                        #endregion
                                    }
                                    JLog.Instance.Info("仿真任务执行失败,无需执行下一步,退出");
                                    continue;
                                }
                                JLog.Instance.Info("启动仿真失败,无需执行下一步,退出");
                                continue;
                                #endregion
                            }
                            JLog.Instance.AppInfo("编辑仿真范围失败,无需执行下一步");
                            continue;
                        }
                        JLog.Instance.AppInfo("配置文件中没有找到相应的工程信息,中断");
                        continue;
                        #endregion

                        #region 导入XML文件,生成
                        //JLog.Instance.AppInfo("开始生成XML成功,开始...");
                        ////导入XML文件
                        //if (ExecuteCommand(AutoEDSInputCommand(xmlFilePage.InputLocationFileFullName, _CurProcData.ProjectName),
                        //    60000))
                        //{
                        //    if (
                        //        ExecuteCommand(AutoEDSInputCommand(xmlFilePage.InputLTENodeFileFullName, _CurProcData.ProjectName),
                        //            60000))
                        //    {
                        //        JLog.Instance.AppInfo("导入XML文件执行完成,判断导入位置数据是否成功...");
                        //        if (InputXmlSuccess(_CurProcData.BaseInfo.StationId, _CurProcData.ProjectName))
                        //        //判断导入是否成功,导入成功执行
                        //        {
                        //            JLog.Instance.AppInfo("导入XML文件执行成功,启动EAWS仿真...");

                        //            #region 启动EAWS仿真

                        //            //string Taskname = GetTaskName(_CurProcData.ProjectName);
                        //            //string SchemaName = GlobalInfo.Instance.ConfigParam.EAWSSchemaName;
                        //            if (!String.IsNullOrEmpty(Taskname))
                        //            {
                        //                //获取带号

                        //                var ProjectInfo = GlobalInfo.Instance.ConfigParam.ProjectNames
                        //                    .FirstOrDefault(
                        //                        Fo => Fo.ProjectName == _CurProcData.ProjectName);
                        //                if (ProjectInfo == null)
                        //                {

                        //                    JLog.Instance.AppInfo(string.Format("配置文件中没有找到工程名为:{0}的工程",
                        //                        _CurProcData.ProjectName));
                        //                    continue;
                        //                }
                        //                var ProjNo = ProjectInfo.UtmID;
                        //                JLog.Instance.AppInfo(string.Format("工程投影带号为:{0}", ProjNo));
                        //                _CurProcData.GetExtend(_CurProcData.BaseInfo.Lng, _CurProcData.BaseInfo.Lat,
                        //                    out _CurProcData.RegionBound.EastMin,
                        //                    out _CurProcData.RegionBound.Eastmax,
                        //                    out _CurProcData.RegionBound.NorthMin,
                        //                    out _CurProcData.RegionBound.NorthMax,
                        //                    _CurProcData.CoverRadius * 1000, ProjNo);
                        //                JLog.Instance.AppInfo(string.Format("工程坐标范围为:{0}",
                        //                    _CurProcData.RegionBound.ToString()));
                        //                _bllEAWs.UpdateRegionREQ(_CurProcData.RegionBound, SchemaName,
                        //                    Taskname);
                        //                DoNextTask = false;
                        //                _ReSet.WaitOne(600000);
                        //                JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                        //                if (DoNextTask)
                        //                {
                        //                    JLog.Instance.AppInfo("编辑仿真范围完成");

                        //                    #region 启动仿真

                        //                    DoNextTask = false;
                        //                    JLog.Instance.AppInfo("发送启动仿真请求");
                        //                    _bllEAWs.StartTaskREQ(SchemaName, Taskname);
                        //                    DoNextTask = false;
                        //                    _ReSet.WaitOne(60000);
                        //                    if (DoNextTask)
                        //                    {
                        //                        JLog.Instance.AppInfo("启动仿真任务完成,等待任务执行完成");
                        //                        DoNextTask = false;
                        //                        _ReSet.WaitOne(3600000);
                        //                        JLog.Instance.AppInfo("_ReSet等待完成,执行下一步操作");
                        //                        if (DoNextTask)
                        //                        {
                        //                            JLog.Instance.AppInfo("仿真任务执行完成");

                        //                            #region 压缩上传文件
                        //                            if (!string.IsNullOrEmpty(EAWSReleaseSaveDir))
                        //                            {
                        //                                EAWSReleaseSaveDir = string.Format(@"{0}\{1}", EAWSReleaseSaveDir,
                        //                                      ProjectInfo.TaskName);
                        //                            }
                        //                            else
                        //                            {
                        //                                JLog.Instance.AppInfo("BLLEAWS返回的仿真结果保存路径为空,执行中断");
                        //                                continue;

                        //                            }
                        //                            JLog.Instance.AppInfo(string.Format("仿真结果保存路径:{0}", EAWSReleaseSaveDir));
                        //                            string rarFileName = string.Format("{0}.rar", Guid.NewGuid().ToString());
                        //                            ZipHelper.Zip(
                        //                                Path.Combine(GlobalInfo.Instance.ConfigParam.FTPDir,
                        //                                    rarFileName), EAWSReleaseSaveDir, string.Empty,
                        //                                ZipHelper.CompressLevel.Level6);
                        //                            #endregion

                        //                            #region 调用浪潮接口上传
                        //                            JLog.Instance.AppInfo("压缩文件,上传至浪潮");
                        //                            Inspur.InspurRequestApiModel sendmodel = new Inspur.InspurRequestApiModel()
                        //                            {
                        //                                flow_id = _CurProcData.WorkOrder,
                        //                                name = rarFileName,
                        //                                remark = ""
                        //                            };
                        //                            var sendxml = XMLHelper.SerializeToXmlStr(sendmodel, true);
                        //                            var s = new Inspur.InspurService.TaircomServiceImplService();
                        //                            var recxml = s.SycAirCom(sendxml);
                        //                            var recModel =
                        //                                XMLHelper.XmlDeserialize<Inspur.InspurResponeseApiModel>(
                        //                                    recxml);
                        //                            if (recModel.is_archive.Equals("0"))
                        //                            {
                        //                                JLog.Instance.AppInfo("浪潮返回调用成功消息");
                        //                            }
                        //                            else
                        //                            {
                        //                                JLog.Instance.AppInfo("浪潮返回调用失败消息");
                        //                            }
                        //                            #endregion

                        //                            if (_CurProcData.BaseInfo.SaveType == EnumSaveType.Delete)
                        //                            //需要删除基站的,执行删除程序
                        //                            {
                        //                                JLog.Instance.AppInfo("执行删除xml操作");

                        //                                #region 执行删除xml操作

                        //                                if (
                        //                                    !ExecuteCommand(
                        //                                        AutoEDSDeleteCommand(
                        //                                            xmlFilePage.DeleteLTENodeFileFullName,
                        //                                            _CurProcData.ProjectName),
                        //                                        60000))
                        //                                {
                        //                                    JLog.Instance.AppInfo("执行删除xml操作失败");
                        //                                }
                        //                                else
                        //                                {
                        //                                    JLog.Instance.AppInfo("执行删除xml操作成功");

                        //                                }
                        //                                #endregion
                        //                            }
                        //                            continue;
                        //                        }
                        //                        JLog.Instance.Info("仿真任务执行失败,无需执行下一步,退出");
                        //                        continue;
                        //                    }
                        //                    JLog.Instance.Info("启动仿真失败,无需执行下一步,退出");
                        //                    continue;
                        //                    #endregion
                        //                }
                        //                JLog.Instance.AppInfo("编辑仿真范围失败,无需执行下一步");
                        //                continue;
                        //            }
                        //            JLog.Instance.AppInfo("配置文件中没有找到相应的工程信息,中断");
                        //            continue;
                        //            #endregion

                        //        }
                        //        JLog.Instance.AppInfo("导入XML文件执行失败,不执行仿真任务");
                        //        continue;

                        //    }
                        //    JLog.Instance.AppInfo("执行导入LTENode命令失败");
                        //    continue;

                        //}
                        //JLog.Instance.AppInfo("执行导入location命令失败");
                        //continue;
                        #endregion
                    }
                    JLog.Instance.AppInfo("开始生成XML文件失败");
                    continue;
                }
                JLog.Instance.AppInfo("等待.......");
                Thread.Sleep(40000);
            }
        }
コード例 #11
0
        /// <summary>
        /// 用户权限列表
        /// </summary>
        public string PubGetUserPurviewList(int systemId, int roleId, int userId)
        {
            DataTable rltDt = this.BLLProvider.UserPurviewBLL.GetUserPurview(systemId, roleId, userId);

            return(ZipHelper.CompressDataTable(rltDt));
        }
コード例 #12
0
 /// <summary>
 /// 异步导入诊疗项目
 /// </summary>
 /// <param name="paraCategory"></param>
 /// <param name="paraShopCategory"></param>
 /// <param name="paraBrand"></param>
 /// <param name="paraSaleStatus"></param>
 /// <param name="_shopid"></param>
 /// <param name="_userid"></param>
 /// <param name="file">压缩文件名</param>
 /// <returns></returns>
 public void ImportProductAsync(long paraCategory, long paraShopCategory, long?paraBrand, int paraSaleStatus, long _shopid, long _userid, long freightId, string file)
 {
     /*
      * 产品ID/主图
      * 产品ID/Details/明细图片
      */
     AsyncManager.OutstandingOperations.Increment();
     Task.Factory.StartNew(() =>
     {
         string filePath = Server.MapPath("/temp/" + file);
         string imgpath1 = string.Format(@"/Storage/Shop/{0}/Products", _shopid);
         string imgpath2 = Server.MapPath(imgpath1);
         long brand      = 0;
         if (paraBrand.HasValue)
         {
             brand = paraBrand.Value;
         }
         JsonResult result = new JsonResult();
         if (System.IO.File.Exists(filePath))
         {
             try
             {
                 ZipHelper.ZipInfo zipinfo = ZipHelper.UnZipFile(filePath);
                 if (zipinfo.Success)
                 {
                     int intCnt = ProcessProduct(paraCategory, paraShopCategory, brand, paraSaleStatus, _shopid, _userid, freightId, zipinfo.UnZipPath, imgpath1, imgpath2);
                     if (intCnt > 0)
                     {
                         AsyncManager.Parameters["success"] = true;
                         AsyncManager.Parameters["message"] = "成功导入【" + intCnt.ToString() + "】件诊疗项目";
                     }
                     else
                     {
                         Core.Cache.Remove(CacheKeyCollection.UserImportProductCount(_userid));
                         Core.Cache.Remove(CacheKeyCollection.UserImportProductTotal(_userid));
                         AsyncManager.Parameters["success"] = false;
                         AsyncManager.Parameters["message"] = "导入【0】件诊疗项目,请检查数据包格式,或是否重复导入";
                     }
                 }
                 else
                 {
                     Core.Log.Error("解压文件异常:" + zipinfo.InfoMessage);
                     AsyncManager.Parameters["success"] = false;
                     AsyncManager.Parameters["message"] = "解压出现异常,请检查压缩文件格式";
                 }
             }
             catch (Exception ex)
             {
                 Core.Log.Error("导入诊疗项目异常:" + ex.Message);
                 Core.Cache.Remove(CacheKeyCollection.UserImportProductCount(_userid));
                 Core.Cache.Remove(CacheKeyCollection.UserImportProductTotal(_userid));
                 AsyncManager.Parameters["success"] = false;
                 AsyncManager.Parameters["message"] = "导入诊疗项目异常:" + ex.Message;
             }
         }
         else
         {
             AsyncManager.Parameters["success"] = false;
             AsyncManager.Parameters["message"] = "上传文件不存在";
         }
         AsyncManager.OutstandingOperations.Decrement();
         object opcount = Core.Cache.Get(CacheKeyCollection.UserImportOpCount);
         if (opcount != null)
         {
             Core.Cache.Insert(CacheKeyCollection.UserImportOpCount, int.Parse(opcount.ToString()) - 1);
         }
     });
 }
コード例 #13
0
        // TODO Load element with XMLBeans or dynamic table
        // TODO Check every element/namespace for compliance
        public PackagePart Unmarshall(UnmarshallContext context, Stream in1)
        {
            PackagePropertiesPart coreProps = new PackagePropertiesPart(context
                                                                        .Package, context.PartName);

            // If the input stream is null then we try to get it from the
            // package.
            if (in1 == null)
            {
                if (context.ZipEntry != null)
                {
                    in1 = ((ZipPackage)context.Package).ZipArchive
                          .GetInputStream(context.ZipEntry);
                }
                else if (context.Package != null)
                {
                    // Try to retrieve the part inputstream from the URI
                    ZipEntry zipEntry;
                    try
                    {
                        zipEntry = ZipHelper
                                   .GetCorePropertiesZipEntry((ZipPackage)context
                                                              .Package);
                    }
                    catch (OpenXml4NetException)
                    {
                        throw new IOException(
                                  "Error while trying to get the part input stream.");
                    }
                    in1 = ((ZipPackage)context.Package).ZipArchive
                          .GetInputStream(zipEntry);
                }
                else
                {
                    throw new IOException(
                              "Error while trying to get the part input stream.");
                }
            }

            XmlDocument xmlDoc = null;

            try
            {
                xmlDoc = DocumentHelper.LoadDocument(in1);

                nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("cp", namespaceCP);
                nsmgr.AddNamespace("dc", namespaceDC);
                nsmgr.AddNamespace("dcterms", namespaceDcTerms);
                nsmgr.AddNamespace("xsi", namespaceXSI);
                nsmgr.AddNamespace("cml", PackageNamespaces.MARKUP_COMPATIBILITY);
                nsmgr.AddNamespace("dcmitype", PackageNamespaces.DCMITYPE);


                //xmlDoc.ReadNode(reader);
                //try {
                //xmlDoc = xmlReader.read(in1);


                /* Check OPC compliance */

                // Rule M4.2, M4.3, M4.4 and M4.5/
                CheckElementForOPCCompliance(xmlDoc.DocumentElement);

                /* End OPC compliance */

                //} catch (DocumentException e) {
                //    throw new IOException(e.getMessage());
                //}
            }
            catch (XmlException ex)
            {
                throw new IOException(ex.Message, ex);
            }
            if (xmlDoc != null && xmlDoc.DocumentElement != null)
            {
                coreProps.SetCategoryProperty(LoadCategory(xmlDoc));
                coreProps.SetContentStatusProperty(LoadContentStatus(xmlDoc));
                coreProps.SetContentTypeProperty(LoadContentType(xmlDoc));
                coreProps.SetCreatedProperty(LoadCreated(xmlDoc));
                coreProps.SetCreatorProperty(LoadCreator(xmlDoc));
                coreProps.SetDescriptionProperty(LoadDescription(xmlDoc));
                coreProps.SetIdentifierProperty(LoadIdentifier(xmlDoc));
                coreProps.SetKeywordsProperty(LoadKeywords(xmlDoc));
                coreProps.SetLanguageProperty(LoadLanguage(xmlDoc));
                coreProps.SetLastModifiedByProperty(LoadLastModifiedBy(xmlDoc));
                coreProps.SetLastPrintedProperty(LoadLastPrinted(xmlDoc));
                coreProps.SetModifiedProperty(LoadModified(xmlDoc));
                coreProps.SetRevisionProperty(LoadRevision(xmlDoc));
                coreProps.SetSubjectProperty(LoadSubject(xmlDoc));
                coreProps.SetTitleProperty(LoadTitle(xmlDoc));
                coreProps.SetVersionProperty(LoadVersion(xmlDoc));
            }
            return(coreProps);
        }
コード例 #14
0
        public static DataTable ReadDBF(string dbfFile, ZipHelper _ziphelper, char DirSeperator)
        {
            long         start = DateTime.Now.Ticks;
            DataTable    dt    = new DataTable();
            BinaryReader recReader;
            DataRow      row;
            int          fieldIndex;

            // If there isn't even a file, just return an empty DataTable
            if ((false == _ziphelper.FileExists(dbfFile)))
            {
                return(dt);
            }

            BinaryReader br = null;

            openMemoFile(dbfFile, _ziphelper, DirSeperator);

            readMDXFile(dbfFile, _ziphelper, DirSeperator);
            //Dictionary<int, byte[]> memoLookup = ReadDBT(dbfFile);

            try
            {
                // Read the header into a buffer
                //br = new BinaryReader(new FileStream(dbfFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

                Stream tmpStream = _ziphelper.GetReadStream(dbfFile);
                br = new BinaryReader(tmpStream);
                byte[] completeBuffer = br.ReadBytes((int)_ziphelper.GetStreamLength(dbfFile, tmpStream));
                tmpStream.Close();
                br.Close();
                br = new BinaryReader(new MemoryStream(completeBuffer));

                byte[] buffer = br.ReadBytes(Marshal.SizeOf(typeof(DBFHeader)));


                // Marshall the header into a DBFHeader structure
                GCHandle  handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                DBFHeader header = (DBFHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBFHeader));
                handle.Free();

                // Read in all the field descriptors. Per the spec, 13 (0D) marks the end of the field descriptors
                ArrayList fields = new ArrayList();

                while ((13 != br.PeekChar()))
                {
                    buffer = br.ReadBytes(Marshal.SizeOf(typeof(FieldDescriptor)));
                    handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                    fields.Add((FieldDescriptor)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FieldDescriptor)));
                    handle.Free();
                }

                // Read in the first row of records, we need this to help determine column types below
                (br.BaseStream).Seek(header.headerLen + 1, SeekOrigin.Begin);
                buffer    = br.ReadBytes(header.recordLen);
                recReader = new BinaryReader(new MemoryStream(buffer));

                // Create the columns in our new DataTable
                DataColumn col = null;

                dt.Columns.Add(new DataColumn("DELETED_FLAG", typeof(bool)));

                foreach (FieldDescriptor field in fields)
                {
                    byte[] NumberByteArray = recReader.ReadBytes(field.fieldLen);
                    switch (field.fieldType)
                    {
                    case dBaseType.N:
                        if (dBaseConverter.N_IsDecimal(NumberByteArray))
                        {
                            col = new DataColumn(field.fieldName, typeof(decimal));
                        }
                        else
                        {
                            col = new DataColumn(field.fieldName, typeof(int));
                        }
                        break;

                    case dBaseType.C:
                        col = new DataColumn(field.fieldName, typeof(string));
                        break;

                    case dBaseType.T:
                        col = new DataColumn(field.fieldName, typeof(DateTime));
                        break;

                    case dBaseType.D:
                        col = new DataColumn(field.fieldName, typeof(DateTime));
                        break;

                    case dBaseType.L:
                        col = new DataColumn(field.fieldName, typeof(bool));
                        break;

                    case dBaseType.F:
                        col = new DataColumn(field.fieldName, typeof(Double));
                        break;

                    case dBaseType.M:
                        //Field Type Memo...
                        col = new DataColumn(field.fieldName, typeof(byte[]));
                        break;
                    }
                    dt.Columns.Add(col);
                }

                // Skip past the end of the header.
                (br.BaseStream).Seek(header.headerLen, SeekOrigin.Begin);

                // Read in all the records
                for (int counter = 0; counter <= header.numRecords - 1; counter++)
                {
                    // First we'll read the entire record into a buffer and then read each field from the buffer
                    // This helps account for any extra space at the end of each record and probably performs better
                    buffer    = br.ReadBytes(header.recordLen);
                    recReader = new BinaryReader(new MemoryStream(buffer));

                    // All dbf field records begin with a deleted flag field. Deleted - 0x2A (asterisk) else 0x20 (space)
                    //if (recReader.ReadChar() == '*')
                    //{
                    //	continue;
                    //}


                    // Loop through each field in a record
                    fieldIndex = 0;
                    row        = dt.NewRow();

                    char delflg = recReader.ReadChar();
                    if (delflg == '*')
                    {
                        row[0] = true;
                    }
                    else
                    {
                        row[0] = false;
                    }


                    foreach (FieldDescriptor field in fields)
                    {
                        switch (field.fieldType)
                        {
                        case dBaseType.N:      // Number
                            byte[] NumberBytes = recReader.ReadBytes(field.fieldLen);
                            if (dBaseConverter.N_IsDecimal(NumberBytes))
                            {
                                row[fieldIndex + 1] = dBaseConverter.N_ToDecimal(NumberBytes);
                            }
                            else
                            {
                                row[fieldIndex + 1] = dBaseConverter.N_ToInt(NumberBytes);
                            }
                            break;

                        case dBaseType.C:     // String
                            row[fieldIndex + 1] = dBaseConverter.C_ToString(recReader.ReadBytes(field.fieldLen));
                            break;

                        case dBaseType.M:     // Memo
                            row[fieldIndex + 1] = ReadMemoBlock(dBaseConverter.N_ToInt(recReader.ReadBytes(field.fieldLen)));
                            break;

                        case dBaseType.D:     // Date (YYYYMMDD)
                            DateTime DTFromFile = dBaseConverter.D_ToDateTime(recReader.ReadBytes(8));
                            if (DTFromFile == DateTime.MinValue)
                            {
                                row[fieldIndex + 1] = System.DBNull.Value;
                            }
                            else
                            {
                                row[fieldIndex] = DTFromFile;
                            }
                            break;

                        case dBaseType.T:
                            row[fieldIndex + 1] = dBaseConverter.T_ToDateTime(recReader.ReadBytes(8));
                            break;

                        case dBaseType.L:     // Boolean (Y/N)
                            row[fieldIndex + 1] = dBaseConverter.L_ToBool(recReader.ReadByte());
                            break;

                        case dBaseType.F:
                            row[fieldIndex + 1] = dBaseConverter.F_ToDouble(recReader.ReadBytes(field.fieldLen));
                            break;
                        }
                        fieldIndex++;
                    }

                    recReader.Close();
                    dt.Rows.Add(row);
                }
            }

            catch
            {
                throw;
            }
            finally
            {
                if (null != br)
                {
                    br.Close();
                }

                if (dbtReader != null)
                {
                    dbtReader.Close();
                    dbtReader = null;
                }
            }

            long count = DateTime.Now.Ticks - start;

            return(dt);
        }
コード例 #15
0
        //This function should wite a MDX file with the specified indexes.!

        /* private static void writeMDXFile(string dbfFile, indexes)
         * {
         *
         * }*/
        #endregion

        #region DBF-Write-Functions
        /// <summary>
        /// This Function Writes directly to a DBF File.
        /// It reads the Field list, and writes to the correct position.
        /// To access the deleted flag, use DELETED_FLAG as column Name
        /// </summary>
        /// <param name="dbfFile"></param>
        /// <param name="column"></param>
        /// <param name="row"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool WriteValue(string dbfFile, string column, int row, object value, ZipHelper _ziphelper, char DirSeperator)
        {
            //if (zipfile != null)
            //    throw new Exception("Write to Zipped Files is not supported!");

            int  BytesToRecordStart = 0;
            long start = DateTime.Now.Ticks;

            // If there isn't even a file, just return an empty DataTable
            if ((false == _ziphelper.FileExists(dbfFile)))
            {
                return(false);
            }

            BinaryReader br = null;
            BinaryWriter bw = null;

            try
            {
                // Read the header into a buffer
                Stream tmpStream = _ziphelper.GetReadStream(dbfFile);
                br = new BinaryReader(tmpStream);
                byte[] completeBuffer = br.ReadBytes((int)_ziphelper.GetStreamLength(dbfFile, tmpStream));
                tmpStream.Close();
                br.Close();
                br = new BinaryReader(new MemoryStream(completeBuffer));

                byte[] buffer = br.ReadBytes(Marshal.SizeOf(typeof(DBFHeader)));


                // Marshall the header into a DBFHeader structure
                GCHandle  handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                DBFHeader header = (DBFHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBFHeader));
                handle.Free();

                // Read in all the field descriptors. Per the spec, 13 (0D) marks the end of the field descriptors
                ArrayList fields = new ArrayList();

                while ((13 != br.PeekChar()))
                {
                    buffer = br.ReadBytes(Marshal.SizeOf(typeof(FieldDescriptor)));
                    handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                    fields.Add((FieldDescriptor)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FieldDescriptor)));
                    handle.Free();
                }


                char writeFieldType   = ' ';
                int  writeFieldLength = 0;
                foreach (FieldDescriptor field in fields)
                {
                    writeFieldType   = (char)field.fieldType;
                    writeFieldLength = field.fieldLen;
                    if (field.fieldName == column)
                    {
                        break;
                    }
                    BytesToRecordStart += field.fieldLen;
                }

                br.Close();

                Stream strm = _ziphelper.GetWriteStream(dbfFile);
                bw = new BinaryWriter(strm);

                if (column != "DELETED_FLAG")
                {
                    BytesToRecordStart++;
                }
                else
                {
                    BytesToRecordStart = 0;
                }

                (/*(FileStream)*/ bw.BaseStream).Seek(header.headerLen + row * header.recordLen + BytesToRecordStart, SeekOrigin.Begin);

                if (column == "DELETED_FLAG")
                {
                    if ((bool)value == true)
                    {
                        bw.Write(Encoding.ASCII.GetBytes("*"));
                    }
                    else
                    {
                        bw.Write(Encoding.ASCII.GetBytes(" "));
                    }
                }
                else
                {
                    /*
                     * number = Encoding.ASCII.GetString(recReader.ReadBytes(field.fieldLen));
                     * switch (field.fieldType)
                     * {
                     *  case (byte)'N':
                     *      if (number.IndexOf(".") > -1)
                     *      {
                     *          col = new DataColumn(field.fieldName, typeof(decimal));
                     *      }
                     *      else
                     *      {
                     *          col = new DataColumn(field.fieldName, typeof(int));
                     *      }
                     *      break;
                     *  case (byte)'C':
                     *      col = new DataColumn(field.fieldName, typeof(string));
                     *      break;
                     *  case (byte)'T':
                     *      // You can uncomment this to see the time component in the grid
                     *      //col = new DataColumn(field.fieldName, typeof(string));
                     *      col = new DataColumn(field.fieldName, typeof(DateTime));
                     *      break;
                     *  case (byte)'D':
                     *      col = new DataColumn(field.fieldName, typeof(DateTime));
                     *      break;
                     *  case (byte)'L':
                     *      col = new DataColumn(field.fieldName, typeof(bool));
                     *      break;
                     *  case (byte)'F':
                     *      col = new DataColumn(field.fieldName, typeof(Double));
                     *      break;
                     *  case (byte)'M':
                     *      //Field Type Memo...
                     *      col = new DataColumn(field.fieldName, typeof(byte[]));
                     *      //col = new DataColumn(field.fieldName, typeof(string));
                     *      break;
                     * }*/


                    switch (writeFieldType)
                    {
                    case 'N':
                        bw.Write(Encoding.ASCII.GetBytes(value.ToString().PadLeft(writeFieldLength, ' ')));
                        break;

                    case 'C':
                        bw.Write(Encoding.ASCII.GetBytes(value.ToString().PadRight(writeFieldLength, ' ')));
                        break;

                    default:
                        //br.Close();
                        return(false);

                        break;
                    }
                }

                _ziphelper.WriteBackStream(dbfFile, strm);

                bw.Close();
            }
            finally
            {
                if (br != null)
                {
                    br.Close();
                }
                if (bw != null)
                {
                    bw.Close();
                }
            }

            return(true);
        }
コード例 #16
0
ファイル: XASdkTests.cs プロジェクト: wengst/xamarin-android
        public void DotNetBuild(string runtimeIdentifiers, bool isRelease)
        {
            var proj = new XASdkProject {
                IsRelease = isRelease
            };

            proj.OtherBuildItems.Add(new AndroidItem.InputJar("javaclasses.jar")
            {
                BinaryContent = () => Convert.FromBase64String(InlineData.JavaClassesJarBase64)
            });
            // TODO: bring back when Xamarin.Android.Bindings.Documentation.targets is working
            //proj.OtherBuildItems.Add (new BuildItem ("JavaSourceJar", "javasources.jar") {
            //	BinaryContent = () => Convert.FromBase64String (InlineData.JavaSourcesJarBase64)
            //});
            if (!runtimeIdentifiers.Contains(";"))
            {
                proj.SetProperty(KnownProperties.RuntimeIdentifier, runtimeIdentifiers);
            }
            else
            {
                proj.SetProperty(KnownProperties.RuntimeIdentifiers, runtimeIdentifiers);
            }

            var dotnet = CreateDotNetBuilder(proj);

            Assert.IsTrue(dotnet.Build(), "`dotnet build` should succeed");

            // TODO: run for release once illink warnings are gone
            // context: https://github.com/xamarin/xamarin-android/issues/4708
            if (!isRelease)
            {
                Assert.IsTrue(StringAssertEx.ContainsText(dotnet.LastBuildOutput, " 0 Warning(s)"), "Should have no MSBuild warnings.");
            }

            var outputPath = Path.Combine(Root, dotnet.ProjectDirectory, proj.OutputPath);

            if (!runtimeIdentifiers.Contains(";"))
            {
                outputPath = Path.Combine(outputPath, runtimeIdentifiers);
            }
            var assemblyPath = Path.Combine(outputPath, "UnnamedProject.dll");

            FileAssert.Exists(assemblyPath);
            using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath)) {
                var typeName = "Com.Xamarin.Android.Test.Msbuildtest.JavaSourceJarTest";
                var type     = assembly.MainModule.GetType(typeName);
                Assert.IsNotNull(type, $"{assemblyPath} should contain {typeName}");
            }

            var apk = Path.Combine(outputPath, "UnnamedProject.UnnamedProject.apk");

            FileAssert.Exists(apk);
            using (var zip = ZipHelper.OpenZip(apk)) {
                var rids = runtimeIdentifiers.Split(';');
                foreach (var abi in rids.Select(MonoAndroidHelper.RuntimeIdentifierToAbi))
                {
                    Assert.IsTrue(zip.ContainsEntry($"lib/{abi}/libmonodroid.so"), "libmonodroid.so should exist.");
                    Assert.IsTrue(zip.ContainsEntry($"lib/{abi}/libmonosgen-2.0.so"), "libmonosgen-2.0.so should exist.");
                    if (rids.Length > 1)
                    {
                        Assert.IsTrue(zip.ContainsEntry($"assemblies/{abi}/System.Private.CoreLib.dll"), "System.Private.CoreLib.dll should exist.");
                    }
                    else
                    {
                        Assert.IsTrue(zip.ContainsEntry("assemblies/System.Private.CoreLib.dll"), "System.Private.CoreLib.dll should exist.");
                    }
                }
            }
        }
コード例 #17
0
    // 开始解压缩
    public void StartDecompress()
    {
        UpdateStageResult.DownLoad.IsEnable    = false;
        UpdateStageResult.Compression.IsEnable = true;
        UpdateStageResult.Compression.ClearAll();

        var deItr = _decompress_queue.GetEnumerator();

        while (deItr.MoveNext())
        {
            UpdateStageResult.Compression.TotalSize += deItr.Current.TotalSize;
            UpdateStageResult.Compression.FileCount++;
        }
        deItr.Dispose();

        string localPath = AssetsCommon.LocalAssetPath;

        if (!Directory.Exists(localPath))
        {
            Directory.CreateDirectory(localPath);
        }

        AssetDownInfo[] tempDatas = new AssetDownInfo[_decompress_queue.Count];
        for (int i = 0; i < tempDatas.Length; i++)
        {
            int index = _decompress_queue[i].Index;
            tempDatas[index] = _decompress_queue[i];
        }

        for (int i = 0; i < tempDatas.Length; i++)
        {
            AssetDownInfo downInfo = tempDatas[i];

            string zipFileName = string.Format("{0}/{1}", localPath, downInfo.AssetName);
            List <AssetDataInfo> assetNames = ZipHelper.Decompress(
                zipFileName,
                localPath);

            AssetDataInfo dataInfo = downInfo.ToAssetDataInfo();
            dataInfo.IsCompressed = true;

            UpdateStageResult.Compression.CurrentCount++;
            FileManifestManager.UpdateLocalFenBaoData(dataInfo);

            for (int j = 0; j < assetNames.Count; j++)
            {
                FileManifestManager.UpdateLocalABData(assetNames[j]);
            }

            if (File.Exists(zipFileName))
            {
                File.Delete(zipFileName);
            }
        }

        UpdateStageResult.Compression.IsEnable = false;

        if (_owner.IsDownLoadAllVersion)
        {
            FileManifestManager.WriteFenBaoDataByServer();
        }
        else
        {
            FileManifestManager.WriteFenBaoDataByCurrent();
        }

        FileManifestManager.WriteABDataByCurrent();
    }
コード例 #18
0
        public void InstallWithoutSharedRuntime()
        {
            AssertCommercialBuild();
            AssertHasDevices();

            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease = true,
            };

            proj.SetProperty(proj.ReleaseProperties, "Optimize", false);
            proj.SetProperty(proj.ReleaseProperties, "DebugType", "none");
            proj.SetProperty(proj.ReleaseProperties, "AndroidUseSharedRuntime", false);
            proj.RemoveProperty(proj.ReleaseProperties, "EmbedAssembliesIntoApk");
            var abis = new [] { "armeabi-v7a", "x86" };

            proj.SetAndroidSupportedAbis(abis);
            using (var builder = CreateApkBuilder(Path.Combine("temp", TestContext.CurrentContext.Test.Name), false, false)) {
                builder.Verbosity = LoggerVerbosity.Diagnostic;
                if (RunAdbCommand("shell pm list packages Mono.Android.DebugRuntime").Trim().Length != 0)
                {
                    RunAdbCommand("uninstall Mono.Android.DebugRuntime");
                }
                Assert.IsTrue(builder.Install(proj));
                var runtimeInfo = builder.GetSupportedRuntimes();
                var apkPath     = Path.Combine(Root, builder.ProjectDirectory,
                                               proj.IntermediateOutputPath, "android", "bin", "UnnamedProject.UnnamedProject.apk");
                using (var apk = ZipHelper.OpenZip(apkPath)) {
                    foreach (var abi in abis)
                    {
                        var runtime = runtimeInfo.FirstOrDefault(x => x.Abi == abi && x.Runtime == "debug");
                        Assert.IsNotNull(runtime, "Could not find the expected runtime.");
                        var inApk        = ZipHelper.ReadFileFromZip(apk, String.Format("lib/{0}/{1}", abi, runtime.Name));
                        var inApkRuntime = runtimeInfo.FirstOrDefault(x => x.Abi == abi && x.Size == inApk.Length);
                        Assert.IsNotNull(inApkRuntime, "Could not find the actual runtime used.");
                        Assert.AreEqual(runtime.Size, inApkRuntime.Size, "expected {0} got {1}", "debug", inApkRuntime.Runtime);
                    }
                }
                //FIXME: https://github.com/xamarin/androidtools/issues/141
                //Assert.AreEqual (0, RunAdbCommand ("shell pm list packages Mono.Android.DebugRuntime").Trim ().Length,
                //	"The Shared Runtime should not have been installed.");
                var overrideDirs = new string [] {
                    $"/data/data/{proj.PackageName}/files/.__override__",
                    $"/storage/emulated/0/Android/data/{proj.PackageName}/files/.__override__",
                    $"/mnt/shell/emulated/0/Android/data/{proj.PackageName}/files/.__override__",
                    $"/storage/sdcard/Android/data/{proj.PackageName}/files/.__override__",
                };
                var directorylist = string.Empty;
                foreach (var dir in overrideDirs)
                {
                    var listing = RunAdbCommand($"shell ls {dir}");
                    if (!listing.Contains("No such file or directory"))
                    {
                        directorylist += listing;
                    }
                }
                StringAssert.Contains($"{proj.ProjectName}.dll", directorylist, $"{proj.ProjectName}.dll should exist in the .__override__ directory.");
                StringAssert.Contains($"System.dll", directorylist, $"System.dll should exist in the .__override__ directory.");
                StringAssert.Contains($"Mono.Android.dll", directorylist, $"Mono.Android.dll should exist in the .__override__ directory.");
            }
        }
コード例 #19
0
        public void CheckMetadataSkipItemsAreProcessedCorrectly()
        {
            var packages = new List <Package> ()
            {
                KnownPackages.Android_Arch_Core_Common_26_1_0,
                KnownPackages.Android_Arch_Lifecycle_Common_26_1_0,
                KnownPackages.Android_Arch_Lifecycle_Runtime_26_1_0,
                KnownPackages.AndroidSupportV4_27_0_2_1,
                KnownPackages.SupportCompat_27_0_2_1,
                KnownPackages.SupportCoreUI_27_0_2_1,
                KnownPackages.SupportCoreUtils_27_0_2_1,
                KnownPackages.SupportDesign_27_0_2_1,
                KnownPackages.SupportFragment_27_0_2_1,
                KnownPackages.SupportMediaCompat_27_0_2_1,
                KnownPackages.SupportV7AppCompat_27_0_2_1,
                KnownPackages.SupportV7CardView_27_0_2_1,
                KnownPackages.SupportV7MediaRouter_27_0_2_1,
                KnownPackages.SupportV7RecyclerView_27_0_2_1,
                KnownPackages.VectorDrawable_27_0_2_1,
                new Package()
                {
                    Id = "Xamarin.Android.Support.Annotations", Version = "27.0.2.1"
                },
                new Package()
                {
                    Id = "Xamarin.Android.Support.Transition", Version = "27.0.2.1"
                },
                new Package()
                {
                    Id = "Xamarin.Android.Support.v7.Palette", Version = "27.0.2.1"
                },
                new Package()
                {
                    Id = "Xamarin.Android.Support.Animated.Vector.Drawable", Version = "27.0.2.1"
                },
            };

            string metaDataTemplate = @"<AndroidCustomMetaDataForReferences Include=""%"">
	<AndroidSkipAddToPackage>True</AndroidSkipAddToPackage>
	<AndroidSkipJavaStubGeneration>True</AndroidSkipJavaStubGeneration>
	<AndroidSkipResourceExtraction>True</AndroidSkipResourceExtraction>
</AndroidCustomMetaDataForReferences>";
            var    proj             = new XamarinAndroidApplicationProject()
            {
                Imports =
                {
                    new Import(() => "CustomMetaData.target")
                    {
                        TextContent = () => @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemGroup>" +
                                      string.Join("\n", packages.Select(x => metaDataTemplate.Replace("%", x.Id))) +
                                      @"</ItemGroup>
</Project>"
                    },
                }
            };

            proj.SetProperty(proj.DebugProperties, "AndroidPackageNamingPolicy", "Lowercase");
            foreach (var package in packages)
            {
                proj.PackageReferences.Add(package);
            }
            using (var b = CreateApkBuilder(Path.Combine("temp", TestName))) {
                b.ThrowOnBuildFailure = false;
                b.Verbosity           = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic;
                Assert.IsTrue(b.Build(proj), "build failed");
                var bin = Path.Combine(Root, b.ProjectDirectory, proj.OutputPath);
                var obj = Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath);
                var lp  = Path.Combine(obj, "lp");
                Assert.IsTrue(Directory.Exists(lp), $"{lp} should exists.");
                Assert.AreEqual(0, Directory.GetDirectories(lp).Length, $"{lp} should NOT contain any directories.");
                var support = Path.Combine(obj, "android", "src", "android", "support");
                Assert.IsFalse(Directory.Exists(support), $"{support} should NOT exists.");
                Assert.IsFalse(File.Exists(lp), $" should NOT have been generated.");
                foreach (var apk in Directory.GetFiles(bin, "*-Signed.apk"))
                {
                    using (var zip = ZipHelper.OpenZip(apk)) {
                        foreach (var package in packages)
                        {
                            Assert.IsFalse(zip.Any(e => e.FullName == $"assemblies/{package.Id}.dll"), $"APK file `{apk}` should not contain {package.Id}");
                        }
                    }
                }
            }
        }
コード例 #20
0
    public static bool GenerateBinPatches()
    {
        string assetBinDataPath       = EXPORTED_ASSETS_PATH + "/bin/Data/";
        string patchTopPath           = PROJECT_DIR + "/AllAndroidPatchFiles/";
        string assertBinDataPatchPath = patchTopPath + "/assets_bin_Data/";

        if (Directory.Exists(patchTopPath))
        {
            FileUtil.DeleteFileOrDirectory(patchTopPath);
        }
        Directory.CreateDirectory(assertBinDataPatchPath);

        string[][] soPatchFile =
        {
            // path_in_android_project, filename inside zip, zip file anme
            new string[3] {
                "/" + SO_DIR_NAME + "/armeabi-v7a/libil2cpp.so", "libil2cpp.so.new", "lib_armeabi-v7a_libil2cpp.so.zip"
            },
            new string[3] {
                "/" + SO_DIR_NAME + "/x86/libil2cpp.so", "libil2cpp.so.new", "lib_x86_libil2cpp.so.zip"
            },
#if UNITY_2018 || UNITY_2019
            new string[3] {
                "/" + SO_DIR_NAME + "/arm64-v8a/libil2cpp.so", "libil2cpp.so.new", "lib_arm64-v8a_libil2cpp.so.zip"
            },
#endif
        };

        for (int i = 0; i < soPatchFile.Length; i++)
        {
            string[] specialPaths        = soPatchFile[i];
            string   projectRelativePath = specialPaths[0];
            string   pathInZipFile       = specialPaths[1];
            string   zipFileName         = specialPaths[2];

            string projectFullPath = BUILD_SCRIPTS_PATH + projectRelativePath;
            ZipHelper.ZipFile(projectFullPath, pathInZipFile, patchTopPath + zipFileName, 9);
        }

        string[]      allAssetsBinDataFiles = Directory.GetFiles(assetBinDataPath, "*", SearchOption.AllDirectories);
        StringBuilder allZipCmds            = new StringBuilder();

        allZipCmds.AppendFormat("if not exist \"{0}\" (MD \"{0}\") \n", PROJECT_DIR + "/AllAndroidPatchFiles/");
        allZipCmds.AppendFormat("if not exist \"{0}\" (MD \"{0}\") \n", PROJECT_DIR + "/AllAndroidPatchFiles/assets_bin_Data/");
        foreach (string apk_file in allAssetsBinDataFiles)
        {
            string relativePathHeader = "assets/bin/Data/";
            int    relativePathStart  = apk_file.IndexOf(relativePathHeader);
            string filenameInZip      = apk_file.Substring(relativePathStart);                                                //file: assets/bin/Data/xxx/xxx
            string relativePath       = apk_file.Substring(relativePathStart + relativePathHeader.Length).Replace('\\', '/'); //file: xxx/xxx
            string zipFileName        = relativePath.Replace("/", "__").Replace("\\", "__") + ".bin";                         //file: xxx__xxx.bin

            allZipCmds.AppendFormat("cd {0} && {1} -8 \"{2}\" \"{3}\"\n", BUILD_SCRIPTS_PATH, ZIP_PATH, PROJECT_DIR + "/AllAndroidPatchFiles/assets_bin_Data/" + zipFileName, filenameInZip);
        }
        allZipCmds.Append("sleep 1\n");
        allZipCmds.AppendFormat("cd {0} && {1} -9 -r \"{2}\" \"{3}\"\n", patchTopPath, ZIP_PATH, PROJECT_DIR + "/AllAndroidPatchFiles_Versionx.zip", "*");

        if (allZipCmds.Length > 0)
        {
            string zipPatchesFile = BUILD_SCRIPTS_PATH + "/" + "zip_patches.bat";
            File.WriteAllText(zipPatchesFile, allZipCmds.ToString());
            if (!Exec(zipPatchesFile, zipPatchesFile))
            {
                Debug.LogError("exec failed:" + zipPatchesFile);
                return(false);
            }
        }
        return(true);
    }
コード例 #21
0
        public void CheckSignApk([Values(true, false)] bool useApkSigner, [Values(true, false)] bool perAbiApk)
        {
            string ext            = Environment.OSVersion.Platform != PlatformID.Unix ? ".bat" : "";
            var    foundApkSigner = Directory.EnumerateDirectories(Path.Combine(AndroidSdkPath, "build-tools")).Any(dir => Directory.EnumerateFiles(dir, "apksigner" + ext).Any());

            if (useApkSigner && !foundApkSigner)
            {
                Assert.Ignore("Skipping test. Required build-tools verison which contains apksigner is not installed.");
            }
            string keyfile = Path.Combine(Root, "temp", TestName, "release.keystore");

            if (File.Exists(keyfile))
            {
                File.Delete(keyfile);
            }
            var androidSdk     = new AndroidSdkInfo((level, message) => {
            }, AndroidSdkPath, AndroidNdkPath);
            string keyToolPath = Path.Combine(androidSdk.JavaSdkPath, "bin");
            var    engine      = new MockBuildEngine(Console.Out);
            string pass        = "******";
            var    task        = new AndroidCreateDebugKey {
                BuildEngine  = engine,
                KeyStore     = keyfile,
                StorePass    = pass,
                KeyAlias     = "releasestore",
                KeyPass      = pass,
                KeyAlgorithm = "RSA",
                Validity     = 30,
                StoreType    = "pkcs12",
                Command      = "-genkeypair",
                ToolPath     = keyToolPath,
            };

            Assert.IsTrue(task.Execute(), "Task should have succeeded.");
            var proj = new XamarinAndroidApplicationProject()
            {
                IsRelease = true,
            };

            if (useApkSigner)
            {
                proj.SetProperty("AndroidUseApkSigner", "true");
            }
            else
            {
                proj.RemoveProperty("AndroidUseApkSigner");
            }
            proj.SetProperty(proj.ReleaseProperties, "AndroidKeyStore", "True");
            proj.SetProperty(proj.ReleaseProperties, "AndroidSigningKeyStore", keyfile);
            proj.SetProperty(proj.ReleaseProperties, "AndroidSigningKeyAlias", "releasestore");
            proj.SetProperty(proj.ReleaseProperties, "AndroidSigningKeyPass", pass);
            proj.SetProperty(proj.ReleaseProperties, "AndroidSigningStorePass", pass);
            proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, perAbiApk);
            proj.SetAndroidSupportedAbis("armeabi-v7a", "x86");
            using (var b = CreateApkBuilder(Path.Combine("temp", TestContext.CurrentContext.Test.Name))) {
                var bin = Path.Combine(Root, b.ProjectDirectory, proj.OutputPath);
                Assert.IsTrue(b.Build(proj), "First build failed");
                Assert.IsTrue(StringAssertEx.ContainsText(b.LastBuildOutput, " 0 Warning(s)"),
                              "First build should not contain warnings!  Contains\n" +
                              string.Join("\n", b.LastBuildOutput.Where(line => line.Contains("warning"))));

                //Make sure the APKs are signed
                foreach (var apk in Directory.GetFiles(bin, "*-Signed.apk"))
                {
                    using (var zip = ZipHelper.OpenZip(apk)) {
                        Assert.IsTrue(zip.Any(e => e.FullName == "META-INF/MANIFEST.MF"), $"APK file `{apk}` is not signed! It is missing `META-INF/MANIFEST.MF`.");
                    }
                }

                var item = proj.AndroidResources.First(x => x.Include() == "Resources\\values\\Strings.xml");
                item.TextContent = () => proj.StringsXml.Replace("${PROJECT_NAME}", "Foo");
                item.Timestamp   = null;
                Assert.IsTrue(b.Build(proj), "Second build failed");
                Assert.IsTrue(StringAssertEx.ContainsText(b.LastBuildOutput, " 0 Warning(s)"),
                              "Second build should not contain warnings!  Contains\n" +
                              string.Join("\n", b.LastBuildOutput.Where(line => line.Contains("warning"))));

                //Make sure the APKs are signed
                foreach (var apk in Directory.GetFiles(bin, "*-Signed.apk"))
                {
                    using (var zip = ZipHelper.OpenZip(apk)) {
                        Assert.IsTrue(zip.Any(e => e.FullName == "META-INF/MANIFEST.MF"), $"APK file `{apk}` is not signed! It is missing `META-INF/MANIFEST.MF`.");
                    }
                }
            }
        }
コード例 #22
0
        public void CheckAssetsAreIncludedInAPK([Values(true, false)] bool useAapt2)
        {
            AssertAaptSupported(useAapt2);
            var projectPath = Path.Combine("temp", TestName);
            var libproj     = new XamarinAndroidLibraryProject()
            {
                ProjectName     = "Library1",
                IsRelease       = true,
                OtherBuildItems =
                {
                    new AndroidItem.AndroidAsset("Assets\\asset1.txt")
                    {
                        TextContent = () => "Asset1",
                        Encoding    = Encoding.ASCII,
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\")
                    {
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\asset2.txt")
                    {
                        TextContent = () => "Asset2",
                        Encoding    = Encoding.ASCII,
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\asset5.txt")
                    {
                        TextContent = () => "Asset5",
                        Encoding    = Encoding.ASCII,
                        Metadata    = { { "LogicalName", Path.Combine(Path.GetPathRoot(Root), "Assets", "subfolder", "asset5.txt") } },
                    },
                }
            };
            var proj = new XamarinAndroidApplicationProject()
            {
                ProjectName     = "App1",
                IsRelease       = true,
                OtherBuildItems =
                {
                    new AndroidItem.AndroidAsset("Assets\\asset3.txt")
                    {
                        TextContent = () => "Asset3",
                        Encoding    = Encoding.ASCII,
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\")
                    {
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\asset4.txt")
                    {
                        TextContent = () => "Asset4",
                        Encoding    = Encoding.ASCII,
                    },
                    new AndroidItem.AndroidAsset("Assets\\subfolder\\asset6.txt")
                    {
                        TextContent = () => "Asset6",
                        Encoding    = Encoding.ASCII,
                        Metadata    = { { "LogicalName", Path.Combine(Path.GetPathRoot(Root), "Assets", "subfolder", "asset6.txt") } },
                    },
                }
            };

            proj.AndroidUseAapt2 = useAapt2;
            proj.References.Add(new BuildItem("ProjectReference", "..\\Library1\\Library1.csproj"));
            using (var libb = CreateDllBuilder(Path.Combine(projectPath, libproj.ProjectName))) {
                Assert.IsTrue(libb.Build(libproj), "{0} should have built successfully.", libproj.ProjectName);
                using (var b = CreateApkBuilder(Path.Combine(projectPath, proj.ProjectName))) {
                    Assert.IsTrue(b.Build(proj), "{0} should have built successfully.", proj.ProjectName);
                    using (var apk = ZipHelper.OpenZip(Path.Combine(Root, b.ProjectDirectory, proj.IntermediateOutputPath, "android", "bin", "UnnamedProject.UnnamedProject.apk"))) {
                        foreach (var a in libproj.OtherBuildItems.Where(x => x is AndroidItem.AndroidAsset))
                        {
                            var item = a.Include().ToLower().Replace("\\", "/");
                            if (item.EndsWith("/"))
                            {
                                continue;
                            }
                            var data = ZipHelper.ReadFileFromZip(apk, item);
                            Assert.IsNotNull(data, "{0} should be in the apk.", item);
                            Assert.AreEqual(a.TextContent(), Encoding.ASCII.GetString(data), "The Contents of {0} should be \"{1}\"", item, a.TextContent());
                        }
                        foreach (var a in proj.OtherBuildItems.Where(x => x is AndroidItem.AndroidAsset))
                        {
                            var item = a.Include().ToLower().Replace("\\", "/");
                            if (item.EndsWith("/"))
                            {
                                continue;
                            }
                            var data = ZipHelper.ReadFileFromZip(apk, item);
                            Assert.IsNotNull(data, "{0} should be in the apk.", item);
                            Assert.AreEqual(a.TextContent(), Encoding.ASCII.GetString(data), "The Contents of {0} should be \"{1}\"", item, a.TextContent());
                        }
                    }
                    Directory.Delete(Path.Combine(Root, projectPath), recursive: true);
                }
            }
        }
コード例 #23
0
        public void NetStandardReferenceTest()
        {
            var netStandardProject = new DotNetStandard()
            {
                ProjectName           = "XamFormsSample",
                ProjectGuid           = Guid.NewGuid().ToString(),
                Sdk                   = "Microsoft.NET.Sdk",
                TargetFramework       = "netstandard1.4",
                IsRelease             = true,
                PackageTargetFallback = "portable-net45+win8+wpa81+wp8",
                PackageReferences     =
                {
                    KnownPackages.XamarinForms_2_3_4_231,
                    new Package()
                    {
                        Id      = "System.IO.Packaging",
                        Version = "4.4.0",
                    },
                    new Package()
                    {
                        Id      = "Newtonsoft.Json",
                        Version = "10.0.3"
                    },
                },
                OtherBuildItems =
                {
                    new BuildItem("None")
                    {
                        Remove = () => "**\\*.xaml",
                    },
                    new BuildItem("Compile")
                    {
                        Update        = () => "**\\*.xaml.cs",
                        DependentUpon = () => "%(Filename)"
                    },
                    new BuildItem("EmbeddedResource")
                    {
                        Include   = () => "**\\*.xaml",
                        SubType   = () => "Designer",
                        Generator = () => "MSBuild:UpdateDesignTimeXaml",
                    },
                },
                Sources =
                {
                    new BuildItem.Source("App.xaml.cs")
                    {
                        TextContent = () => @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO.Packaging;

using Xamarin.Forms;

namespace XamFormsSample
{
    public partial class App : Application
    {
        Package package;

        public App()
        {
            try {
                JsonConvert.DeserializeObject<string>(""test"");
                package = Package.Open ("""");
            } catch {
            }
            InitializeComponent();

            MainPage = new ContentPage ();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}",
                    },
                    new BuildItem.Source("App.xaml")
                    {
                        TextContent = () => @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Application xmlns=""http://xamarin.com/schemas/2014/forms""
             xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml""
             x:Class=""XamFormsSample.App"">
  <Application.Resources>
    <!-- Application resource dictionary -->
  </Application.Resources>
</Application>",
                    },
                },
            };

            var app = new XamarinAndroidApplicationProject()
            {
                ProjectName          = "App1",
                IsRelease            = true,
                UseLatestPlatformSdk = true,
                References           =
                {
                    new BuildItem.Reference("Mono.Android.Export"),
                    new BuildItem.ProjectReference($"..\\{netStandardProject.ProjectName}\\{netStandardProject.ProjectName}.csproj",
                                                   netStandardProject.ProjectName, netStandardProject.ProjectGuid),
                },
                PackageReferences =
                {
                    KnownPackages.SupportDesign_27_0_2_1,
                    KnownPackages.SupportV7CardView_27_0_2_1,
                    KnownPackages.AndroidSupportV4_27_0_2_1,
                    KnownPackages.SupportCoreUtils_27_0_2_1,
                    KnownPackages.SupportMediaCompat_27_0_2_1,
                    KnownPackages.SupportFragment_27_0_2_1,
                    KnownPackages.SupportCoreUI_27_0_2_1,
                    KnownPackages.SupportCompat_27_0_2_1,
                    KnownPackages.SupportV7AppCompat_27_0_2_1,
                    KnownPackages.SupportV7MediaRouter_27_0_2_1,
                    KnownPackages.XamarinForms_2_3_4_231,
                    new Package()
                    {
                        Id      = "System.Runtime.Loader",
                        Version = "4.3.0",
                    },
                }
            };

            app.MainActivity = @"using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using XamFormsSample;

namespace App1
{
	[Activity (Label = ""App1"", MainLauncher = true, Icon = ""@drawable/icon"")]
	public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
			protected override void OnCreate (Bundle bundle)
			{
				base.OnCreate (bundle);

				global::Xamarin.Forms.Forms.Init (this, bundle);

				LoadApplication (new App ());
			}
		}
	}"    ;
            app.SetAndroidSupportedAbis("x86", "armeabi-v7a");
            var expectedFiles = new string [] {
                "Java.Interop.dll",
                "Mono.Android.dll",
                "mscorlib.dll",
                "System.Core.dll",
                "System.dll",
                "System.Runtime.Serialization.dll",
                "System.IO.Packaging.dll",
                "System.IO.Compression.dll",
                "Mono.Android.Export.dll",
                "App1.dll",
                "FormsViewGroup.dll",
                "Xamarin.Android.Arch.Core.Common.dll",
                "Xamarin.Android.Arch.Lifecycle.Common.dll",
                "Xamarin.Android.Arch.Lifecycle.Runtime.dll",
                "Xamarin.Android.Support.Compat.dll",
                "Xamarin.Android.Support.Core.UI.dll",
                "Xamarin.Android.Support.Core.Utils.dll",
                "Xamarin.Android.Support.Design.dll",
                "Xamarin.Android.Support.Fragment.dll",
                "Xamarin.Android.Support.Media.Compat.dll",
                "Xamarin.Android.Support.v4.dll",
                "Xamarin.Android.Support.v7.AppCompat.dll",
                "Xamarin.Android.Support.Animated.Vector.Drawable.dll",
                "Xamarin.Android.Support.Vector.Drawable.dll",
                "Xamarin.Android.Support.Transition.dll",
                "Xamarin.Android.Support.v7.MediaRouter.dll",
                "Xamarin.Android.Support.v7.RecyclerView.dll",
                "Xamarin.Android.Support.Annotations.dll",
                "Xamarin.Android.Support.v7.CardView.dll",
                "Xamarin.Android.Support.v7.Palette.dll",
                "Xamarin.Forms.Core.dll",
                "Xamarin.Forms.Platform.Android.dll",
                "Xamarin.Forms.Platform.dll",
                "Xamarin.Forms.Xaml.dll",
                "XamFormsSample.dll",
                "Mono.Security.dll",
                "System.Xml.dll",
                "System.Net.Http.dll",
                "System.ServiceModel.Internals.dll",
                "Newtonsoft.Json.dll",
                "Microsoft.CSharp.dll",
                "System.Numerics.dll",
                "System.Xml.Linq.dll",
            };
            var path = Path.Combine("temp", TestContext.CurrentContext.Test.Name);

            using (var builder = CreateDllBuilder(Path.Combine(path, netStandardProject.ProjectName), cleanupOnDispose: false)) {
                using (var ab = CreateApkBuilder(Path.Combine(path, app.ProjectName), cleanupOnDispose: false)) {
                    Assert.IsTrue(builder.Build(netStandardProject), "XamFormsSample should have built.");
                    Assert.IsTrue(ab.Build(app), "App should have built.");
                    var apk = Path.Combine(Root, ab.ProjectDirectory,
                                           app.IntermediateOutputPath, "android", "bin", "UnnamedProject.UnnamedProject.apk");
                    using (var zip = ZipHelper.OpenZip(apk)) {
                        var existingFiles = zip.Where(a => a.FullName.StartsWith("assemblies/", StringComparison.InvariantCultureIgnoreCase));
                        var missingFiles  = expectedFiles.Where(x => !zip.ContainsEntry("assemblies/" + Path.GetFileName(x)));
                        Assert.IsFalse(missingFiles.Any(),
                                       string.Format("The following Expected files are missing. {0}",
                                                     string.Join(Environment.NewLine, missingFiles)));
                        var additionalFiles = existingFiles.Where(x => !expectedFiles.Contains(Path.GetFileName(x.FullName)));
                        Assert.IsTrue(!additionalFiles.Any(),
                                      string.Format("Unexpected Files found! {0}",
                                                    string.Join(Environment.NewLine, additionalFiles.Select(x => x.FullName))));
                    }
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// 根据数据表获取列,并且输出实体类文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetColumnByTable(HttpContext context)
        {
            try
            {
                crudHelper = new CRUDHelper <object>(HttpContext.Current.Session["strConnection"]?.ToString(), HttpContext.Current.Session["strType"]?.ToString());
                string table       = context.Request.Params["table"];
                Array  arr         = table.Split(',');
                string currentPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "WebForms\\CreateModel\\ModelFile";
                //清除文件夹中所有文件
                if (!FolderHelper.IsEmptyDirectory(currentPath))
                {
                    FolderHelper.DeleteFolder(currentPath, false);
                }

                foreach (string item in arr)
                {
                    string        sql        = $"select t.column_name names,t.comments,u.DATA_TYPE types from user_col_comments t join user_tab_cols u on t.column_name=u.COLUMN_NAME where t.table_name='{item}' and u.TABLE_NAME='{item}' order by u.INTERNAL_COLUMN_ID";
                    DataTable     data       = crudHelper.SelectBySQL(sql);
                    string        className  = item.ToUpper();
                    StringBuilder classStr   = new StringBuilder();
                    bool          isIdentity = true;
                    classStr.Append(" using DotNet.Utils;\n");
                    classStr.Append(" using System;\n");
                    classStr.Append(" namespace Models\n{\n");
                    classStr.Append("  /// <summary>\n/// " + item + "\n/// </summary>\n");
                    classStr.Append("  public  class " + className + "\n{\n");

                    foreach (DataRow dr in data?.Rows)
                    {
                        TempTable tt = new TempTable()
                        {
                            names    = dr["NAMES"].ToString(),
                            types    = dr["TYPES"].ToString(),
                            comments = dr["COMMENTS"].ToString()
                        };
                        classStr.Append("  /// <summary>\n/// " + tt.comments + "\n/// </summary>\n");
                        if (isIdentity)
                        {
                            classStr.Append("[Column(Identity =true)]\n");
                            isIdentity = false;
                        }
                        classStr.Append("  public  " + GetModelType(tt.types) + tt.names + " { get; set; }\n\n");
                    }
                    classStr.Append(" }\n");
                    classStr.Append("public class " + className + "Manage : CRUDHelper<" + className + ">\n{ \n}\n");
                    classStr.Append(" }\n");
                    string path = currentPath + "\\" + className + ".cs";
                    FileHelper.Write(path, classStr.ToString());
                }
                string err  = "";
                bool   bZip = ZipHelper.ZipFile(currentPath, currentPath + "\\Model.Zip", out err);
                if (bZip)
                {
                    return("1");
                }
                else
                {
                    return(err);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                return(ex.Message);
            }
        }
コード例 #25
0
        /**
         * Save this package into the specified stream
         *
         *
         * @param outputStream
         *            The stream use to save this package.
         *
         * @see #save(OutputStream)
         */

        protected override void SaveImpl(Stream outputStream)
        {
            // Check that the document was open in write mode
            ThrowExceptionIfReadOnly();
            ZipOutputStream zos = null;

            try
            {
                if (!(outputStream is ZipOutputStream))
                {
                    zos = new ZipOutputStream(outputStream);
                }
                else
                {
                    zos = (ZipOutputStream)outputStream;
                }

                zos.UseZip64 = UseZip64.Off;
                // If the core properties part does not exist in the part list,
                // we save it as well
                if (this.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).Count == 0 &&
                    this.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).Count == 0)
                {
                    logger.Log(POILogger.DEBUG, "Save core properties part");

                    // Ensure that core properties are added if missing
                    GetPackageProperties();

                    // Add core properties to part list ...
                    AddPackagePart(this.packageProperties);

                    // ... and to add its relationship ...
                    this.relationships.AddRelationship(this.packageProperties
                                                       .PartName.URI, TargetMode.Internal,
                                                       PackageRelationshipTypes.CORE_PROPERTIES, null);
                    // ... and the content if it has not been added yet.
                    if (!this.contentTypeManager
                        .IsContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART))
                    {
                        this.contentTypeManager.AddContentType(
                            this.packageProperties.PartName,
                            ContentTypes.CORE_PROPERTIES_PART);
                    }
                }

                // Save package relationships part.
                logger.Log(POILogger.DEBUG, "Save package relationships");
                ZipPartMarshaller.MarshallRelationshipPart(this.Relationships,
                                                           PackagingUriHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,
                                                           zos);

                // Save content type part.
                logger.Log(POILogger.DEBUG, "Save content types part");
                this.contentTypeManager.Save(zos);

                // Save parts.
                foreach (PackagePart part in GetParts())
                {
                    // If the part is a relationship part, we don't save it, it's
                    // the source part that will do the job.
                    if (part.IsRelationshipPart)
                    {
                        continue;
                    }

                    logger.Log(POILogger.DEBUG, "Save part '"
                               + ZipHelper.GetZipItemNameFromOPCName(part
                                                                     .PartName.Name) + "'");
                    if (partMarshallers.ContainsKey(part._contentType))
                    {
                        PartMarshaller marshaller = partMarshallers[part._contentType];

                        if (!marshaller.Marshall(part, zos))
                        {
                            throw new OpenXml4NetException(
                                      "The part "
                                      + part.PartName.URI
                                      + " fail to be saved in the stream with marshaller "
                                      + marshaller);
                        }
                    }
                    else
                    {
                        if (!defaultPartMarshaller.Marshall(part, zos))
                        {
                            throw new OpenXml4NetException(
                                      "The part "
                                      + part.PartName.URI
                                      + " fail to be saved in the stream with marshaller "
                                      + defaultPartMarshaller);
                        }
                    }
                }
                //Finishes writing the contents of the ZIP output stream without closing the underlying stream.
                if (isStream)
                {
                    zos.Finish();   //instead of use zos.Close, it will close the stream
                }
                else
                {
                    zos.Close();
                }
            }
            catch (OpenXML4NetRuntimeException e)
            {
                // no need to wrap this type of Exception
                throw e;
            }
            catch (Exception e)
            {
                logger.Log(POILogger.ERROR, "fail to save: an error occurs while saving the package : "
                           + e.Message);
            }
        }
コード例 #26
0
        public void ExportDictionaries(string processId, ClassifierSettingsElastic settings, List <string> tagIdList, List <int> nGramList, CancellationToken token, string hostUrl)
        {
            try
            {
                var service = serviceQuery.Get(settings.ServiceId);

                var dataSet     = GlobalStore.DataSets.Get(settings.DataSetName).DataSet;
                var allDicCount = tagIdList.Count * nGramList.Count;
                /*ZIP time*/ allDicCount += (allDicCount / 10);
                var counter = 0;

                foreach (var nGram in nGramList)
                {
                    var dictionariesPath  = string.Format("{0}/{1}/{2}", _dictionaryRootPath, settings.ServiceId, nGram);
                    var tempDirectoryPath = string.Format("{0}/{1}/{2}", siteConfig.Directory.Temp, processId, nGram);

                    Directory.CreateDirectory(tempDirectoryPath);

                    foreach (var tagId in tagIdList)
                    {
                        if (token.IsCancellationRequested)
                        {
                            processHandler.Cancelled(processId);
                            return;
                        }
                        var filePath    = $"{dictionariesPath}/{DictionaryProtoBuf.GetFileName(tagId)}";
                        var dicProtoBuf = BaseProtoBuf.DeSerialize <DictionaryProtoBuf>(filePath);

                        var csvPath = $"{tempDirectoryPath}/{tagId}.csv";
                        if (dicProtoBuf.Dictionary != null)
                        {
                            CsvHelper.CreateCsv(csvPath, dicProtoBuf.Dictionary.Select(d => new List <string> {
                                d.Key, d.Value.ToString()
                            }).ToList());
                        }
                        else
                        {
                            CsvHelper.CreateCsv(csvPath, new List <List <string> >());
                        }

                        if (++counter % 15 == 0)
                        {
                            processHandler.Changed(processId, Math.Round(counter / (double)allDicCount * 100, 2));
                        }
                    }
                }
                /*time to ZIP the results*/
                var zipFileName   = string.Format("{0}.zip", processId);
                var dirToZipPath  = string.Format("{0}/{1}", siteConfig.Directory.Temp, processId);
                var resultZipPath = string.Format("{0}/{1}.zip", siteConfig.Directory.User, processId);

                ZipHelper.CompressFolder(dirToZipPath, resultZipPath);

                var zipUrl = string.Format("{0}{1}/{2}", hostUrl, Common.Constants.FilesPath, zipFileName);

                processHandler.Finished(processId,
                                        string.Format("{0}\n{1}",
                                                      string.Format(ServiceResources.SuccessfullyExportedDictionariesFrom_0_Service_1, ServiceTypeEnum.Classifier, service.Name),
                                                      string.Format(ServiceResources.ExportFileCanBeDownloadFromHere_0, zipUrl)));
            }
            catch (Exception ex)
            {
                processHandler.Interrupted(processId, ex);
            }
        }
コード例 #27
0
        /**
         * Constructor. Opens a Zip based Open XML document.
         *
         * @param file
         *            The file to open or create.
         * @param access
         *            The package access mode.
         */
        public ZipPackage(FileInfo file, PackageAccess access)
            : base(access)
        {
            ZipEntrySource ze;

            try
            {
                ZipFile zipFile = ZipHelper.OpenZipFile(file);
                ze = new ZipFileZipEntrySource(zipFile);
            }
            catch (IOException e)
            {
                // probably not happening with write access - not sure how to handle the default read-write access ...
                if (access == PackageAccess.WRITE)
                {
                    throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e);
                }
                logger.Log(POILogger.ERROR, "Error in zip file " + file + " - falling back to stream processing (i.e. ignoring zip central directory)");
                // some zips can't be opened via ZipFile in JDK6, as the central directory
                // contains either non-latin entries or the compression type can't be handled
                // the workaround is to iterate over the stream and not the directory
                FileStream fis = null;
                //ThresholdInputStream zis = null;
                ZipInputStream zis = null;
                try
                {
                    fis = file.Create();
                    // TODO: ZipSecureFile
                    // zis = ZipHelper.OpenZipStream(fis);
                    zis = ZipHelper.OpenZipStream(fis);
                    ze  = new ZipInputStreamZipEntrySource(zis);
                }
                catch (IOException e2)
                {
                    if (zis != null)
                    {
                        try
                        {
                            zis.Close();
                        }
                        catch (IOException)
                        {
                            throw new InvalidOperationException("Can't open the specified file: '" + file + "'" +
                                                                " and couldn't close the file input stream", e);
                        }
                    }
                    else if (fis != null)
                    {
                        try
                        {
                            fis.Close();
                        }
                        catch (IOException)
                        {
                            throw new InvalidOperationException("Can't open the specified file: '" + file + "'" +
                                                                " and couldn't close the file input stream", e);
                        }
                    }
                    throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e2);
                }
            }
            this.zipArchive = ze;
        }
コード例 #28
0
 static public Project LoadProject(string file, bool showDeleted)
 {
     if (file.ToLower().EndsWith(".s5d"))
     {
         return(new Step5Project(file, showDeleted));
     }
     else if (file.ToLower().EndsWith(".s7p"))
     {
         return(new Step7ProjectV5(file, showDeleted));
     }
     else if (file.ToLower().EndsWith(".s7l"))
     {
         return(new Step7ProjectV5(file, showDeleted));
     }
     else if (file.ToLower().EndsWith(".ap11"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".ap12"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".ap13"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".ap14"))
     {
         return(createV14SP1ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".ap15"))
     {
         return(createV15ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".al11"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".al12"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".al13"))
     {
         return(createV13ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".al14"))
     {
         return(createV14SP1ProjectInstance(file));
     }
     else if (file.ToLower().EndsWith(".al15"))
     {
         return(createV15ProjectInstance(file));
     }
     else if (!string.IsNullOrEmpty(ZipHelper.GetFirstZipEntryWithEnding(file, ".s5d")))
     {
         return(new Step5Project(file, showDeleted));
     }
     else if (!string.IsNullOrEmpty(ZipHelper.GetFirstZipEntryWithEnding(file, ".s7p")))
     {
         return(new Step7ProjectV5(file, showDeleted));
     }
     else if (!string.IsNullOrEmpty(ZipHelper.GetFirstZipEntryWithEnding(file, ".s7l")))
     {
         return(new Step7ProjectV5(file, showDeleted));
     }
     return(null);
 }
コード例 #29
0
ファイル: XCProject.cs プロジェクト: TianJingDa/Arithmetic
        public void ApplyMod(XCMod mod)
        {
            PBXGroup modGroup = this.GetGroup(mod.group);

//			UnityEngine.Debug.Log( "Adding libraries..." );
//			PBXGroup librariesGroup = this.GetGroup( "Libraries" );
            foreach (XCModFile libRef in mod.libs)
            {
                string completeLibPath = System.IO.Path.Combine("usr/lib", libRef.filePath);
                this.AddFile(completeLibPath, modGroup, "SDKROOT", true, libRef.isWeak);
            }

//			UnityEngine.Debug.Log( "Adding frameworks..." );
            PBXGroup frameworkGroup = this.GetGroup("Frameworks");

            foreach (string framework in mod.frameworks)
            {
                string[] filename     = framework.Split(':');
                bool     isWeak       = (filename.Length > 1) ? true : false;
                string   completePath = System.IO.Path.Combine("System/Library/Frameworks", filename[0]);
                this.AddFile(completePath, frameworkGroup, "SDKROOT", true, isWeak);
            }

//			UnityEngine.Debug.Log( "Adding files..." );
//			foreach( string filePath in mod.files ) {
//				string absoluteFilePath = System.IO.Path.Combine( mod.path, filePath );
//
//
//				if( filePath.EndsWith(".framework") )
//					this.AddFile( absoluteFilePath, frameworkGroup, "GROUP", true, false);
//				else
//					this.AddFile( absoluteFilePath, modGroup );
//			}

//			UnityEngine.Debug.Log( "Adding folders..." );
            foreach (string folderPath in mod.folders)
            {
                string absoluteFolderPath = System.IO.Path.Combine(mod.path, folderPath);
                this.AddFolder(absoluteFolderPath, modGroup, (string[])mod.excludes.ToArray(typeof(string)));
            }

//			UnityEngine.Debug.Log( "Adding headerpaths..." );
            foreach (string headerpath in mod.headerpaths)
            {
                string absoluteHeaderPath = System.IO.Path.Combine(mod.path, headerpath);
                this.AddHeaderSearchPaths(absoluteHeaderPath);
            }
//			UnityEngine.Debug.Log( "Adding librarypaths..." );
            foreach (string headerpath in mod.librarypaths)
            {
                string absoluteLibraryPath = System.IO.Path.Combine(mod.path, headerpath);
                this.AddLibrarySearchPaths(absoluteLibraryPath);
            }

//			UnityEngine.Debug.Log ("Adding Zip...");
            foreach (string zipPath in mod.zipPaths)
            {
                string zipFileName = zipPath;
                string sdkName     = zipFileName.Remove(zipFileName.LastIndexOf("."));

                string    unzipLoc = mod.path + "/" + zipFileName;
                string    dirpath  = this.projectRootPath;
                ZipHelper zipTool  = new ZipHelper();
                zipTool.UnzipWithPath(unzipLoc, dirpath);

                //删除多余解压文件
                DirectoryInfo di = new DirectoryInfo(dirpath + "/__MACOSX");
                di.Delete(true);

                if (sdkName == "SDK")
                {
                    //根据Editor所勾选执行删除工作
                    DeleteUnnecessaryFile();
                }

                string absoluteFolderPath = System.IO.Path.Combine(this.projectRootPath, sdkName + "/");
//				this.AddFolder( absoluteFolderPath, modGroup, (string[])mod.excludes.ToArray( typeof(string) ) );
                //第二个参数传null,能够在xcode项目再减少一层文件夹
                this.AddFolder(absoluteFolderPath, null, (string[])mod.excludes.ToArray(typeof(string)));
            }

//			UnityEngine.Debug.Log( "Adding files..." );
            foreach (string filePath in mod.files)
            {
                //原版为根据.projmods中的files来添加
//				string absoluteFilePath = System.IO.Path.Combine( mod.path, filePath );

                //对于ShareSDK,由于解压的文件夹已经移动至Xcode根目录,所以要根据根目录路径进行库路径添加
                string absoluteFilePath = System.IO.Path.Combine(this.projectRootPath, filePath);

                if (filePath.EndsWith(".framework"))
                {
                    this.AddFile(absoluteFilePath, frameworkGroup, "GROUP", true, false);
                }
                else
                {
                    this.AddFile(absoluteFilePath, modGroup);
                }
            }


//			UnityEngine.Debug.Log( "Configure build settings..." );
            Hashtable buildSettings = mod.buildSettings;

            if (buildSettings.ContainsKey("OTHER_LDFLAGS"))
            {
//				UnityEngine.Debug.Log( "    Adding other linker flags..." );
                ArrayList otherLinkerFlags = (ArrayList)buildSettings["OTHER_LDFLAGS"];
                foreach (string linker in otherLinkerFlags)
                {
                    string _linker = linker;
                    if (!_linker.StartsWith("-"))
                    {
                        _linker = "-" + _linker;
                    }
                    this.AddOtherLDFlags(_linker);
                }
            }

            if (buildSettings.ContainsKey("GCC_ENABLE_CPP_EXCEPTIONS"))
            {
//				UnityEngine.Debug.Log( "    GCC_ENABLE_CPP_EXCEPTIONS = " + buildSettings["GCC_ENABLE_CPP_EXCEPTIONS"] );
                this.GccEnableCppExceptions((string)buildSettings["GCC_ENABLE_CPP_EXCEPTIONS"]);
            }

            if (buildSettings.ContainsKey("GCC_ENABLE_OBJC_EXCEPTIONS"))
            {
//				UnityEngine.Debug.Log( "    GCC_ENABLE_OBJC_EXCEPTIONS = " + buildSettings["GCC_ENABLE_OBJC_EXCEPTIONS"] );
                this.GccEnableObjCExceptions((string)buildSettings["GCC_ENABLE_OBJC_EXCEPTIONS"]);
            }

            this.Consolidate();
        }
コード例 #30
0
    //构建Win64平台EXE 程序
    public static void BuildWin64Exe()
    {
        GenerateLuaWrap();
        AssetDatabase.Refresh();

#if USE_PACK_RES
        FullResBuilder.DeleteRedundantFiles(BuildTarget.StandaloneWindows);
#endif
        string version = System.Text.Encoding.UTF8.GetString(FileUtil.ReadFile(Application.dataPath + "/Resources/Version.bytes"));
        if (string.IsNullOrEmpty(version))
        {
            version = "000";
        }
        //
        version = version.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
        string exeFolderName = string.Empty;
        //
#if JW_DEBUG
        exeFolderName = "Debug_Arcade_" + version;
#else
        exeFolderName = "Release_Arcade_" + version;
#endif
        string outDir  = Application.dataPath + "/../../Builds/BuildWin/" + exeFolderName;
        string outPath = outDir + "/ToyRealMachine.exe";
        //
        PlayerSettings.companyName = "BCZX";
        PlayerSettings.productName = "RealMachine";

        PlayerSettings.defaultIsFullScreen       = true;
        PlayerSettings.displayResolutionDialog   = ResolutionDialogSetting.Disabled;
        PlayerSettings.resizableWindow           = false;
        PlayerSettings.forceSingleInstance       = true;
        PlayerSettings.allowFullscreenSwitch     = false;
        PlayerSettings.applicationIdentifier     = "com.bczx.arcade";
        PlayerSettings.d3d11FullscreenMode       = D3D11FullscreenMode.FullscreenWindow;
        PlayerSettings.visibleInBackground       = false;
        PlayerSettings.defaultIsNativeResolution = true;
        PlayerSettings.runInBackground           = false;
        PlayerSettings.SplashScreen.show         = false;
        PlayerSettings.forceSingleInstance       = true;

        string path = System.IO.Path.GetFullPath(outPath);
#if JW_DEBUG
        BuildOptions option = BuildOptions.AllowDebugging | BuildOptions.Development;
#else
        BuildOptions option = BuildOptions.None;
#endif
        string error = BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, path, BuildTarget.StandaloneWindows64, option);
        if (error != null)
        {
            Debug.Log("BuildWinExe Error:" + error.ToString());
#if !UNITY_EDITOR
            EditorApplication.Exit(2);
#endif
        }
        //
        if (FileUtil.IsFileExist(outPath))
        {
            Debug.Log("BuildWinExe Zip:");
            //合并成Zip
            string outZipPath = Application.dataPath + "/../../Builds/BuildWin/" + exeFolderName + ".zip";
            //
            ZipHelper.CreateZip(outZipPath, outDir);
            //
            FileUtil.CopyFile(Application.dataPath + "/Resources/Version.bytes", Application.dataPath + "/../../Builds/BuildWin/Version.bytes");
        }

#if !UNITY_EDITOR
        EditorApplication.Exit(0);
#endif
    }
コード例 #31
0
 public void ZipTest()
 {
     ZipHelper.ZipDirectory(@"E:\Project\RxConsole\RxConsole\bin\Debug\tmp\", @"E:\Project\RxConsole\RxConsole\bin\Debug\public\1.zip");
 }