public void GetPossibleBundlesApplied_WithBundlesNotInRegisteredList_DoesNotReturnUnregisteredBundles() { var registeredBundle = new BundleInfo("registered", null, new Version()); var unregisteredBundle = new BundleInfo("unregistered", null, new Version()); List<BundleInfo> bundlesFromManifests = new List<BundleInfo> { registeredBundle, unregisteredBundle }; _projectUpgradeService.RegisteredBundles.Add(0, registeredBundle); List<BundleInfo> possibleMatches = _projectUpgradeService.GetPossibleBundlesApplied(new List<BundleInfo>(), bundlesFromManifests); Assert.AreEqual(1, possibleMatches.Count); Assert.AreEqual(registeredBundle, possibleMatches.First()); }
/// <summary> /// Deletes bundle product and its dependecies. Called when the "Delete bundle" button is pressed. /// </summary> private bool DeleteBundle() { // Prepare the parameters string where = "SKUName LIKE N'MyNewBundleProduct%' AND SKUOptionCategoryID IS NULL"; // Get the data DataSet products = SKUInfoProvider.GetSKUs(where, null); // Delete bundle product if (!DataHelper.DataSourceIsEmpty(products)) { // Create object from DataRow SKUInfo deleteBundleProduct = new SKUInfo(products.Tables[0].Rows[0]); // Get the product DataSet bundleProducts = BundleInfoProvider.GetBundles("BundleID = " + deleteBundleProduct.SKUID, null); if (!DataHelper.DataSourceIsEmpty(bundleProducts)) { foreach (DataRow bundleRow in bundleProducts.Tables[0].Rows) { // Create object from DataRow BundleInfo bundleProduct = new BundleInfo(bundleRow); BundleInfoProvider.DeleteBundleInfo(bundleProduct); } } // Delete the bundle product SKUInfoProvider.DeleteSKUInfo(deleteBundleProduct); return true; } return false; }
public void FindInstalledBundlesByMatches_DoesNotReturnBundlesWhereMajorMinorBuildDiffersFromMatchVersion() { var bundleToMatch = new BundleInfo("bundle to match", "", new Version()); var match1 = new FileReleaseInfo("match1", "", new Version("7.5.3.1"), null, bundleToMatch, null); var bundleToNotMatch = new BundleInfo("bundle to not match", "", new Version()); var match2 = new FileReleaseInfo("match2", "", new Version("7.5.0.1"), null, bundleToNotMatch, null); var allMatches = new List<List<FileReleaseInfo>> { new List<FileReleaseInfo> { match1, match2} }; var installedBundles = _projectUpgradeService.FindInstalledBundlesByMatches(allMatches, new Version("7.5.3")); Assert.AreEqual(1, installedBundles.Count()); Assert.AreEqual(bundleToMatch, installedBundles.First()); }
public void GetBundlesApplied_ReturnsOnlyBundlesFoundInBothMatchesAndManifests() { var bundleInBoth = new BundleInfo("Match", "", new Version()); var bundleOnlyInMatches = new BundleInfo("OnlyInMatches", "", new Version()); var bundleOnlyInManifests = new BundleInfo("OnlyInManifests", "", new Version()); var matchedBundles = new List<BundleInfo> { bundleInBoth, bundleOnlyInMatches }; var bundlesFromManifests = new List<BundleInfo> { bundleInBoth, bundleOnlyInManifests }; List<BundleInfo> bundlesApplied = _projectUpgradeService.GetBundlesApplied(matchedBundles, bundlesFromManifests); Assert.AreEqual(1, bundlesApplied.Count); Assert.AreEqual(bundleInBoth, bundlesApplied.First()); }
public static void GetDiff(ref List <BundleInfo> downLoadList, ref List <BundleInfo> removeList, FileList localListInfo, FileList serverListInfo) { if (downLoadList == null || removeList == null || localListInfo == null || serverListInfo == null) { return; } downLoadList.Clear(); removeList.Clear(); List <BundleInfo> localList = localListInfo.m_FileList; List <BundleInfo> serverList = serverListInfo.m_FileList; if (serverList == null) { return; } // 查找需要下载的资源; for (int index = 0; index < serverList.Count; index++) { BundleInfo serverDataInfo = serverList[index]; if (serverDataInfo == null) { continue; } BundleInfo localDataInfo = GetBundleInfo(serverDataInfo.bundleName, localList); // 如果本地FileList没有记录这个文件; if (localDataInfo == null) { downLoadList.Add(serverDataInfo); continue; } // 如果服务器上的比本地的要新,则需要重新下载; if (!BundleInfo.Equals(FileListUtils.s_updateMode, serverDataInfo, localDataInfo)) { downLoadList.Add(serverDataInfo); continue; } //Debug.LogFormat("{5} s_updateMode = {0}, serverDataInfo = {1} - {2}, localDataInfo = {3} - {4}", s_updateMode, serverDataInfo.crc, serverDataInfo.md5, localDataInfo.crc, localDataInfo.md5, serverDataInfo.bundleName); //if (serverDataInfo.crc != localDataInfo.crc) //{ // downLoadList.Add(serverDataInfo); // continue; //} #if !UNITY_EDITOR bool find = false; if (localDataInfo.stream) { find = FindStreamFile(serverDataInfo.bundleName); } else { find = FindLocalFile(serverDataInfo.bundleName); } // 如果列表记录了,但是本地又没有,只能再次下载; if (!find) { downLoadList.Add(serverDataInfo); continue; } #else bool find = FindLocalFile(serverDataInfo.bundleName); if (!find) { downLoadList.Add(serverDataInfo); continue; } #endif } if (localList == null) { return; } // 查找需要删除的资源; for (int index = 0; index < localList.Count; index++) { BundleInfo localDataInfo = localList[index]; BundleInfo serverDataInfo = GetBundleInfo(localDataInfo.bundleName, serverList); // 如果本地没有这个文件; if (serverDataInfo == null) { removeList.Add(localDataInfo); continue; } } }
/// <summary> /// 资源打包 /// </summary> /// <param name="outputPath"></param> /// <param name="options"></param> /// <param name="targetPlatform"></param> public static void BuildAssetBundles(string outputPath, BuildAssetBundleOptions options, BuildTarget targetPlatform) { // 输出目录不存在则创建 if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } // 获取打包规则 var rules = GetBuildRules(); // 获取要打包的Asset var builds = rules.GetBuilds(); // 开始打包 var assetBundleManifest = BuildPipeline.BuildAssetBundles(outputPath, builds, options, targetPlatform); if (assetBundleManifest == null) { Log.Error("no assetbundle !!"); return; } // 获取所有AssetBundleName var bundleNames = assetBundleManifest.GetAllAssetBundles(); // 给所有的AssetBundleName分配索引 var tempDic = new Dictionary <string, int>(); var index = 0; foreach (var name in bundleNames) { tempDic[name] = index; index++; } // 解析每个AssetBundle,依赖、大小、hash值 var bundles = new List <BundleInfo>(); for (var i = 0; i < bundleNames.Length; i++) { var bundleName = bundleNames[i]; var deps = assetBundleManifest.GetAllDependencies(bundleName); var path = string.Format("{0}/{1}", outputPath, bundleName); if (!File.Exists(path)) { Log.Error(path + " file not exsit."); continue; } using (var stream = File.OpenRead(path)) { bundles.Add(new BundleInfo { bundleName = bundleName, deps = Array.ConvertAll(deps, name => tempDic[name]), len = stream.Length, hash = assetBundleManifest.GetAssetBundleHash(bundleName).ToString(), crc = Utility.Verifier.GetCRC32(stream) }); } } // 资源存放的目录 var dirs = new List <string>(); // 所有的资源信息 var assets = new List <AssetInfo>(); // 解析所有打包的资源,对路径和AssetBundleName做映射 for (int i = 0; i < rules.assets.Length; i++) { var item = rules.assets[i]; var dir = Path.GetDirectoryName(item.path); dir = Utility.Path.GetRegularPath(dir); index = dirs.FindIndex(d => d.Equals(dir)); if (index == -1) { index = dirs.Count; dirs.Add(dir); } var asset = new AssetInfo(); asset.fileName = Path.GetFileName(item.path); if (!tempDic.TryGetValue(item.assetBundleName, out asset.bundle)) { var bundle = new BundleInfo(); var id = bundles.Count; bundle.bundleName = asset.fileName; using (var stream = File.OpenRead(item.path)) { bundle.len = stream.Length; bundle.crc = Utility.Verifier.GetCRC32(stream); } bundles.Add(bundle); asset.bundle = id; } asset.dir = index; assets.Add(asset); } // 获取存储BundleManifest的asset var manifest = GetManifest(); // 将数据写到asset文件 manifest.dirs = dirs.ToArray(); manifest.assets = assets.ToArray(); manifest.bundles = bundles.ToArray(); UnityEditor.EditorUtility.SetDirty(manifest); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); // 最后将manifest.asset打包 var assetPath = AssetDatabase.GetAssetPath(manifest); var manifestBundleName = Path.GetFileNameWithoutExtension(assetPath).ToLower(); builds = new[] { new AssetBundleBuild { assetNames = new[] { assetPath }, assetBundleName = manifestBundleName } }; BuildPipeline.BuildAssetBundles(outputPath, builds, options, targetPlatform); { var path = outputPath + "/" + manifestBundleName; var bundle = new BundleInfo(); bundle.bundleName = Path.GetFileName(path); using (var stream = File.OpenRead(path)) { bundle.len = stream.Length; bundle.crc = Utility.Verifier.GetCRC32(stream); } bundles.Add(bundle); } ArrayUtility.Add(ref bundleNames, manifestBundleName); // 生成版本文件 BuildVersions(outputPath, bundles, rules.IncreaseVersion()); }
public static void CompressFiles(string path, bool bCopyToStreamingAsset = false, bool bQuick = false) { //the path of save bundle file string pathbase = path; //backup old lua bundle path string backOldLuaPath = path.Substring(0, path.LastIndexOf("/")); Dictionary <string, bool> ScenenBundleMap = new Dictionary <string, bool>(); //the path used to save compressed bundle file string targetbase = pathbase.Substring(0, pathbase.LastIndexOf("/")) + "/Compressed"; //the latest bundle file path string currentBmFile = path + "/bm.data"; //save the hash code of lua bundle file Dictionary <string, string> hashCodes = new Dictionary <string, string>(); hashCodes.Clear(); //First cook bundles. ensure directory is exists. never read hash code of lua bundles string bmpathbase = pathbase.Substring(0, pathbase.LastIndexOf("/")); if (!Directory.Exists(bmpathbase + "/Bundle_Latest")) { Directory.CreateDirectory(bmpathbase + "/Bundle_Latest"); } else { //read hash code of lua bundles if (File.Exists(backOldLuaPath + "/bm_old.data") && CustomTool.ManageBundleWindow.checkBundleBinary.Count > 0) { FileStream readStream = new FileStream(backOldLuaPath + "/bm_old.data", FileMode.Open); byte[] content = new byte[readStream.Length]; readStream.Seek(0, SeekOrigin.Begin); readStream.Read(content, 0, content.Length); string bm_string = System.Text.Encoding.Default.GetString(content); List <BundleSmallData> data = LitJson.JsonMapper.ToObject <List <BundleSmallData> >(bm_string); readStream.Close(); foreach (var obj in CustomTool.ManageBundleWindow.checkBundleBinary) { foreach (var bundle in data) { if (bundle.name.Equals(obj)) { hashCodes.Add(obj, bundle.bundleHashCode); } } } } } //try to delete old bundle manage file if (File.Exists(backOldLuaPath + "/bm_old.data")) { File.Delete(backOldLuaPath + "/bm_old.data"); } //try to delete bm.data file which was cooked in last time. not current if (File.Exists(bmpathbase + "/Bundle_Latest/bm.data")) { File.Delete(bmpathbase + "/Bundle_Latest/bm.data"); } //copy newest bm.data file to cache directory FileUtil.CopyFileOrDirectory(bmpathbase + "/tmp/bm.data", bmpathbase + "/Bundle_Latest/bm.data"); //load all cooked bundles from bm.data file FileStream bmfile = new FileStream(currentBmFile, FileMode.Open); byte[] bmcontent = new byte[bmfile.Length]; bmfile.Seek(0, SeekOrigin.Begin); bmfile.Read(bmcontent, 0, bmcontent.Length); string tmpbm = System.Text.Encoding.Default.GetString(bmcontent); List <BundleSmallData> AllBundleData = LitJson.JsonMapper.ToObject <List <BundleSmallData> >(tmpbm); bmfile.Close(); //老的信息 List <BundleSmallData> OldStates = new List <BundleSmallData>(); //load old bm.data file to compare bundles with current if (bQuick) { if (File.Exists(targetbase + "/bm.data")) { //解压到bm.tmp DecompressFileLZMA(targetbase + "/bm.data", targetbase + "/bm.tmp"); FileStream tmpfile = new FileStream(targetbase + "/bm.tmp", FileMode.Open); byte[] tmpcontent = new byte[tmpfile.Length]; tmpfile.Seek(0, SeekOrigin.Begin); tmpfile.Read(tmpcontent, 0, tmpcontent.Length); string tmpstr = System.Text.Encoding.Default.GetString(tmpcontent); OldStates = LitJson.JsonMapper.ToObject <List <BundleSmallData> >(tmpstr); tmpfile.Close(); } else { Debug.LogError("No Last Build DLC"); } } //try to clear cache path of bundles. if build type is quick, skip this step if (Directory.Exists(targetbase)) { if (!bQuick) { CustomTool.FileSystem.ClearPath(targetbase, false); } } else { CustomTool.FileSystem.CreatePath(targetbase); } //load all bundles from bundle configuration file List <string> AllFiles = CustomTool.FileSystem.GetSubFiles(pathbase); BundleInfo Setting = CustomTool.ManageBundleWindow.GetCurrentCookingSetting();// AssetDatabase.LoadAssetAtPath(PathOfConf, typeof(BundleInfo)) as BundleInfo; List <BundleInfo.Element> bundleinfos = new List <BundleInfo.Element>(Setting.ListOfBundles); AssetDatabase.RemoveUnusedAssetBundleNames(); string finalTypeName = "." + BundleSuffix; foreach (var file in AllFiles) { int startIndex = file.LastIndexOf("."); if (startIndex < 0) { continue; } string typename = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")); if (typename == "manifest") { continue; } if (typename != finalTypeName) { if (typename == ".data") { } else { continue; } } string tgname; string bundleName = ""; if (file.LastIndexOf("/") >= 0) { tgname = file.Substring(file.LastIndexOf("/"), file.Length - file.LastIndexOf("/")); bundleName = file.Substring(0, file.Length - typename.Length); bundleName = bundleName.Substring(bundleName.LastIndexOf("/") + 1, bundleName.Length - bundleName.LastIndexOf("/") - 1); } else { tgname = "/" + file; bundleName = file.Substring(0, file.Length - typename.Length); } //Debug.Log("BundleName is = " + bundleName); bool bEncrypt = false; bEncrypt = false; bool bSceneBundle = false; //值判断allinone foreach (var tmpinfo in bundleinfos) { if (tmpinfo.Mode != BundleInfo.BundleMode.AllInOne && tmpinfo.Mode != BundleInfo.BundleMode.SceneBundle) { continue; } if (tmpinfo.Name == bundleName) { bEncrypt = tmpinfo.bEncrypt; bSceneBundle = (tmpinfo.Mode == BundleInfo.BundleMode.SceneBundle); ScenenBundleMap[bundleName] = bSceneBundle; break; } } tgname = targetbase + tgname; tgname = tgname.Substring(0, tgname.LastIndexOf(".")); if (typename != finalTypeName) { if (typename == ".data") { tgname += ".data"; } } else { tgname += finalTypeName; } if (file != "bm.data") { string oldhash = ""; string newhash = "-1"; if (bQuick) { //对比老信息,看是否需要重新压缩 foreach (var tmp in AllBundleData) { if (tmp.name == file) { newhash = tmp.bundleHashCode; } } foreach (var tmp in OldStates) { if (tmp.name == file) { oldhash = tmp.bundleHashCode; } } } if (oldhash == newhash) { Debug.Log("Skip compress " + file + " !!"); } else { if (File.Exists(pathbase + "/" + file)) { CompressFileLZMA(pathbase + "/" + file, tgname, bEncrypt); } } } } //decide which lua bundle file need to be real updated Dictionary <string, bool> needUpdateLua = new Dictionary <string, bool>(); if (hashCodes.Count > 0) { int idx = 0; foreach (var lua in CustomTool.ManageBundleWindow.backOldBundleBinary) { bool bShouldUpdateLua = true; //compare the lua bundle string tmpPath = backOldLuaPath + "/" + lua.Value; FileStream readStream = new FileStream(tmpPath, FileMode.Open); byte[] tmpcontent = new byte[readStream.Length]; readStream.Seek(0, SeekOrigin.Begin); readStream.Read(tmpcontent, 0, tmpcontent.Length); string oldLua = System.Text.Encoding.Default.GetString(tmpcontent); readStream.Close(); tmpPath = bmpathbase + "/Bundle_Latest/" + CustomTool.ManageBundleWindow.checkBundleBinary[idx]; readStream = new FileStream(tmpPath, FileMode.Open); tmpcontent = new byte[readStream.Length]; readStream.Seek(0, SeekOrigin.Begin); readStream.Read(tmpcontent, 0, tmpcontent.Length); string newLua = System.Text.Encoding.Default.GetString(tmpcontent); readStream.Close(); if (oldLua.Equals(newLua)) { bShouldUpdateLua = false; // Debug.Log(CustomTool.ManageBundleWindow.checkBundleBinary[idx] + " was not modified, do not update it"); } needUpdateLua.Add(CustomTool.ManageBundleWindow.checkBundleBinary[idx], bShouldUpdateLua); idx++; } } else { Debug.Log("Hash code list doesn't contains any lua bundle file name. Does this means first cook bundle????"); } //try to delete backed lua file foreach (var oldLua in CustomTool.ManageBundleWindow.backOldBundleBinary) { if (File.Exists(backOldLuaPath + "/" + oldLua.Value)) { File.Delete(backOldLuaPath + "/" + oldLua.Value); } } //now modify bm.data DirectoryInfo compressdicinfo = new DirectoryInfo(targetbase); FileInfo[] compressfileinfo = compressdicinfo.GetFiles(); List <BundleSmallData> newBundleData = new List <BundleSmallData>(); CustomTool.FileSystem.ReplaceFile(bmpathbase + "/Compressed/UpdateCommonBundle.txt", "0"); bool bSkipLuaCommon = false; foreach (var bminfo in AllBundleData) { bool bfind = false; string key = bminfo.name; if (needUpdateLua.ContainsKey(key) && needUpdateLua[key] == false && hashCodes.ContainsKey(key) && hashCodes[key] != "") { if (bminfo.name.Equals("lua_common.u")) { bSkipLuaCommon = true; } Debug.LogWarning(string.Format("Skip update bundle:: " + bminfo.name + ". Replace bundle hash code:: {0} with {1}", bminfo.bundleHashCode, hashCodes[key])); bminfo.bundleHashCode = hashCodes[key]; } for (int i = 0; i < compressfileinfo.Length; i++) { if (bminfo.name == compressfileinfo[i].Name) { bminfo.compressedSize = compressfileinfo[i].Length; bfind = true; string tmps = bminfo.name.Substring(0, bminfo.name.LastIndexOf('.')); if (ScenenBundleMap.ContainsKey(tmps)) { bminfo.sceneBundle = ScenenBundleMap[tmps]; } else { bminfo.sceneBundle = false; } break; } } if (bfind == false) { Debug.LogError("Can't find " + bminfo.name); } newBundleData.Add(bminfo); } //means not first cook bundle if (!bSkipLuaCommon && hashCodes.Count > 0) { CustomTool.FileSystem.ReplaceFile(bmpathbase + "/Compressed/UpdateCommonBundle.txt", "1"); } //写回bm.data string bmfinal = JsonFormatter.PrettyPrint(JsonMapper.ToJson(newBundleData)); CustomTool.FileSystem.ReplaceFile(bmpathbase + "/Bundle_Latest" + "/bm.data", bmfinal); //压缩bm.data CompressFileLZMA(bmpathbase + "/Bundle_Latest" + "/bm.data", targetbase + "/bm.data", false); List <string> files = new List <string>(); files = CustomTool.FileSystem.GetSubFiles(targetbase); if (bCopyToStreamingAsset) { string streamingAssetPath = "Assets/StreamingAssets"; if (Directory.Exists(streamingAssetPath)) { files.Clear(); files = CustomTool.FileSystem.GetSubFiles(streamingAssetPath); foreach (string file in files) { string typename = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")).ToLower(); if (typename == ".mp4" || typename == ".txt") { continue; } File.Delete(streamingAssetPath + "/" + file); } } else { //FileUtil.cre Directory.CreateDirectory(streamingAssetPath); } files.Clear(); files = CustomTool.FileSystem.GetSubFiles(targetbase); Debug.Log("File.Count = " + files.Count); foreach (string file in files) { string tmpTypeName = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")); if (tmpTypeName.Equals(".txt") || tmpTypeName.Equals(".manifest")) { Debug.Log("Skip copy file:: " + file); continue; } if (CustomTool.ManageBundleWindow.isToStreamingAsset(file)) { Debug.Log("Copying file :: " + file); FileUtil.ReplaceFile(targetbase + "/" + file, streamingAssetPath + "/" + file); } } } }
public BundleInfoPair(BundleInfo bundleInfo1, BundleInfo bundleInfo2) { this.bundleInfo1 = bundleInfo1; this.bundleInfo2 = bundleInfo2; }
static void WriteXml(XmlDocument xmlDoc, XmlNode node, CPathTree pathTree, string path) { if (pathTree == null || xmlDoc == null || node == null) { return; } if (string.IsNullOrEmpty(path)) { path = pathTree.path; } else { path = path + "_" + pathTree.path; } XmlNode path_node = node; // 写入文件信息; XmlNode child_node = null; XmlAttribute attributeNode = null; if (pathTree.total_file_cnt > 0) { attributeNode = xmlDoc.CreateAttribute("total_file_cnt"); attributeNode.Value = pathTree.total_file_cnt.ToString(); path_node.Attributes.Append(attributeNode); attributeNode = xmlDoc.CreateAttribute("total_file_size"); attributeNode.Value = GetSizeDes(pathTree.total_file_size); path_node.Attributes.Append(attributeNode); } if (pathTree.data_list != null) { path_node = xmlDoc.CreateElement(path); node.AppendChild(path_node); node = path_node; attributeNode = xmlDoc.CreateAttribute("bundleSize"); attributeNode.Value = (1.0f * pathTree.size / 1024).ToString("F2") + "KB"; node.Attributes.Append(attributeNode); for (int nIdx = 0; nIdx < pathTree.data_list.Count; ++nIdx) { BundleInfo bundleInfo = pathTree.data_list[nIdx]; child_node = xmlDoc.CreateElement("file"); path_node.AppendChild(child_node); attributeNode = xmlDoc.CreateAttribute("bundleName"); attributeNode.Value = bundleInfo.bundleName; child_node.Attributes.Append(attributeNode); attributeNode = xmlDoc.CreateAttribute("size"); attributeNode.Value = (1.0f * bundleInfo.size / 1024).ToString("F2") + "KB"; child_node.Attributes.Append(attributeNode); } } if (pathTree.subPathTree.Count == 0) { return; } foreach (KeyValuePair <string, CPathTree> pairs in pathTree.subPathTree) { WriteXml(xmlDoc, path_node, pairs.Value, path); } }
static void BuildFileTable(AssetBundleManifest manifest, string bundleRoot, string resourceVersion, PlatformType platformType, BuildTarget target) { Dictionary <string, string> assetTable = new Dictionary <string, string>(); string[] bundles = manifest.GetAllAssetBundles(); string bundleTablePath = Path.Combine("Assets", Path.Combine(bundleRoot, _bundleInfoFileName)); FileInfo bundleTableFile = new FileInfo(bundleTablePath); Dictionary <string, BundleInfo> finalVersionDic = new Dictionary <string, BundleInfo>(); foreach (var bundlePath in bundles) { string path = Path.Combine(bundleRoot, bundlePath); path = Path.Combine(Application.dataPath, path); var bytes = File.ReadAllBytes(path); var assetBundle = AssetBundle.LoadFromMemory(bytes); // log bundle info if (finalVersionDic.ContainsKey(bundlePath)) { if (finalVersionDic[bundlePath].Hash != manifest.GetAssetBundleHash(bundlePath).ToString()) { var newInfo = new BundleInfo(manifest.GetAssetBundleHash(bundlePath).ToString()); finalVersionDic[bundlePath] = newInfo; Debug.Log("Bundle " + bundlePath); } } else { var newInfo = new BundleInfo(manifest.GetAssetBundleHash(bundlePath).ToString()); finalVersionDic.Add(bundlePath, newInfo); Debug.Log("Bundle " + bundlePath); } var assetPaths = assetBundle.GetAllAssetNames(); foreach (var ap in assetPaths) { var subAssetPath = ap; subAssetPath = subAssetPath.Split('.')[0]; var subBundlePath = bundlePath.Split('.')[0]; if (!assetTable.ContainsKey(subAssetPath)) { assetTable.Add(subAssetPath, subBundlePath); } } assetBundle.Unload(true); } //1 BundleInfo.txt using (var writer = File.CreateText(bundleTableFile.FullName)) { writer.WriteLine(resourceVersion); foreach (var line in finalVersionDic) { writer.WriteLine(line.Key + "," + line.Value.Hash); } writer.Close(); } //2 AssetMap.txt var assetTablePath = Path.Combine("Assets", Path.Combine(bundleRoot, _assetMapFileName)); FileInfo assetTableFile = new FileInfo(assetTablePath); using (var writer = File.CreateText(assetTablePath)) { foreach (var pair in assetTable) { string s = string.Format("{0},{1}", pair.Key, pair.Value); writer.WriteLine(s); } writer.Close(); } //Critical fix: //On official document: AssetDatabase.Refresh: Import any changed assets //Make Unity recognize the existence of generated BundleInfo.txt and AssetMap.txt //Otherwise, the resourceinfo generation would fail for the first time while work for the second time AssetDatabase.Refresh(); //3 ResourceInfo var assetMap = new AssetBundleBuild[1]; assetMap[0].assetBundleName = _resourceInfoFileName; assetMap[0].assetNames = new string[] { bundleTablePath, assetTablePath }; //pack the bundleTablePath and assetTablePath to compress its size AssetBundleManifest resourceInfoManifest = BuildPipeline.BuildAssetBundles(assetTableFile.Directory.FullName, assetMap, BuildAssetBundleOptions.None, target); Debug.Log("Build resourceInfo result: " + (resourceInfoManifest != null).ToString()); //4 make zip if (resourceInfoManifest != null) { MakeZip(resourceVersion, platformType, bundles, _resourceInfoFileName, bundleRoot); } }
internal static void RenameBundle(BundleInfo bi, string newName) { MoveAssetsToBundle(bi.m_assets.Values, newName); m_bundles.Remove(bi.m_name); m_dirty = true; }
public TreeItem(BundleInfo b, int depth) : base(b.m_name.GetHashCode(), depth, b.m_name) { bundle = b; icon = Utilities.FoldlerIcon; }
public AssetInfo(BundleInfo b, string n) { m_bundle = b; m_name = n; }
/// <summary> /// Saves edited SKU and returns it's ID. In case of error 0 is returned. Does not fire product saved event. /// </summary> private int SaveInternal() { // Check permissions this.CheckModifyPermission(); // If form is valid and enabled if (this.Validate() && this.FormEnabled) { bool newItem = false; // Get SKUInfo SKUInfo skuiObj = SKUInfoProvider.GetSKUInfo(mProductId); if (skuiObj == null) { newItem = true; // Create new item -> insert skuiObj = new SKUInfo(); skuiObj.SKUSiteID = editedSiteId; } else { SKUProductTypeEnum oldProductType = skuiObj.SKUProductType; SKUProductTypeEnum newProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); // Remove e-product dependencies if required if ((oldProductType == SKUProductTypeEnum.EProduct) && (newProductType != SKUProductTypeEnum.EProduct)) { // Delete meta files MetaFileInfoProvider.DeleteFiles(skuiObj.SKUID, ECommerceObjectType.SKU, MetaFileInfoProvider.OBJECT_CATEGORY_EPRODUCT); // Delete SKU files DataSet skuFiles = SKUFileInfoProvider.GetSKUFiles("FileSKUID = " + skuiObj.SKUID, null); foreach (DataRow skuFile in skuFiles.Tables[0].Rows) { SKUFileInfo skufi = new SKUFileInfo(skuFile); SKUFileInfoProvider.DeleteSKUFileInfo(skufi); } } // Remove bundle dependencies if required if ((oldProductType == SKUProductTypeEnum.Bundle) && (newProductType != SKUProductTypeEnum.Bundle)) { // Delete SKU to bundle mappings DataSet bundles = BundleInfoProvider.GetBundles("BundleID = " + skuiObj.SKUID, null); foreach (DataRow bundle in bundles.Tables[0].Rows) { BundleInfo bi = new BundleInfo(bundle); BundleInfoProvider.DeleteBundleInfo(bi); } } } skuiObj.SKUName = this.txtSKUName.Text.Trim(); skuiObj.SKUNumber = this.txtSKUNumber.Text.Trim(); skuiObj.SKUDescription = this.htmlTemplateBody.ResolvedValue; skuiObj.SKUPrice = this.txtSKUPrice.Value; skuiObj.SKUEnabled = this.chkSKUEnabled.Checked; skuiObj.SKUInternalStatusID = this.internalStatusElem.InternalStatusID; skuiObj.SKUDepartmentID = this.departmentElem.DepartmentID; skuiObj.SKUManufacturerID = this.manufacturerElem.ManufacturerID; skuiObj.SKUPublicStatusID = this.publicStatusElem.PublicStatusID; skuiObj.SKUSupplierID = this.supplierElem.SupplierID; skuiObj.SKUSellOnlyAvailable = this.chkSKUSellOnlyAvailable.Checked; skuiObj.SKUNeedsShipping = this.chkNeedsShipping.Checked; skuiObj.SKUWeight = ValidationHelper.GetDouble(this.txtSKUWeight.Text.Trim(), 0); skuiObj.SKUHeight = ValidationHelper.GetDouble(this.txtSKUHeight.Text.Trim(), 0); skuiObj.SKUWidth = ValidationHelper.GetDouble(this.txtSKUWidth.Text.Trim(), 0); skuiObj.SKUDepth = ValidationHelper.GetDouble(this.txtSKUDepth.Text.Trim(), 0); skuiObj.SKUConversionName = ValidationHelper.GetString(this.ucConversion.Value, String.Empty); skuiObj.SKUConversionValue = this.txtConversionValue.Text.Trim(); if (String.IsNullOrEmpty(this.txtSKUAvailableItems.Text.Trim())) { skuiObj.SetValue("SKUAvailableItems", null); } else { skuiObj.SKUAvailableItems = ValidationHelper.GetInteger(this.txtSKUAvailableItems.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtSKUAvailableInDays.Text.Trim())) { skuiObj.SetValue("SKUAvailableInDays", null); } else { skuiObj.SKUAvailableInDays = ValidationHelper.GetInteger(this.txtSKUAvailableInDays.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtMaxOrderItems.Text.Trim())) { skuiObj.SetValue("SKUMaxItemsInOrder", null); } else { skuiObj.SKUMaxItemsInOrder = ValidationHelper.GetInteger(this.txtMaxOrderItems.Text.Trim(), 0); } if (!ProductOrdered) { // Set product type skuiObj.SKUProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); } // Clear product type specific properties skuiObj.SetValue("SKUMembershipGUID", null); skuiObj.SetValue("SKUValidity", null); skuiObj.SetValue("SKUValidFor", null); skuiObj.SetValue("SKUValidUntil", null); skuiObj.SetValue("SKUMaxDownloads", null); skuiObj.SetValue("SKUBundleInventoryType", null); skuiObj.SetValue("SKUPrivateDonation", null); skuiObj.SetValue("SKUMinPrice", null); skuiObj.SetValue("SKUMaxPrice", null); // Set product type specific properties switch (skuiObj.SKUProductType) { // Set membership specific properties case SKUProductTypeEnum.Membership: skuiObj.SKUMembershipGUID = this.membershipElem.MembershipGUID; skuiObj.SKUValidity = this.membershipElem.MembershipValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.membershipElem.MembershipValidUntil; } else { skuiObj.SKUValidFor = this.membershipElem.MembershipValidFor; } break; // Set e-product specific properties case SKUProductTypeEnum.EProduct: skuiObj.SKUValidity = this.eProductElem.EProductValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.eProductElem.EProductValidUntil; } else { skuiObj.SKUValidFor = this.eProductElem.EProductValidFor; } break; // Set donation specific properties case SKUProductTypeEnum.Donation: skuiObj.SKUPrivateDonation = this.donationElem.DonationIsPrivate; if (this.donationElem.MinimumDonationAmount == 0.0) { skuiObj.SetValue("SKUMinPrice", null); } else { skuiObj.SKUMinPrice = this.donationElem.MinimumDonationAmount; } if (this.donationElem.MaximumDonationAmount == 0.0) { skuiObj.SetValue("SKUMaxPrice", null); } else { skuiObj.SKUMaxPrice = this.donationElem.MaximumDonationAmount; } break; // Set bundle specific properties case SKUProductTypeEnum.Bundle: skuiObj.SKUBundleInventoryType = this.bundleElem.RemoveFromInventory; break; } // When creating new product option if ((this.ProductID == 0) && (this.OptionCategoryID > 0)) { skuiObj.SKUOptionCategoryID = this.OptionCategoryID; } if ((newItem) && (!SKUInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))) { lblError.Visible = true; lblError.Text = GetString("ecommerceproduct.versioncheck"); return(0); } SKUInfoProvider.SetSKUInfo(skuiObj); if (newItem) { if (ECommerceSettings.UseMetaFileForProductImage) { // Get allowed extensions string settingKey = (skuiObj.IsGlobal) ? "CMSUploadExtensions" : (CMSContext.CurrentSiteName + ".CMSUploadExtensions"); string allowedExtensions = SettingsKeyProvider.GetStringValue(settingKey); // Get posted file HttpPostedFile file = this.ucMetaFile.PostedFile; if ((file != null) && (file.ContentLength > 0)) { // Get file extension string extension = Path.GetExtension(file.FileName); // Check if file is an image and its extension is allowed if (ImageHelper.IsImage(extension) && (String.IsNullOrEmpty(allowedExtensions) || FileHelper.CheckExtension(extension, allowedExtensions))) { // Upload SKU image meta file this.ucMetaFile.ObjectID = skuiObj.SKUID; this.ucMetaFile.UploadFile(); // Update SKU image path this.UpdateSKUImagePath(skuiObj); } else { // Set error message string error = ValidationHelper.GetString(SessionHelper.GetValue("NewProductError"), null); error += ";" + String.Format(this.GetString("com.productedit.invalidproductimage"), extension); SessionHelper.SetValue("NewProductError", error); } } } else { skuiObj.SKUImagePath = this.imgSelect.Value; } // Upload initial e-product file if (skuiObj.SKUProductType == SKUProductTypeEnum.EProduct) { this.eProductElem.SKUID = skuiObj.SKUID; this.eProductElem.UploadNewProductFile(); } } else { // Update SKU image path UpdateSKUImagePath(skuiObj); } SKUInfoProvider.SetSKUInfo(skuiObj); if ((mNodeId > 0) && (mProductId == 0)) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(mNodeId, TreeProvider.ALL_CULTURES); node.NodeSKUID = skuiObj.SKUID; node.Update(); // Update search index for node if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); // Ensure new SKU values SKUInfoProvider.SetSKUInfo(skuiObj); } // If SKU is of bundle product type and bundle does not exist yet if ((skuiObj.SKUProductType == SKUProductTypeEnum.Bundle) && (this.bundleElem.BundleID == 0)) { // Set bundle ID this.bundleElem.BundleID = skuiObj.SKUID; // Save selected products this.bundleElem.SaveProductsSelectionChanges(); } this.ProductID = skuiObj.SKUID; // Reload form this.LoadData(skuiObj); // Set changes saved message this.lblInfo.Text = this.GetString("general.changessaved"); return(ValidationHelper.GetInteger(skuiObj.SKUID, 0)); } else { return(0); } }
/// <summary> /// this funcition only used to test. do not call this when build distribution bundles /// </summary> /// <param name="path"></param> /// <param name="bToStreamingAsset"></param> public static void CompressFile(string path, bool bToStreamingAsset = false) { //the path of save bundle file string pathbase = path; Dictionary <string, bool> ScenenBundleMap = new Dictionary <string, bool>(); //the path used to save compressed bundle file string targetbase = pathbase.Substring(0, pathbase.LastIndexOf("/")) + "/Compressed"; //try to clear cache path of bundles. if build type is quick, skip this step if (Directory.Exists(targetbase)) { CustomTool.FileSystem.ClearPath(targetbase, false); } else { CustomTool.FileSystem.CreatePath(targetbase); } //load all bundles from bundle configuration file List <string> AllFiles = CustomTool.FileSystem.GetSubFiles(pathbase); BundleInfo Setting = CustomTool.ManageBundleWindow.GetCurrentCookingSetting();// AssetDatabase.LoadAssetAtPath(PathOfConf, typeof(BundleInfo)) as BundleInfo; List <BundleInfo.Element> bundleinfos = new List <BundleInfo.Element>(Setting.ListOfBundles); AssetDatabase.RemoveUnusedAssetBundleNames(); string finalTypeName = "." + BundleSuffix; foreach (var file in AllFiles) { int startIndex = file.LastIndexOf("."); if (startIndex < 0) { continue; } string typename = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")); if (typename == "manifest") { continue; } if (typename != finalTypeName) { if (typename == ".data") { } else { continue; } } string tgname; string bundleName = ""; if (file.LastIndexOf("/") >= 0) { tgname = file.Substring(file.LastIndexOf("/"), file.Length - file.LastIndexOf("/")); bundleName = file.Substring(0, file.Length - typename.Length); bundleName = bundleName.Substring(bundleName.LastIndexOf("/") + 1, bundleName.Length - bundleName.LastIndexOf("/") - 1); } else { tgname = "/" + file; bundleName = file.Substring(0, file.Length - typename.Length); } bool bSceneBundle = false; //值判断allinone foreach (var tmpinfo in bundleinfos) { if (tmpinfo.Mode != BundleInfo.BundleMode.AllInOne && tmpinfo.Mode != BundleInfo.BundleMode.SceneBundle) { continue; } if (tmpinfo.Name == bundleName) { bSceneBundle = (tmpinfo.Mode == BundleInfo.BundleMode.SceneBundle); ScenenBundleMap[bundleName] = bSceneBundle; break; } } tgname = targetbase + tgname; tgname = tgname.Substring(0, tgname.LastIndexOf(".")); if (typename != finalTypeName) { if (typename == ".data") { tgname += ".data"; } } else { tgname += finalTypeName; } if (File.Exists(pathbase + "/" + file)) { FileUtil.ReplaceFile(pathbase + "/" + file, tgname); } } CustomTool.FileSystem.ReplaceFile(targetbase + "/UpdateCommonBundle.txt", "0"); List <string> files = new List <string>(); files = CustomTool.FileSystem.GetSubFiles(targetbase); if (bToStreamingAsset) { string streamingAssetPath = "Assets/StreamingAssets"; if (Directory.Exists(streamingAssetPath)) { files.Clear(); files = CustomTool.FileSystem.GetSubFiles(streamingAssetPath); foreach (string file in files) { string typename = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")).ToLower(); if (typename == ".mp4" || typename == ".txt") { continue; } File.Delete(streamingAssetPath + "/" + file); } } else { //FileUtil.cre Directory.CreateDirectory(streamingAssetPath); } files.Clear(); files = CustomTool.FileSystem.GetSubFiles(targetbase); Debug.Log("File.Count = " + files.Count); foreach (string file in files) { string tmpTypeName = file.Substring(file.LastIndexOf("."), file.Length - file.LastIndexOf(".")); if (tmpTypeName.Equals(".txt") || tmpTypeName.Equals(".manifest")) { Debug.Log("Skip copy file:: " + file); continue; } if (CustomTool.ManageBundleWindow.isToStreamingAsset(file)) { Debug.Log("Copying file :: " + file); FileUtil.ReplaceFile(targetbase + "/" + file, streamingAssetPath + "/" + file); } } } }
protected virtual string ToCSV(BundleInfo[] previousVersionBundleInfos, BundleInfo[] currVersionBundleInfos) { StringBuilder buf = new StringBuilder(); buf.Append("\"Name\"").Append(","); buf.Append("\"HASH\"").Append(","); buf.Append("\"CRC\"").Append(","); buf.Append("\"Size\"").Append(","); buf.Append("\"Encoding\"").Append(","); buf.Append("\"Published\"").Append(","); buf.Append("\"Filename\"").Append(","); buf.Append("\"State\"").Append("\r\n"); Dictionary <string, BundleInfoPair> dict = new Dictionary <string, BundleInfoPair>(); foreach (BundleInfo bundle in previousVersionBundleInfos) { dict.Add(bundle.FullName, new BundleInfoPair(bundle, null)); } foreach (BundleInfo bundle in currVersionBundleInfos) { BundleInfoPair pair; if (!dict.TryGetValue(bundle.FullName, out pair)) { dict.Add(bundle.FullName, new BundleInfoPair(null, bundle)); continue; } pair.BundleInfo2 = bundle; } List <BundleInfoPair> bundles = new List <BundleInfoPair>(); bundles.AddRange(dict.Values); bundles.Sort((x, y) => x.Name.CompareTo(y.Name)); long totalSize = 0L; long updatedSize = 0L; long deletedSize = 0L; foreach (BundleInfoPair pair in bundles) { BundleInfo bundle = pair.BundleInfo2 != null ? pair.BundleInfo2 : pair.BundleInfo1; buf.Append("\"").Append(bundle.FullName).Append("\"").Append(","); buf.Append("\"").Append(bundle.Hash.ToString()).Append("\"").Append(","); buf.Append("\"").Append(bundle.CRC).Append("\"").Append(","); buf.Append("\"").Append(bundle.FileSize).Append("\"").Append(","); buf.Append("\"").Append(bundle.Encoding).Append("\"").Append(","); buf.Append("\"").Append(bundle.Published).Append("\"").Append(","); buf.Append("\"").Append(bundle.Filename).Append("\"").Append(","); buf.Append("\"").Append(pair.State).Append("\"").Append("\r\n"); if (pair.State != BundleState.DELETED) { totalSize += pair.BundleInfo2.FileSize; } if (pair.State == BundleState.DELETED) { deletedSize += pair.BundleInfo1.FileSize; } if (pair.State == BundleState.ADDED || pair.State == BundleState.CHANGED) { updatedSize += pair.BundleInfo2.FileSize; } } buf.Append("\r\n"); buf.Append("\"").Append("Total Size").Append("\"").Append(","); buf.Append("\"").Append("Updated Size").Append("\"").Append(","); buf.Append("\"").Append("Deleted Size").Append("\"").Append("\r\n"); buf.Append("\"").Append(totalSize / (float)1048576).Append(" MB\"").Append(","); buf.Append("\"").Append(updatedSize / (float)1048576).Append(" MB\"").Append(","); buf.Append("\"").Append(deletedSize / (float)1048576).Append(" MB\"").Append("\r\n"); return(buf.ToString()); }
public void AddToLoadOrder(string bundleID, LoadOrderType loadOrderType) { BundleInfo bundleInfo = new BundleInfo(bundleID, loadOrderType); //If this is replacing an already loaded bundle (load late), remove the old instances //Also, update the new bundle info to be marked as unloaded if (bundleInfoDic.ContainsKey(bundleID)) { BundleInfo oldInfo = bundleInfoDic[bundleID]; bundleInfoDic.Remove(bundleID); loadFirst.Remove(oldInfo); loadUnordered.Remove(oldInfo); loadLast.Remove(oldInfo); bundleInfo.Status = BundleStatus.Unloaded; bundleInfo.LoadOrderType = oldInfo.LoadOrderType; if (oldInfo.Status != BundleStatus.Loaded && oldInfo.Status != BundleStatus.Unloaded) { OtherLogger.LogError("Tracking a late bundle, but the data bundle isn't already loaded! Data bundle status: " + oldInfo.Status); } } //If this is a new bundle, we should decide if it is able to start being loaded immediately else { if (loadOrderType == LoadOrderType.LoadFirst) { if (loadFirst.Count == 0 || loadFirst.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded)) { bundleInfo.Status = BundleStatus.CanLoad; } //When adding load first bundles, there must never be unordered or load last bundles already added if (loadUnordered.Count != 0 || loadLast.Count != 0) { OtherLogger.LogError($"Mod is set to load first, but it looks like unordered or load last mods are already loading! BundleID ({bundleID})"); loadUnordered.ForEach(o => OtherLogger.LogError($"Load Unordered BundleID ({o.BundleID})")); loadLast.ForEach(o => OtherLogger.LogError($"Load Last BundleID ({o.BundleID})")); } } if (loadOrderType == LoadOrderType.LoadUnordered) { if (loadFirst.Count == 0 || loadFirst.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded)) { bundleInfo.Status = BundleStatus.CanLoad; } //When adding load unordered bundles, there must never be load last bundles already added if (loadLast.Count != 0) { OtherLogger.LogError($"Mod is set to load unordered, but it looks like load last mods are already loading! BundleID ({bundleID})"); loadLast.ForEach(o => OtherLogger.LogError($"Load Last BundleID ({o.BundleID})")); } } if (loadOrderType == LoadOrderType.LoadLast) { if ((loadFirst.Count == 0 && loadUnordered.Count == 0 && loadLast.Count == 0) || (loadFirst.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded) && loadUnordered.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded) && loadLast.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded))) { bundleInfo.Status = BundleStatus.CanLoad; } } } bundleInfoDic.Add(bundleID, bundleInfo); if (loadOrderType == LoadOrderType.LoadFirst) { loadFirst.Add(bundleInfo); } else if (loadOrderType == LoadOrderType.LoadLast) { loadLast.Add(bundleInfo); } else if (loadOrderType == LoadOrderType.LoadUnordered) { loadUnordered.Add(bundleInfo); } }
public static FileListCompareData Compare(FileList newFileList, FileList oldFileList, bool remove_old = true, BundleUpdateMode mode = BundleUpdateMode.Update_CRC) { FileListCompareData comData = new FileListCompareData(); if (newFileList == null) { return(comData); } if (oldFileList == null) { comData.addList.CopyFrom(newFileList.m_FileList); return(comData); } for (int i = 0; i < newFileList.m_FileList.Count; i++) { BundleInfo bundleInfo = newFileList.m_FileList[i]; if (bundleInfo == null || string.IsNullOrEmpty(bundleInfo.bundleName)) { continue; } BundleInfo oldBundleInfo = oldFileList.GetBundleInfo(bundleInfo.bundleName); if (oldBundleInfo == null) { comData.addList.Add(bundleInfo); continue; } if (BundleInfo.Equals(mode, oldBundleInfo, bundleInfo)) { continue; } //if (oldBundleInfo.crc == bundleInfo.crc) //{ // continue; //} comData.modifiyList.Add(bundleInfo); } if (remove_old) { return(comData); } for (int i = 0; i < oldFileList.m_FileList.Count; i++) { BundleInfo oldBundleInfo = oldFileList.m_FileList[i]; if (oldBundleInfo == null || string.IsNullOrEmpty(oldBundleInfo.bundleName)) { continue; } BundleInfo bundleInfo = newFileList.GetBundleInfo(oldBundleInfo.bundleName); if (bundleInfo != null) { continue; } comData.deleteList.Add(bundleInfo); } return(comData); }
public void MarkBundleAsLoaded(string bundleID, bool permanentlyLoaded) { //First, mark bundle as loaded BundleInfo bundleInfo = bundleInfoDic[bundleID]; if (permanentlyLoaded) { bundleInfo.Status = BundleStatus.Loaded; } else { bundleInfo.Status = BundleStatus.Unloaded; } //Next, mark one of the bundles that aren't yet loaded as able to load if (bundleInfo.LoadOrderType == LoadOrderType.LoadFirst) { BundleInfo nextBundle = loadFirst.FirstOrDefault(o => o.Status == BundleStatus.Waiting); //If there is no next bundle to load, it will be null, and all bundles are loaded if (nextBundle != null) { nextBundle.Status = BundleStatus.CanLoad; } else { if (loadUnordered.Count > 0) { loadUnordered.ForEach(o => o.Status = BundleStatus.CanLoad); } else if (loadLast.Count > 0) { loadLast[0].Status = BundleStatus.CanLoad; } } } else if (bundleInfo.LoadOrderType == LoadOrderType.LoadUnordered) { if (loadUnordered.All(o => o.Status == BundleStatus.Loaded || o.Status == BundleStatus.Unloaded)) { if (loadLast.Count != 0) { loadLast[0].Status = BundleStatus.CanLoad; } } //If not all of the unordered bundles have loaded yet, it is assumed that they are still currently loading, so we don't have to set them to load } else if (bundleInfo.LoadOrderType == LoadOrderType.LoadLast) { BundleInfo nextBundle = loadLast.FirstOrDefault(o => o.Status == BundleStatus.Waiting); //If there is no next bundle to load, it will be null, and all bundles are loaded if (nextBundle != null) { nextBundle.Status = BundleStatus.CanLoad; } } }
public static bool GetStreamingAssetsDiff(ref List <BundleInfo> updateLoadList, ref FileList localListInfo, FileList streamListInfo) { if (updateLoadList == null || streamListInfo == null) { return(true); } if (localListInfo == null) { localListInfo = new FileList(); } // 是否是mini; bool isMiniClient = false; updateLoadList.Clear(); List <BundleInfo> localList = localListInfo.m_FileList; List <BundleInfo> serverList = streamListInfo.m_FileList; if (serverList == null) { return(true); } // 查找需要下载的资源; for (int index = 0; index < serverList.Count; index++) { BundleInfo streamDataInfo = serverList[index]; if (streamDataInfo == null) { continue; } BundleInfo localDataInfo = GetBundleInfo(streamDataInfo.bundleName, localList); // 在安装包中 ; if (streamDataInfo.bundleName.EndsWith(".dat")) { streamDataInfo.stream = false; } else { streamDataInfo.stream = true; } bool find = FindStreamFile(streamDataInfo.bundleName); if (!find) { // 安装包里没有有文件; if (localDataInfo != null) { localDataInfo.stream = false; } isMiniClient = true; continue; } updateLoadList.Add(streamDataInfo); } return(isMiniClient); }
public List <BundleInfo> GetBundleDependencies(string bundleID) { List <BundleInfo> depList = new List <BundleInfo>(); BundleInfo bundleStatus = bundleInfoDic[bundleID]; if (bundleStatus.LoadOrderType == LoadOrderType.LoadFirst) { foreach (BundleInfo dep in loadFirst) { if (dep.BundleID == bundleID) { break; } if (!AnvilManager.m_bundles.m_lookup.ContainsKey(dep.BundleID)) { depList.Add(dep); } } } else if (bundleStatus.LoadOrderType == LoadOrderType.LoadUnordered) { foreach (BundleInfo dep in loadFirst) { if (!AnvilManager.m_bundles.m_lookup.ContainsKey(dep.BundleID)) { depList.Add(dep); } } } else if (bundleStatus.LoadOrderType == LoadOrderType.LoadLast) { foreach (BundleInfo dep in loadFirst) { if (!AnvilManager.m_bundles.m_lookup.ContainsKey(dep.BundleID)) { depList.Add(dep); } } foreach (BundleInfo dep in loadUnordered) { if (!AnvilManager.m_bundles.m_lookup.ContainsKey(dep.BundleID)) { depList.Add(dep); } } foreach (BundleInfo dep in loadLast) { if (dep.BundleID == bundleID) { break; } if (!AnvilManager.m_bundles.m_lookup.ContainsKey(dep.BundleID)) { depList.Add(dep); } } } return(depList); }
public void AddFileToReleaseDb_WithNonNullBundleId_SetsBundleOnFileReleaseInfo() { string bundleFileName = "SomeBundle.zip"; var version = new Version("7.5.2.0"); BundleInfo bundleInfo = new BundleInfo("SomeBundle", bundleFileName, version); _projectUpgradeService.InsertBundleRecord(bundleInfo, version); var url = @"\SomeFolder\SomeFile.entity.xml"; var connection = _projectUpgradeService.Connection; int bundleId = _projectUpgradeService.RegisteredBundles.Keys.First(); _projectUpgradeService.AddFileToReleaseDb(StubFile(url), new Version(), connection, bundleId); FileReleaseInfo matchingRelease = _projectUpgradeService.GetReleaseInfoByPath(url).First(); Assert.NotNull(matchingRelease.Bundle); Assert.AreEqual(bundleFileName, matchingRelease.Bundle.FileName); }
void Refresh() { mTarget.Ip = BuildConfig.LocalIpAddress(); var newGroups = new BundleManifest(); var groups = Directory.GetDirectories(BuildConfig.BundleResRoot, "*", SearchOption.TopDirectoryOnly); int n = 0; foreach (var group in groups) { EditorUtility.DisplayCancelableProgressBar("update group ...", group, (float)(++n) / groups.Length); var groupName = group.upath().Replace(BuildConfig.BundleResRoot, ""); GroupInfo groupInfo = mTarget.Groups.Find(i => i.Name == groupName); if (groupInfo == null) { groupInfo = new GroupInfo() { Name = groupName, Bundles = new List <BundleInfo>(), mRebuild = true, }; } var newBundles = new List <BundleInfo>(); foreach (var bundle in Directory.GetDirectories(group, "*", SearchOption.TopDirectoryOnly)) { var bundlePath = bundle.upath(); var bundleName = bundlePath.Replace(BuildConfig.BundleResRoot, "") + BuildConfig.BundlePostfix; var assetBundle = AssetImporter.GetAtPath(bundlePath); if (assetBundle != null) { assetBundle.assetBundleName = bundleName; } //var bundleName = bundle.upath().Replace(group + "/", ""); var bundleInfo = groupInfo.Bundles.Find(i => i.Name == bundleName); if (bundleInfo == null) { bundleInfo = new BundleInfo(); bundleInfo.Name = bundleName; } foreach (var f in Directory.GetFiles(bundle, "*", SearchOption.AllDirectories) .Where(i => !i.EndsWith(".meta"))) { var assetImporter = AssetImporter.GetAtPath(f); if (assetImporter != null) { assetImporter.assetBundleName = bundleName; //"";// var assetTimeStamp = assetImporter.assetTimeStamp; } } // if (time > 0) newBundles.Add(bundleInfo); } //for 2 // AssetDatabase.GetAllAssetBundleNames(); // AssetDatabase.RemoveUnusedAssetBundleNames(); groupInfo.Bundles = newBundles; groupInfo.Refresh(); if (groupInfo.Bundles.Count > 0) { newGroups.Add(groupInfo); } } //for 1 mTarget.Groups = newGroups; EditorUtility.ClearProgressBar(); }
public void FindInstalledBundlesByMatches_WithMultipleMatchesOnTheSameBundle_OnlyReturnsTheSameBundleOnce() { var bundle = new BundleInfo("test", "", new Version()); var match1 = new FileReleaseInfo("match1", "", new Version("7.5.3.1"), null, bundle, null); var match2 = new FileReleaseInfo("match2", "", new Version("7.5.3.2"), null, bundle, null); var allMatches = new List<List<FileReleaseInfo>> { new List<FileReleaseInfo> { match1, match2} }; var installedBundles = _projectUpgradeService.FindInstalledBundlesByMatches(allMatches, new Version("7.5.3")); Assert.AreEqual(1, installedBundles.Count()); Assert.AreEqual(bundle, installedBundles.First()); }
protected override IEnumerator DoDownloadBundles(IProgressPromise <Progress, bool> promise, List <BundleInfo> bundles) { long totalSize = 0; long downloadedSize = 0; Progress progress = new Progress(); List <BundleInfo> list = new List <BundleInfo>(); for (int i = 0; i < bundles.Count; i++) { var info = bundles[i]; totalSize += info.FileSize; if (BundleUtil.Exists(info)) { downloadedSize += info.FileSize; continue; } list.Add(info); } progress.TotalCount = bundles.Count; progress.CompletedCount = bundles.Count - list.Count; progress.TotalSize = totalSize; progress.CompletedSize = downloadedSize; yield return(null); List <KeyValuePair <BundleInfo, WWW> > tasks = new List <KeyValuePair <BundleInfo, WWW> >(); for (int i = 0; i < list.Count; i++) { BundleInfo bundleInfo = list[i]; WWW www = (useCache && !bundleInfo.IsEncrypted) ? WWW.LoadFromCacheOrDownload(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash) : new WWW(GetAbsoluteUri(bundleInfo.Filename)); tasks.Add(new KeyValuePair <BundleInfo, WWW>(bundleInfo, www)); while (tasks.Count >= this.MaxTaskCount || (i == list.Count - 1 && tasks.Count > 0)) { long tmpSize = 0; for (int j = tasks.Count - 1; j >= 0; j--) { var task = tasks[j]; BundleInfo _bundleInfo = task.Key; WWW _www = task.Value; if (!_www.isDone) { tmpSize += Math.Max(0, (long)(_www.progress * _bundleInfo.FileSize)); continue; } progress.CompletedCount += 1; tasks.RemoveAt(j); downloadedSize += _bundleInfo.FileSize; if (!string.IsNullOrEmpty(_www.error)) { promise.SetException(new Exception(_www.error)); if (log.IsErrorEnabled) { log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), _www.error); } yield break; } try { if (useCache && !_bundleInfo.IsEncrypted) { AssetBundle bundle = _www.assetBundle; if (bundle != null) { bundle.Unload(true); } } else { string fullname = BundleUtil.GetStorableDirectory() + _bundleInfo.Filename; FileInfo info = new FileInfo(fullname); if (info.Exists) { info.Delete(); } if (!info.Directory.Exists) { info.Directory.Create(); } File.WriteAllBytes(info.FullName, _www.bytes); } } catch (Exception e) { promise.SetException(e); if (log.IsErrorEnabled) { log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), e); } yield break; } } progress.CompletedSize = downloadedSize + tmpSize; promise.UpdateProgress(progress); yield return(null); } } promise.SetResult(true); }
public void GetPossibleBundlesApplied_OnlyReturnsBundlesInManifestsButNotMatches() { var bundlefromManifest1 = new BundleInfo("manifest1 bundle", null, new Version()); var bundlefromManifest2 = new BundleInfo("manifest2 bundle", null, new Version()); List<BundleInfo> bundlesFromManifests = new List<BundleInfo> { bundlefromManifest1, bundlefromManifest2 }; List<BundleInfo> bundlesFromMatches = new List<BundleInfo> { bundlefromManifest1 }; _projectUpgradeService.RegisteredBundles.Add(0, bundlefromManifest1); _projectUpgradeService.RegisteredBundles.Add(1, bundlefromManifest2); List<BundleInfo> possibleMatches = _projectUpgradeService.GetPossibleBundlesApplied(bundlesFromMatches, bundlesFromManifests); Assert.AreEqual(1, possibleMatches.Count); Assert.AreEqual(bundlefromManifest2, possibleMatches.First()); }
protected override IEnumerator DoDownloadBundles(IProgressPromise <Progress, bool> promise, List <BundleInfo> bundles) { long totalSize = 0; long downloadedSize = 0; Progress progress = new Progress(); List <BundleInfo> list = new List <BundleInfo>(); for (int i = 0; i < bundles.Count; i++) { var info = bundles[i]; totalSize += info.FileSize; if (BundleUtil.Exists(info)) { downloadedSize += info.FileSize; continue; } list.Add(info); } progress.TotalCount = bundles.Count; progress.CompletedCount = bundles.Count - list.Count; progress.TotalSize = totalSize; progress.CompletedSize = downloadedSize; yield return(null); List <KeyValuePair <BundleInfo, UnityWebRequest> > tasks = new List <KeyValuePair <BundleInfo, UnityWebRequest> >(); for (int i = 0; i < list.Count; i++) { BundleInfo bundleInfo = list[i]; UnityWebRequest www; if (useCache && !bundleInfo.IsEncrypted) { #if UNITY_2018_1_OR_NEWER www = UnityWebRequestAssetBundle.GetAssetBundle(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash, 0); #else www = UnityWebRequest.GetAssetBundle(GetAbsoluteUri(bundleInfo.Filename), bundleInfo.Hash, 0); #endif } else { www = new UnityWebRequest(GetAbsoluteUri(bundleInfo.Filename)); www.downloadHandler = new DownloadHandlerBuffer(); } #if UNITY_2018_1_OR_NEWER www.SendWebRequest(); #else www.Send(); #endif tasks.Add(new KeyValuePair <BundleInfo, UnityWebRequest>(bundleInfo, www)); while (tasks.Count >= this.MaxTaskCount || (i == list.Count - 1 && tasks.Count > 0)) { long tmpSize = 0; for (int j = tasks.Count - 1; j >= 0; j--) { var task = tasks[j]; BundleInfo _bundleInfo = task.Key; UnityWebRequest _www = task.Value; if (!_www.isDone) { tmpSize += (long)Math.Max(0, _www.downloadedBytes);//the UnityWebRequest.downloadedProgress has a bug in android platform continue; } progress.CompletedCount += 1; tasks.RemoveAt(j); downloadedSize += _bundleInfo.FileSize; if (!string.IsNullOrEmpty(_www.error)) { promise.SetException(new Exception(_www.error)); if (log.IsErrorEnabled) { log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), _www.error); } yield break; } try { if (useCache && !bundleInfo.IsEncrypted) { AssetBundle bundle = ((DownloadHandlerAssetBundle)_www.downloadHandler).assetBundle; if (bundle != null) { bundle.Unload(true); } } else { string fullname = BundleUtil.GetStorableDirectory() + _bundleInfo.Filename; FileInfo info = new FileInfo(fullname); if (info.Exists) { info.Delete(); } if (!info.Directory.Exists) { info.Directory.Create(); } File.WriteAllBytes(info.FullName, _www.downloadHandler.data); } } catch (Exception e) { promise.SetException(e); if (log.IsErrorEnabled) { log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), e); } yield break; } } progress.CompletedSize = downloadedSize + tmpSize; promise.UpdateProgress(progress); yield return(null); } } promise.SetResult(true); }
public void LoadRegisteredBundles_LoadsDbDataIntoBundleInfoDictionary() { string fileName = "file.txt"; string name = "my name"; Version version = new Version("7.5.3.2"); BundleInfo bundleInfo = new BundleInfo(name, fileName, version); _projectUpgradeService.InsertBundleRecord(bundleInfo, version); Dictionary<int, BundleInfo> registeredBundles = _projectUpgradeService.LoadRegisteredBundles(); Assert.AreEqual(1, registeredBundles.Count); var bundle = registeredBundles.Values.First(); Assert.AreEqual(fileName, bundle.FileName); Assert.AreEqual(name, bundle.Name); Assert.AreEqual(version, bundle.Version); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var assetName = property.FindPropertyRelative("assetName"); var bundleName = property.FindPropertyRelative("bundleName"); var typeProp = property.FindPropertyRelative("type");; var parentLayerProp = property.FindPropertyRelative("parentLayer"); var resetProp = property.FindPropertyRelative("reset"); var buttonProp = property.FindPropertyRelative("button"); var toggleProp = property.FindPropertyRelative("toggle"); float height = EditorGUIUtility.singleLineHeight; Rect rect = new Rect(position.xMin, position.yMin, position.width * 0.9f, height); if (GUI.Button(rect, assetName.stringValue, EditorStyles.toolbar)) { //使用对象是UIGroupObj,将无法从button和Toggle加载 if (property.serializedObject.targetObject is UIGroupObj) { if (typeProp.enumValueIndex == (int)ItemInfoBase.Type.Button || typeProp.enumValueIndex == (int)ItemInfoBase.Type.Toggle) { typeProp.enumValueIndex = (int)ItemInfoBase.Type.Name; } } property.isExpanded = !property.isExpanded; } switch ((ItemInfoBase.Type)typeProp.enumValueIndex) { case ItemInfoBase.Type.Button: if (buttonProp.objectReferenceValue == null) { Worning(rect, "button lost!"); } break; case ItemInfoBase.Type.Toggle: if (toggleProp.objectReferenceValue == null) { Worning(rect, "toggle lost!"); } break; default: break; } rect = new Rect(position.max.x - position.width * 0.1f, position.yMin, position.width * 0.1f, height); if (GUI.Button(rect, "open", EditorStyles.textField)) { var select = EditorUtility.DisplayDialog("提示", "是否打开新场景并加载资源", "是", "否"); if (!select) { return; } BundlePreview.Data data = new BundlePreview.Data(); var assetUrl = property.serializedObject.FindProperty("assetUrl"); var menu = property.serializedObject.FindProperty("menu"); if (string.IsNullOrEmpty(assetUrl.stringValue) || string.IsNullOrEmpty(menu.stringValue)) { return; } data.assetUrl = assetUrl.stringValue; data.menu = menu.stringValue; var bdinfo = new BundleInfo(); bdinfo.assetName = assetName.stringValue; bdinfo.bundleName = bundleName.stringValue; bdinfo.reset = resetProp.boolValue; data.rbundles.Add(bdinfo); var path = AssetDatabase.GUIDToAssetPath("018159907ea26db409399b839477ad27"); UnityEditor.SceneManagement.EditorSceneManager.OpenScene(path); GameObject holder = new GameObject("holder"); BundlePreview preview = holder.AddComponent <BundlePreview>(); preview.data = data; EditorApplication.ExecuteMenuItem("Edit/Play"); } if (!property.isExpanded) { return; } rect = new Rect(position.xMin, position.yMin + height, position.width, height); EditorGUI.PropertyField(rect, assetName, new GUIContent("name")); rect.y += height; EditorGUI.PropertyField(rect, bundleName, new GUIContent("bundle")); rect.y += height; EditorGUI.PropertyField(rect, typeProp, new GUIContent("type")); switch ((ItemInfoBase.Type)typeProp.enumValueIndex) { case ItemInfoBase.Type.Name: break; case ItemInfoBase.Type.Button: rect.y += height; EditorGUI.PropertyField(rect, buttonProp, new GUIContent("Button")); break; case ItemInfoBase.Type.Toggle: rect.y += height; EditorGUI.PropertyField(rect, toggleProp, new GUIContent("Toggle")); break; case ItemInfoBase.Type.Enable: break; default: break; } rect.y += height; EditorGUI.PropertyField(rect, parentLayerProp, new GUIContent("parentLayer")); rect.y += height; EditorGUI.PropertyField(rect, resetProp, new GUIContent("reset")); }
/// <summary> /// Saves edited SKU and returns it's ID. In case of error 0 is returned. Does not fire product saved event. /// </summary> private int SaveInternal() { // Check permissions this.CheckModifyPermission(); // If form is valid and enabled if (this.Validate() && this.FormEnabled) { bool newItem = false; // Get SKUInfo SKUInfo skuiObj = SKUInfoProvider.GetSKUInfo(mProductId); if (skuiObj == null) { newItem = true; // Create new item -> insert skuiObj = new SKUInfo(); skuiObj.SKUSiteID = editedSiteId; } else { SKUProductTypeEnum oldProductType = skuiObj.SKUProductType; SKUProductTypeEnum newProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); // Remove e-product dependencies if required if ((oldProductType == SKUProductTypeEnum.EProduct) && (newProductType != SKUProductTypeEnum.EProduct)) { // Delete meta files MetaFileInfoProvider.DeleteFiles(skuiObj.SKUID, ECommerceObjectType.SKU, MetaFileInfoProvider.OBJECT_CATEGORY_EPRODUCT); // Delete SKU files DataSet skuFiles = SKUFileInfoProvider.GetSKUFiles("FileSKUID = " + skuiObj.SKUID, null); foreach (DataRow skuFile in skuFiles.Tables[0].Rows) { SKUFileInfo skufi = new SKUFileInfo(skuFile); SKUFileInfoProvider.DeleteSKUFileInfo(skufi); } } // Remove bundle dependencies if required if ((oldProductType == SKUProductTypeEnum.Bundle) && (newProductType != SKUProductTypeEnum.Bundle)) { // Delete SKU to bundle mappings DataSet bundles = BundleInfoProvider.GetBundles("BundleID = " + skuiObj.SKUID, null); foreach (DataRow bundle in bundles.Tables[0].Rows) { BundleInfo bi = new BundleInfo(bundle); BundleInfoProvider.DeleteBundleInfo(bi); } } } skuiObj.SKUName = this.txtSKUName.Text.Trim(); skuiObj.SKUNumber = this.txtSKUNumber.Text.Trim(); skuiObj.SKUDescription = this.htmlTemplateBody.ResolvedValue; skuiObj.SKUPrice = this.txtSKUPrice.Value; skuiObj.SKUEnabled = this.chkSKUEnabled.Checked; skuiObj.SKUInternalStatusID = this.internalStatusElem.InternalStatusID; skuiObj.SKUDepartmentID = this.departmentElem.DepartmentID; skuiObj.SKUManufacturerID = this.manufacturerElem.ManufacturerID; skuiObj.SKUPublicStatusID = this.publicStatusElem.PublicStatusID; skuiObj.SKUSupplierID = this.supplierElem.SupplierID; skuiObj.SKUSellOnlyAvailable = this.chkSKUSellOnlyAvailable.Checked; skuiObj.SKUNeedsShipping = this.chkNeedsShipping.Checked; skuiObj.SKUWeight = ValidationHelper.GetDouble(this.txtSKUWeight.Text.Trim(), 0); skuiObj.SKUHeight = ValidationHelper.GetDouble(this.txtSKUHeight.Text.Trim(), 0); skuiObj.SKUWidth = ValidationHelper.GetDouble(this.txtSKUWidth.Text.Trim(), 0); skuiObj.SKUDepth = ValidationHelper.GetDouble(this.txtSKUDepth.Text.Trim(), 0); skuiObj.SKUConversionName = ValidationHelper.GetString(this.ucConversion.Value, String.Empty); skuiObj.SKUConversionValue = this.txtConversionValue.Text.Trim(); if (String.IsNullOrEmpty(this.txtSKUAvailableItems.Text.Trim())) { skuiObj.SetValue("SKUAvailableItems", null); } else { skuiObj.SKUAvailableItems = ValidationHelper.GetInteger(this.txtSKUAvailableItems.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtSKUAvailableInDays.Text.Trim())) { skuiObj.SetValue("SKUAvailableInDays", null); } else { skuiObj.SKUAvailableInDays = ValidationHelper.GetInteger(this.txtSKUAvailableInDays.Text.Trim(), 0); } if (String.IsNullOrEmpty(this.txtMaxOrderItems.Text.Trim())) { skuiObj.SetValue("SKUMaxItemsInOrder", null); } else { skuiObj.SKUMaxItemsInOrder = ValidationHelper.GetInteger(this.txtMaxOrderItems.Text.Trim(), 0); } if (!ProductOrdered) { // Set product type skuiObj.SKUProductType = SKUInfoProvider.GetSKUProductTypeEnum((string)this.selectProductTypeElem.Value); } // Clear product type specific properties skuiObj.SetValue("SKUMembershipGUID", null); skuiObj.SetValue("SKUValidity", null); skuiObj.SetValue("SKUValidFor", null); skuiObj.SetValue("SKUValidUntil", null); skuiObj.SetValue("SKUMaxDownloads", null); skuiObj.SetValue("SKUBundleInventoryType", null); skuiObj.SetValue("SKUPrivateDonation", null); skuiObj.SetValue("SKUMinPrice", null); skuiObj.SetValue("SKUMaxPrice", null); // Set product type specific properties switch (skuiObj.SKUProductType) { // Set membership specific properties case SKUProductTypeEnum.Membership: skuiObj.SKUMembershipGUID = this.membershipElem.MembershipGUID; skuiObj.SKUValidity = this.membershipElem.MembershipValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.membershipElem.MembershipValidUntil; } else { skuiObj.SKUValidFor = this.membershipElem.MembershipValidFor; } break; // Set e-product specific properties case SKUProductTypeEnum.EProduct: skuiObj.SKUValidity = this.eProductElem.EProductValidity; if (skuiObj.SKUValidity == ValidityEnum.Until) { skuiObj.SKUValidUntil = this.eProductElem.EProductValidUntil; } else { skuiObj.SKUValidFor = this.eProductElem.EProductValidFor; } break; // Set donation specific properties case SKUProductTypeEnum.Donation: skuiObj.SKUPrivateDonation = this.donationElem.DonationIsPrivate; if (this.donationElem.MinimumDonationAmount == 0.0) { skuiObj.SetValue("SKUMinPrice", null); } else { skuiObj.SKUMinPrice = this.donationElem.MinimumDonationAmount; } if (this.donationElem.MaximumDonationAmount == 0.0) { skuiObj.SetValue("SKUMaxPrice", null); } else { skuiObj.SKUMaxPrice = this.donationElem.MaximumDonationAmount; } break; // Set bundle specific properties case SKUProductTypeEnum.Bundle: skuiObj.SKUBundleInventoryType = this.bundleElem.RemoveFromInventory; break; } // When creating new product option if ((this.ProductID == 0) && (this.OptionCategoryID > 0)) { skuiObj.SKUOptionCategoryID = this.OptionCategoryID; } if ((newItem) && (!SKUInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))) { lblError.Visible = true; lblError.Text = GetString("ecommerceproduct.versioncheck"); return 0; } SKUInfoProvider.SetSKUInfo(skuiObj); if (newItem) { if (ECommerceSettings.UseMetaFileForProductImage) { // Get allowed extensions string settingKey = (skuiObj.IsGlobal) ? "CMSUploadExtensions" : (CMSContext.CurrentSiteName + ".CMSUploadExtensions"); string allowedExtensions = SettingsKeyProvider.GetStringValue(settingKey); // Get posted file HttpPostedFile file = this.ucMetaFile.PostedFile; if ((file != null) && (file.ContentLength > 0)) { // Get file extension string extension = Path.GetExtension(file.FileName); // Check if file is an image and its extension is allowed if (ImageHelper.IsImage(extension) && (String.IsNullOrEmpty(allowedExtensions) || FileHelper.CheckExtension(extension, allowedExtensions))) { // Upload SKU image meta file this.ucMetaFile.ObjectID = skuiObj.SKUID; this.ucMetaFile.UploadFile(); // Update SKU image path this.UpdateSKUImagePath(skuiObj); } else { // Set error message string error = ValidationHelper.GetString(SessionHelper.GetValue("NewProductError"), null); error += ";" + String.Format(this.GetString("com.productedit.invalidproductimage"), extension); SessionHelper.SetValue("NewProductError", error); } } } else { skuiObj.SKUImagePath = this.imgSelect.Value; } // Upload initial e-product file if (skuiObj.SKUProductType == SKUProductTypeEnum.EProduct) { this.eProductElem.SKUID = skuiObj.SKUID; this.eProductElem.UploadNewProductFile(); } } else { // Update SKU image path UpdateSKUImagePath(skuiObj); } SKUInfoProvider.SetSKUInfo(skuiObj); if ((mNodeId > 0) && (mProductId == 0)) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = tree.SelectSingleNode(mNodeId, TreeProvider.ALL_CULTURES); node.NodeSKUID = skuiObj.SKUID; node.Update(); // Update search index for node if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); // Ensure new SKU values SKUInfoProvider.SetSKUInfo(skuiObj); } // If SKU is of bundle product type and bundle does not exist yet if ((skuiObj.SKUProductType == SKUProductTypeEnum.Bundle) && (this.bundleElem.BundleID == 0)) { // Set bundle ID this.bundleElem.BundleID = skuiObj.SKUID; // Save selected products this.bundleElem.SaveProductsSelectionChanges(); } this.ProductID = skuiObj.SKUID; // Reload form this.LoadData(skuiObj); // Set changes saved message this.lblInfo.Text = this.GetString("general.changessaved"); return ValidationHelper.GetInteger(skuiObj.SKUID, 0); } else { return 0; } }
internal bool IsMatchVersion(ICachableBundle bundleData) { return(BundleInfo.IsMatchVersion(bundleData)); }