public void Execute(string blogId) { var database = mongoClient.GetDatabase("BlogSystemDB"); var articles = database.GetCollection <Article>("Articles"); var users = database.GetCollection <User>("Users"); using (var session = mongoClient.StartSession()) { session.StartTransaction(); try { var findArticleByBlogId = Builders <Article> .Filter.Eq(a => a.BlogId, blogId); articles.DeleteMany(session, findArticleByBlogId); var filter = new BsonDocument { { "Blogs._id", BsonObjectId.Create(blogId) } }; var update = Builders <User> .Update.PullFilter("Blogs", Builders <Blog> .Filter.Eq("_id", BsonObjectId.Create(blogId))); users.UpdateOne(session, filter, update); session.CommitTransaction(); } catch (Exception ex) { session.AbortTransaction(); throw ex; } } }
public Task GetProfileDataAsync(ProfileDataRequestContext context) { var sUserId = _userManager.GetUserId(context.Subject); if (string.IsNullOrEmpty(sUserId)) { return(Task.FromResult(0)); } var userCollection = _repository.GetDatabase() .GetCollection <AppUser>(AppIndentityConstants.Mongo.IdentityUserCollectionName); var user = userCollection.AsQueryable().SingleOrDefault(u => u.Id == BsonObjectId.Create(sUserId)); if (user == null) { return(Task.FromResult(0)); } var roleNames = user.Roles.Select(r => r).ToList(); var claims = new List <Claim> { new Claim(JwtClaimTypes.Name, user.UserName, ClaimTypes.Name), new Claim(JwtClaimTypes.GivenName, user.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.GivenName)?.Value), new Claim(JwtClaimTypes.FamilyName, user.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.FamilyName)?.Value), new Claim(JwtClaimTypes.Email, user.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Email)?.Value) }; claims.AddRange(roleNames.Select(name => new Claim(JwtClaimTypes.Role, name, ClaimTypes.Role))); context.IssuedClaims.AddRange(claims); return(Task.FromResult(0)); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "该场景不存在!" })); } // 删除场景综合信息 mongo.DeleteOne(Constant.SceneCollectionName, filter); var collectionName = doc["CollectionName"].AsString; // 删除场景数据集 mongo.DropCollection(collectionName); return(Json(new { Code = 200, Msg = "删除场景成功!" })); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.ParticleCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The asset is not existed!" })); } mongo.DeleteOne(Constant.ParticleCollectionName, filter); return(Json(new { Code = 200, Msg = "Delete successfully!" })); }
public User GetByBlogId(string id) { var filterDefinition = new BsonDocument { { "Blogs", new BsonDocument { { "$filter", new BsonDocument { { "input", "$Blogs" }, { "as", "blog" }, { "cond", new BsonDocument { { "$eq", new BsonArray { "$$blog._id", BsonObjectId.Create(id) } } } } } } } } }; var res = users.Aggregate <User>() .Match(new BsonDocument { { "Blogs._id", BsonObjectId.Create(id) } }) .Project(filterDefinition) .ToList(); var user = BsonSerializer.Deserialize <User>(res.First()); return(user); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.PrefabCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "该资源不存在!" })); } mongo.DeleteOne(Constant.PrefabCollectionName, filter); return(Json(new { Code = 200, Msg = "删除成功!" })); }
public async Task <List <Channel> > RetrieveMany(List <string> keys) { var values = new List <BsonValue>(); foreach (var key in keys) { values.Add(BsonObjectId.Create(key)); } var filter = Builders <BsonDocument> .Filter.In("_id", values); var client = new MongoClient("mongodb://localhost"); var database = client.GetDatabase("minicord"); var collection = database.GetCollection <BsonDocument>("channels"); var channels = new List <Channel>(); await collection.Find(filter).ForEachAsync((x) => channels.Add(new Channel() { MessageIds = x.GetValue("message").IsBsonNull ? new List <string>() : x.GetValue("message").AsBsonArray.Select(x => x.IsObjectId ? x.AsObjectId.ToString() : x.AsString).ToList(), ParticipantIds = x.GetValue("participant").IsBsonNull ? new List <string>() : x.GetValue("participant").AsBsonArray.Select(x => x.IsObjectId ? x.AsObjectId.ToString() : x.AsString).ToList(), CreatedAt = x.GetValue("created_at").AsDateTime, Creator = x.GetValue("creator").AsString, Name = x.GetValue("channel_name").AsString, Picture = x.GetValue("channel_picture").AsString, Id = x.GetValue("_id").AsObjectId.ToString(), }) ); return(channels); }
public void TestBsonObjectIdEquals() { BsonObjectId lhs = BsonObjectId.Create(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); BsonObjectId rhs = BsonObjectId.Create(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); Assert.AreNotSame(lhs, rhs); Assert.AreEqual(lhs, rhs); Assert.AreEqual(lhs.GetHashCode(), rhs.GetHashCode()); }
public async Task <EventCommit> ByInternalId(string commitId) { Precondition.For(commitId, nameof(commitId)).NotNullOrWhiteSpace("CommitId must not be null!"); BsonObjectId id = BsonObjectId.Create(commitId); var query = Filters.Eq(x => x.Id, id); var commit = await Collection.Find(query).SortBy(x => x.Ordinal).FirstAsync(); return(commit); }
private BsonValue ParseObjectIdStrict() { VerifyToken(":"); var valueToken = PopToken(); if (valueToken.Type != JsonTokenType.String) { var message = string.Format("JSON reader expected a string but found: '{0}'", valueToken.Lexeme); throw new FileFormatException(message); } VerifyToken("}"); return(BsonObjectId.Create(valueToken.StringValue)); }
public JObject Update(string collection, JObject item, bool replace) { var dataContext = new Dictionary <string, object>(); var id = item["_id"].Value <string>(); var itemToCheck = item; if (replace == false) { itemToCheck = Get(collection, id); itemToCheck.Merge(item, new JsonMergeSettings() { MergeNullValueHandling = MergeNullValueHandling.Merge, MergeArrayHandling = MergeArrayHandling.Replace }); } InvokeValidation(itemToCheck, collection); //TODO: create collection if not exists EnsureCollection(collection); FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(item["_id"].Value <string>())); InvokeProcess(collection, ref item, PipelineStage.PreOperation, DataOperation.Write, dataContext); //insert id (mandatory) BsonDocument doc = BsonDocument.Parse(item.ToString()); doc["_id"] = BsonObjectId.Create(id); doc.Remove("_metadata"); UpdateOptions o = new UpdateOptions() { IsUpsert = true, BypassDocumentValidation = true }; if (replace) { _mongoService.GetCollection <BsonDocument>(collection).ReplaceOne(filter, doc, o); } else { BsonDocument dbset = new BsonDocument("$set", doc); _mongoService.GetCollection <BsonDocument>(collection).UpdateOne(filter, dbset, o); } var fullSaved = Get(collection, id); InvokeProcess(collection, ref fullSaved, PipelineStage.PostOperation, DataOperation.Write, dataContext); return(fullSaved); }
public JsonResult Download(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.MeshCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The asset is not existed!" })); } // 获取模型文件列表 var savePath = HttpContext.Current.Server.MapPath($"~{doc["SavePath"].ToString()}"); var queue = new Queue <string>(); queue.Enqueue(savePath); var fileLists = new List <string>(); while (queue.Count > 0) { var item = queue.Dequeue(); var dirs = Directory.GetDirectories(item); foreach (var i in dirs) { queue.Enqueue(i); } var files = Directory.GetFiles(item); fileLists.AddRange(files); } // 创建压缩包 var descFile = $"/temp/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.zip"; var descPhysicalFile = HttpContext.Current.Server.MapPath($"~{descFile}"); ZipHelper.Zip(fileLists, descPhysicalFile); return(Json(new { Code = 200, Msg = "Download successfully!", Path = descFile })); }
public JsonResult Load(string ID, int version = -1) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The scene is not existed!" })); } var collectionName = doc["CollectionName"].AsString; List <BsonDocument> docs; if (version == -1) // 最新版本 { docs = mongo.FindAll(collectionName).ToList(); } else // 特定版本 { filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version)); docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList(); } var data = new JArray(); foreach (var i in docs) { i["_id"] = i["_id"].ToString(); // ObjectId data.Add(JsonHelper.ToObject <JObject>(i.ToJson())); } return(Json(new { Code = 200, Msg = "Get Successfully!", Data = data })); }
public async Task has_expected_bson_datatypes() { BadgeRepo badgeRepo = CreateBadgeRepo(); // when PkmnSpecies randomSpecies = PkmnSpecies.OfId("9001"); Badge badge = await badgeRepo.AddBadge(null, randomSpecies, Badge.BadgeSource.RunCaught); // then IMongoCollection <BsonDocument> badgesCollectionBson = badgeRepo.Collection.Database.GetCollection <BsonDocument>("badges"); BsonDocument badgeBson = await badgesCollectionBson.Find(FilterDefinition <BsonDocument> .Empty).FirstAsync(); Assert.AreEqual(BsonObjectId.Create(ObjectId.Parse(badge.Id)), badgeBson["_id"]); Assert.AreEqual(BsonNull.Value, badgeBson["user"]); Assert.AreEqual(BsonString.Create(randomSpecies.Id), badgeBson["species"]); Assert.AreEqual(BsonString.Create("run_caught"), badgeBson["source"]); }
// POST: /Matches/Create/{FormCollection} private Match CreateMatch(User user, Match newMatch) { Match match = null; if (user != null) { var red1 = newMatch.RedPlayer1.Id; var red2 = string.IsNullOrWhiteSpace(newMatch.RedPlayer2.Id) ? string.Empty : newMatch.RedPlayer2.Id; var blue1 = newMatch.BluePlayer1.Id; var blue2 = string.IsNullOrWhiteSpace(newMatch.BluePlayer2.Id) ? string.Empty : newMatch.BluePlayer2.Id; // only try to create a match if properties are set correctly if (!string.IsNullOrEmpty(red1) && !string.IsNullOrEmpty(blue1)) { var playerCollection = Dbh.GetCollection <Player>("Players"); var redPlayer1 = string.IsNullOrEmpty(red1) ? new Player() : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(red1))); var redPlayer2 = string.IsNullOrEmpty(red2) ? new Player() : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(red2))); var bluePlayer1 = string.IsNullOrEmpty(blue1) ? new Player() : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(blue1))); var bluePlayer2 = string.IsNullOrEmpty(blue2) ? new Player() : playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(blue2))); match = new Match { RedPlayer1 = redPlayer1, RedPlayer2 = redPlayer2, BluePlayer1 = bluePlayer1, BluePlayer2 = bluePlayer2, RedScore = newMatch.RedScore, BlueScore = newMatch.BlueScore, CreationTime = DateTime.Now, GameOverTime = DateTime.MinValue, CreatedBy = user.Id, }; } } return(match); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.MeshCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "该资源不存在!" })); } // TODO:为避免误删等严重后果,暂时不删除文件 // 删除模型所在目录 //var path = doc["SavePath"].ToString(); //var physicalPath = HttpContext.Current.Server.MapPath(path); //try //{ // Directory.Delete(physicalPath, true); //} //catch (Exception ex) //{ // return Json(new // { // Code = 300, // Msg = ex.Message // }); //} // 删除模型信息 mongo.DeleteOne(Constant.MeshCollectionName, filter); return(Json(new { Code = 200, Msg = "删除成功!" })); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.TypefaceCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The asset is not existed!" })); } // 删除文件所在目录 var url = doc["Url"].ToString(); var physicalPath = HttpContext.Current.Server.MapPath($"~{url}"); var dir = Path.GetDirectoryName(physicalPath); try { Directory.Delete(dir, true); } catch (Exception ex) { return(Json(new { Code = 300, Msg = ex.Message })); } mongo.DeleteOne(Constant.TypefaceCollectionName, filter); return(Json(new { Code = 200, Msg = "Delete successfully!" })); }
static void Main(string[] args) { //MongoClient dbClient = new MongoDB.Driver.MongoClient("mongodb://127.0.0.1:27017"); //MongoClient dbClient = new MongoDB.Driver.MongoClient(); //var dbList = dbClient.ListDatabases().ToList(); //Console.WriteLine("The list of databases are :"); //foreach (var item in dbList) //{ // Console.WriteLine(item); //} for (int i = 0; i < 5; i++) { BsonObjectId id = BsonObjectId.Create(ObjectId.GenerateNewId(DateTime.Now)); Console.WriteLine(id); } }
private List <BsonObjectId> GetLookupValue(JToken input) { if (input == null) { return(new List <BsonObjectId>()); } // Array if (input.Type == JTokenType.Array) { return(input.Values <string>().Select(x => BsonObjectId.Create(x)).ToList()); } // Single value return(new List <BsonObjectId>() { BsonObjectId.Create(input.Value <string>()) }); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.AnimationCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The asset is not existed!" })); } // 删除模型所在目录 var path = doc["SavePath"].ToString(); var physicalPath = HttpContext.Current.Server.MapPath(path); try { Directory.Delete(physicalPath, true); } catch (Exception ex) { return(Json(new { Code = 300, Msg = ex.Message })); } // 删除信息 mongo.DeleteOne(Constant.AnimationCollectionName, filter); return(Json(new { Code = 200, Msg = "Delete successfully!" })); }
public JsonResult Delete(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.AudioCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "该音频不存在!" })); } // 删除音频所在目录 var path = doc["SavePath"].ToString(); var physicalPath = HttpContext.Current.Server.MapPath(path); try { Directory.Delete(physicalPath, true); } catch (Exception ex) { return(Json(new { Code = 300, Msg = ex.Message })); } // 删除音频信息 mongo.DeleteOne(Constant.AudioCollectionName, filter); return(Json(new { Code = 200, Msg = "删除音频成功!" })); }
// public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonObjectId)); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { return(BsonObjectId.Create((ObjectId)ObjectIdSerializer.Instance.Deserialize(bsonReader, typeof(ObjectId), options))); } }
public void TestAllTypes() { BsonDocument document = new BsonDocument { { "double", 1.23 }, { "string", "rosebud" }, { "document", new BsonDocument { { "hello", "world" } } }, { "array", new BsonArray { 1, 2, 3 } }, { "binary", new byte[] { 1, 2, 3 } }, { "objectid", BsonObjectId.Create(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 }) }, { "boolean1", false }, { "boolean2", true } }; byte[] bytes1 = document.ToBson(); byte[] bytes2 = BsonDocument.ReadFrom(bytes1).ToBson(); Assert.AreEqual(bytes1, bytes2); }
public JObject Update(string collection, JObject item, bool replace) { var dataContext = new Dictionary <string, object>(); //TODO: why do not manage validation as a simple presave process? InvokeValidation(item, collection); //TODO: create collection if not exists EnsureCollection(collection); FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(item["_id"].Value <string>())); InvokeProcess(collection, ref item, SavePipelineStage.PreSave, dataContext); var id = item["_id"].Value <string>(); //insert id (mandatory) BsonDocument doc = BsonDocument.Parse(item.ToString()); doc["_id"] = BsonObjectId.Create(id); UpdateOptions o = new UpdateOptions() { IsUpsert = true, BypassDocumentValidation = true }; if (replace) { _mongoService.GetCollection <BsonDocument>(collection).ReplaceOne(filter, doc, o); } else { BsonDocument dbset = new BsonDocument("$set", doc); _mongoService.GetCollection <BsonDocument>(collection).UpdateOne(filter, dbset, o); } var fullSaved = Get(collection, id); InvokeProcess(collection, ref fullSaved, SavePipelineStage.PostSave, dataContext); return(JObject.Parse(fullSaved.ToJson(js))); }
public ActionResult CreateTeamName(TeamName newTeamName) { var teamNameCollection = Dbh.GetCollection <TeamName>("TeamNames"); var playerCollection = Dbh.GetCollection <Player>("Players"); var player1 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(newTeamName.Team.Players[0].Id))); var player2 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Create(newTeamName.Team.Players[1].Id))); var teamName = new TeamName() { Name = newTeamName.Name, Team = new Team() { Players = new List <Player>() { player1, player2 } } }; teamNameCollection.Save(teamName); return(Json(new { success = true, newTeam = teamName })); }
public JsonResult Load(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "该场景不存在!" })); } var collectionName = doc["CollectionName"].AsString; var docs = mongo.FindAll(collectionName); var data = new JArray(); foreach (var i in docs) { i["_id"] = i["_id"].ToString(); // ObjectId data.Add(JsonHelper.ToObject <JObject>(i.ToJson())); } return(Json(new { Code = 200, Msg = "获取成功!", Data = data })); }
public JsonResult Get(string ID) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.ParticleCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The particle is not existed!" })); } var obj = new JObject { ["ID"] = doc["ID"].AsObjectId.ToString(), ["Name"] = doc["Name"].AsString, ["TotalPinYin"] = doc["TotalPinYin"].ToString(), ["FirstPinYin"] = doc["FirstPinYin"].ToString(), ["CreateTime"] = doc["CreateTime"].ToUniversalTime(), ["UpdateTime"] = doc["UpdateTime"].ToUniversalTime(), ["Data"] = JsonConvert.DeserializeObject <JObject>(doc["Data"].ToJson()), ["Thumbnail"] = doc["Thumbnail"].ToString(), }; return(Json(new { Code = 200, Msg = "Get Successfully!", Data = obj })); }
public bool Delete(string collection, string id) { EnsureCollection(collection); FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id)); DeleteResult result = _mongoService.GetCollection <BsonDocument>(collection).DeleteOne(filter); return(result.DeletedCount == 1); }
public JObject Get(string collection, string id) { FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", BsonObjectId.Create(id)); IFindFluent <BsonDocument, BsonDocument> results = _mongoService .GetCollection <BsonDocument>(collection) .Find <BsonDocument>(filter); List <BsonDocument> list = results.ToList(); BsonDocument item = list.FirstOrDefault(); string json = "{}"; //sanitize id format if (item != null) { item["_id"] = item["_id"].ToString(); json = item.ToJson(js); } return(JObject.Parse(json)); }
public JsonResult Run(string ID, int version = -1) { var mongo = new MongoHelper(); var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID)); var doc = mongo.FindOne(Constant.SceneCollectionName, filter); if (doc == null) { return(Json(new { Code = 300, Msg = "The scene is not existed!" })); } // 获取场景数据 var collectionName = doc["CollectionName"].AsString; List <BsonDocument> docs; if (version == -1) // 最新版本 { docs = mongo.FindAll(collectionName).ToList(); } else // 特定版本 { filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version)); docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList(); } // 创建临时目录 var now = DateTime.Now; var path = HttpContext.Current.Server.MapPath($"~/temp/{now.ToString("yyyyMMddHHmmss")}"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // 拷贝静态资源 var viewPath = HttpContext.Current.Server.MapPath("~/view.html"); var viewFileData = File.ReadAllText(viewPath, Encoding.UTF8); viewFileData = viewFileData.Replace("location.origin", "'.'"); // 替换server地址,以便部署到Git Pages上 File.WriteAllText($"{path}/view.html", viewFileData, Encoding.UTF8); var faviconPath = HttpContext.Current.Server.MapPath("~/favicon.ico"); File.Copy(faviconPath, $"{path}/favicon.ico", true); var assetsPath = HttpContext.Current.Server.MapPath($"~/assets"); DirectoryHelper.Copy(assetsPath, $"{path}/assets"); var buildPath = HttpContext.Current.Server.MapPath($"~/build"); DirectoryHelper.Copy(buildPath, $"{path}/build"); // 分析场景,拷贝使用的资源 var data = new JArray(); var urls = new List <string>(); foreach (var i in docs) { i["_id"] = i["_id"].ToString(); // ObjectId var generator = i["metadata"]["generator"].ToString(); if (generator == "ServerObject") // 服务端模型 { urls.Add(i["userData"]["Url"].ToString()); // 模型文件 if (i["userData"].AsBsonDocument.Contains("Animation")) // MMD模型动画 { urls.Add(i["userData"]["Animation"]["Url"].ToString()); } if (i["userData"].AsBsonDocument.Contains("CameraAnimation")) // MMD相机动画 { urls.Add(i["userData"]["CameraAnimation"]["Url"].ToString()); } if (i["userData"].AsBsonDocument.Contains("Audio")) // MMD音频 { urls.Add(i["userData"]["Audio"]["Url"].ToString()); } } else if (generator == "SceneSerializer") // 场景 { if (i["background"].IsBsonDocument) // 贴图或立方体纹理 { if (i["background"]["metadata"]["generator"].ToString() == "CubeTextureSerializer") // 立方体纹理 { var array = i["background"]["image"].AsBsonArray; foreach (var j in array) { urls.Add(j["src"].ToString()); } } else // 普通纹理 { urls.Add(i["background"]["image"]["src"].ToString()); } } } else if (generator == "MeshSerializer" || generator == "SpriteSerializer") // 模型 { if (i["material"]["alphaMap"].IsBsonDocument) { urls.Add(i["material"]["alphaMap"]["image"]["src"].ToString()); } else if (i["material"]["aoMap"].IsBsonDocument) { urls.Add(i["material"]["aoMap"]["image"]["src"].ToString()); } else if (i["material"]["bumpMap"].IsBsonDocument) { urls.Add(i["material"]["bumpMap"]["image"]["src"].ToString()); } else if (i["material"]["displacementMap"].IsBsonDocument) { urls.Add(i["material"]["displacementMap"]["image"]["src"].ToString()); } else if (i["material"]["emissiveMap"].IsBsonDocument) { urls.Add(i["material"]["emissiveMap"]["image"]["src"].ToString()); } else if (i["material"]["envMap"].IsBsonDocument) { urls.Add(i["material"]["envMap"]["image"]["src"].ToString()); } else if (i["material"]["lightMap"].IsBsonDocument) { urls.Add(i["material"]["lightMap"]["image"]["src"].ToString()); } else if (i["material"]["map"].IsBsonDocument) { urls.Add(i["material"]["map"]["image"]["src"].ToString()); } else if (i["material"]["metalnessMap"].IsBsonDocument) { urls.Add(i["material"]["metalnessMap"]["image"]["src"].ToString()); } else if (i["material"]["normalMap"].IsBsonDocument) { urls.Add(i["material"]["normalMap"]["image"]["src"].ToString()); } else if (i["material"]["roughnessMap"].IsBsonDocument) { urls.Add(i["material"]["roughnessMap"]["image"]["src"].ToString()); } } data.Add(JsonHelper.ToObject <JObject>(i.ToJson())); } // 将场景写入文件 if (!Directory.Exists($"{path}/Scene")) { Directory.CreateDirectory($"{path}/Scene"); } // 复制资源 var file = new FileStream($"{path}/Scene/{ID}.txt", FileMode.Create, FileAccess.Write); var writer = new StreamWriter(file); writer.Write(JsonHelper.ToJson(data)); writer.Close(); file.Close(); foreach (var url in urls) { if (!url.StartsWith("/")) // 可能是base64地址 { continue; } // LOL模型存在多个url,两个url之间用分号分隔 var _urls = url.Split(';'); foreach (var _url in _urls) { if (string.IsNullOrEmpty(_url)) { continue; } var sourceDirName = Path.GetDirectoryName(HttpContext.Current.Server.MapPath($"~{_url}")); var targetDirName = Path.GetDirectoryName($"{path}{_url}"); DirectoryHelper.Copy(sourceDirName, targetDirName); } } return(Json(new { Code = 200, Msg = "Export successfully!", Url = $"/temp/{now.ToString("yyyyMMddHHmmss")}/view.html?sceneFile={ID}" })); }