public void CreateCollection(string collectionName) { if (!m_collections.ContainsKey(collectionName)) { m_collections[collectionName] = new CollectionInfo(collectionName); } }
public static List <SelectOption> GetCollectionDataEnum(CollectionInfo collectionInfo, List <int> values = null) { Type enumType = Type.GetType(collectionInfo.SourceExp); FieldInfo[] fields = enumType.GetFields(); var list = new List <SelectOption>(); foreach (var field in fields) { if (field.Name.Equals("value__")) { continue; } var v = (int)field.GetRawConstantValue(); if (values != null) { if (!values.Contains(v)) { continue; } } var d = new SelectOption(); d.Add("Value", v); d.Add("Text", field.Name); list.Add(d); } return(list); }
public CollectionInfo ReadInfo() { if (_disposed) { throw new ObjectDisposedException("InpxReader was disposed"); } var info = new CollectionInfo(); var collectionInfoEntry = _zipArchive.GetEntry(EntryNames.Collection); using (var stream = collectionInfoEntry.Open()) using (var reader = new StreamReader(stream)) { info.Name = reader.ReadLine(); info.FileName = reader.ReadLine(); info.Type = reader.ReadLine(); if (!reader.EndOfStream) { info.Description = reader.ReadToEnd(); } } var versionInfoEntry = _zipArchive.GetEntry(EntryNames.Version); using (var stream = versionInfoEntry.Open()) using (var reader = new StreamReader(stream)) { info.Version = reader.ReadLine(); } return(info); }
public async Task <ActionResult <CollectionInfo> > AddOrEditCollection(int postId, [FromQuery] int privacy) { // 收藏存在则修改,否则添加 var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!int.TryParse(userId, out int uid)) { return(BadRequest(new { error = "Unknow user ID." })); } var col = await _repo.GetCollection(uid, postId); if (col == null) { try { return(CollectionInfo.FromCollection(await _repo.SaveCollection(uid, postId, privacy))); } catch { return(NotFound()); } } else { return(CollectionInfo.FromCollection(await _repo.UpdateCollection(uid, postId, privacy))); } }
public CollectionInfo GetMagicKeyInfo() { if (m_CacheMagicKeyInfo.Count > 0) { CollectionInfo info = m_CacheMagicKeyInfo.Pop(); info.gameObject.SetActive(true); return(info); } GameObject prefab = null; prefab = (GameObject)CoreEntry.gResLoader.Load(MagickeyInfoPrefab, typeof(GameObject)); if (prefab == null) { return(null); } GameObject obj = GameObject.Instantiate(prefab) as GameObject; RectTransform rt = obj.GetComponent <RectTransform>(); CollectionInfo ret = obj.GetComponent <CollectionInfo>(); obj.SetActive(true); rt.SetParent(HPBarRoot); rt.anchoredPosition3D = Vector3.zero; rt.localScale = Vector3.one; return(ret); }
public static bool SaveOrUpdateCollectionInfo(CollectionInfo ci) { bool result = false; try { using (MainDataContext db = new MainDataContext()) { CollectionInfo info = db.CollectionInfos.FirstOrDefault(p => p.CollectionID == ci.CollectionID); if (info == null) { db.CollectionInfos.InsertOnSubmit(ci); } else { info.QuestionCount = ci.QuestionCount; info.CollectionName = ci.CollectionName; info.CollectionUrl = ci.CollectionUrl; info.CreatorHash = ci.CreatorHash; info.CreatorName = ci.CreatorName; info.ModefiedTime = DateTime.Now.ToString(); } db.SubmitChanges(); result = true; } } catch (Exception ex) { } return(result); }
private bool loadCollection(string path) { if (!File.Exists(path)) { return(false); } CollectionInfo info = new CollectionInfo(); info.Path = path; //Load collection from file try { TextReader reader = new StreamReader(path); info.Item = Collection.Deserialize(reader); reader.Close(); } catch (Exception ex) { MessageBox.Show("Error loading collection from file: \n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } collections.Add(info); newCollectionWindow(info.Item); return(true); }
public static void GetCollectionAnswerInfoFromHtml(string html, CollectionInfo ci) { if (!String.IsNullOrWhiteSpace(html)) { try { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNodeCollection answerNodes = doc.DocumentNode.SelectNodes(@"//div[@class='zm-item-rich-text js-collapse-body']"); foreach (HtmlNode answer in answerNodes) { string ids = answer.Attributes.FirstOrDefault(p => p.Name == "data-entry-url").Value; string[] idsArr = ids.Split('/'); CollectionQuestionAndAnswer cqa = new CollectionQuestionAndAnswer() { CollectionID = ci.CollectionID, QuestionID = int.Parse(idsArr[2]), AnswerID = int.Parse(idsArr[4]), ModefiedTime = DateTime.Now.ToString(), }; CollectionDB.SaveOrUpdateCollectionAnswer(cqa); Console.WriteLine("答案:" + cqa.AnswerID + " 于" + DateTime.Now.ToString() + "保存成功"); } } catch (Exception ex) { } } }
protected BnfiTermCollection(Type collectionTypeOrTypeDefinition, Type elementTypeHint, string name, bool runtimeCheck) : base(GetCollectionInfo(collectionTypeOrTypeDefinition, elementTypeHint, runtimeCheck).collectionType, name) { CollectionInfo collectionInfo = GetCollectionInfo(collectionTypeOrTypeDefinition, elementTypeHint, runtimeCheck); Type collectionType = collectionInfo.collectionType; this.domainElementType = collectionInfo.elementType; if (runtimeCheck) { #if !WINDOWS_STORE #if PCL if (collectionType.GetConstructor(new Type[0]) == null) #else if (collectionType.GetConstructor(BnfiTermRecord.bindingAttrInstanceAll, System.Type.DefaultBinder, types: System.Type.EmptyTypes, modifiers: null) == null) #endif { throw new ArgumentException("Collection type has no default constructor (neither public nor nonpublic)", "type"); } #endif #if PCL this.addMethod = collectionType.GetMethod("Add", new[] { domainElementType }); #else this.addMethod = collectionType.GetMethod("Add", BnfiTermRecord.bindingAttrInstanceAll, System.Type.DefaultBinder, new[] { domainElementType }, modifiers: null); #endif if (this.addMethod == null) { throw new ArgumentException("Collection type has proper 'Add' method (neither public nor nonpublic)", "collectionType"); } } this.EmptyCollectionHandling = Sarcasm.GrammarAst.Grammar.CurrentGrammar.EmptyCollectionHandling; SetNodeCreator(); }
public static CollectionInfo GetCollectionInfo(string collectionName, object inputType) { try { var result = new CollectionInfo() { Name = collectionName }; var type = inputType.GetType(); var properties = type.GetProperties(); foreach (var property in properties) { if (!result.Properties.Exists(x => x.Name == property.Name)) { result.Properties.Add(new Property() { Name = property.Name, Type = property.PropertyType.FullName }); } } return(result); } catch (Exception e) { throw new Exception($"Reflector GetCollectionInfo Error: {e.Message}"); } }
private IDbCommand GetClearCollectionCommand( Object obj, ColumnCollectionInfo dataInfo, CollectionInfo collectionInfo, IDbConnection conn, ColumnInfo targetPrimaryKeyInfo = null, object targetPrimaryKey = null) { IDbCommand command = conn.CreateCommand(); string sql = string.Format(DeleteSql, collectionInfo.IntermediateTableName); ColumnInfo primaryKeyColumn = dataInfo.PrimaryKeys.Values.OfType <ColumnInfo>().Single(); string parameterName = string.Format(UpdateSqlValueParameter, 0); string whereSql = collectionInfo.MapSourceKey + Equal + parameterName; AddParameter(primaryKeyColumn, parameterName, primaryKeyColumn.GetValue(obj), command); if (targetPrimaryKeyInfo != null && targetPrimaryKey != null) { parameterName = string.Format(UpdateSqlValueParameter, 1); whereSql = whereSql + And + collectionInfo.MapTargetKey + Equal + parameterName; AddParameter(targetPrimaryKeyInfo, parameterName, targetPrimaryKey, command); } sql = string.Format(WhereSql, sql, whereSql); command.CommandText = sql; return(command); }
private ItemViewModel CreateItemViewModel(string aUserName, Guid aId) { if (!mItemInfo.ContainsKey(aId)) { return(null); } CollectionInfo theCollection = null; if (aUserName != null) { if (mCardCollection.ContainsKey(aUserName) && mCardCollection[aUserName].ContainsKey(aId)) { theCollection = mCardCollection[aUserName][aId]; } if (mInventoryCollection.ContainsKey(aUserName) && mInventoryCollection[aUserName].ContainsKey(aId)) { theCollection = mInventoryCollection[aUserName][aId]; } } AuctionHouseInfo theAuctionHouse = null; if (mAuctionHouseData.ContainsKey(aId)) { theAuctionHouse = mAuctionHouseData[aId]; } return(new ItemViewModel(aId, mItemInfo[aId], theCollection, theAuctionHouse)); }
public ActionResult PayAll(FormCollection formCollection) { try { string[] ids = formCollection["ClientId"].Split(new char[] { ',' }); foreach (string id in ids) { var i = Int32.Parse(id); var clients = _clientservice.GetById(i); CollectionInfo collection = new CollectionInfo(); collection.Amount = clients.Data.Due; collection.UserName = clients.Data.UserName; var a = clients.Data.Due; clients.Data.Due = 0; collection.UserId = clients.Data.ClientId; clients.Data.Pay += a; var result = _clientservice.Payment(clients.Data); _collectionservice.Save(collection); if (clients.HasError) { ViewBag.Message = clients.Message; return(Content("Problem is : " + clients.Message)); } } } catch (Exception) { return(RedirectToAction("ClientShowAll", "ClientInfo", new{ id = 1 })); } return(RedirectToAction("ClientShowAll", "ClientInfo")); }
private void newToolStripMenuItem_Click(object sender, EventArgs e) { CollectionInfo info = new CollectionInfo(); collections.Add(info); newCollectionWindow(info.Item); }
public ActionResult FullPay(int id) { try { var clients = _clientservice.GetById(id); CollectionInfo collection = new CollectionInfo(); collection.Amount = clients.Data.Due; collection.UserName = clients.Data.UserName; var a = clients.Data.Due; clients.Data.Due = 0; collection.UserId = clients.Data.ClientId; clients.Data.Pay += a; var result = _clientservice.Payment(clients.Data); _collectionservice.Save(collection); if (clients.HasError) { ViewBag.Message = clients.Message; return(Content("Problem is : " + clients.Message)); } } catch (Exception ex) { return(Content(ex.Message)); } return(RedirectToAction("ClientShowAll", "ClientInfo")); }
public static void Compare( string expectedName, string expectedDescription, ConfigurationRequirementType expectedType, bool expectedOptionality, CollectionInfo collectionInfo, IEnumerable <IConfigurationRequirement> dependsOn, IEnumerable <IConfigurationRequirement> exclusiveWith, Func <IConfigurationRequirement> requirementFactory, object badInput, object goodInput) { IConfigurationRequirement requirement = requirementFactory.Invoke(); Assert.AreEqual(expectedName, requirement.Name); Assert.AreEqual(expectedDescription, requirement.Description); Assert.AreEqual(expectedType, requirement.OfType); Assert.AreEqual(expectedOptionality, requirement.IsOptional); Assert.AreEqual(collectionInfo, requirement.CollectionInfo); CollectionAssert.AreEquivalent(dependsOn.ToArray(), requirement.DependsOn.ToArray()); CollectionAssert.AreEquivalent(exclusiveWith.ToArray(), requirement.ExclusiveWith.ToArray()); Assert.AreEqual(typeof(ArgumentNullException), requirement.Validate(null).GetType()); Assert.AreEqual(typeof(ArgumentException), requirement.Validate(badInput).GetType()); Assert.IsNull(requirement.Validate(goodInput)); }
public static void GetCollectionInfoFormHtml(string html, string collectionId) { if (!String.IsNullOrWhiteSpace(html)) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNode nameNode = doc.DocumentNode.SelectSingleNode(@"//h2[@id='zh-fav-head-title']"); HtmlNodeCollection fllowerNodes = doc.DocumentNode.SelectNodes(@"//div[@class='zg-gray-normal']"); HtmlNode creatorNode = doc.DocumentNode.SelectSingleNode(@"//h2[@class='zm-list-content-title']"); string fllowercount = ((HtmlNode)fllowerNodes[2]).SelectSingleNode(@"a").InnerText.Replace("\n", ""); CollectionInfo ci = new CollectionInfo() { CollectionID = int.Parse(collectionId), CollectionName = nameNode.InnerText.Replace("\n", ""), CollectionUrl = string.Format(CollectionInfoBaseUrl, collectionId), FllowersCount = int.Parse(fllowercount), QuestionCount = 0, CreatorName = creatorNode.InnerText.Replace("\n", ""), ModefiedTime = DateTime.Now.ToString(), }; CollectionDB.SaveOrUpdateCollectionInfo(ci); Console.WriteLine("收藏夹:" + ci.CollectionID + " " + ci.CollectionName + " 于" + ci.ModefiedTime + "保存完成"); Thread.Sleep(1000 * 5); } }
public static void LoadCollectionIDsFormFile() { string filePath = System.Environment.CurrentDirectory + @"\CollectionID.txt"; if (File.Exists(filePath)) { string fileStr = File.ReadAllText(filePath); IEnumerable <CollectionInfo> infos = CollectionDB.GetAllCollectionInfos().ToList(); foreach (var ci in infos) { fileStr = fileStr.Replace(ci.CollectionID.ToString() + ":" + ci.QuestionCount, ""); } string[] collectionIds = fileStr.Replace(";", "|").Split('|'); foreach (string id in collectionIds) { if (!String.IsNullOrEmpty(id)) { string[] ids = id.Split(':'); CollectionInfo ci = CollectionDB.GetCollectionInfoById(ids[0]); if (ci != null) { ci.QuestionCount = int.Parse(ids[1]); CollectionDB.SaveOrUpdateCollectionInfo(ci); } else { string url = string.Format(CollectionInfoBaseUrl, ids[0]); GetCollectionInfoFormHtml(BusinessUtils.GetByUrl(url), ids[0]); } } } } }
public ActionResult DeleteConfirmed(int id) { CollectionInfo collectionInfo = db.CollectionInfo.Find(id); db.CollectionInfo.Remove(collectionInfo); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// The load weapons. /// </summary> /// <param name="WeaponsList">The weapons list.</param> /// <remarks></remarks> public void LoadWeapons(ref List <CollectionInfo> WeaponsList) { if (WeaponsList == null) { WeaponsList = new List <CollectionInfo>(); } else { WeaponsList.Clear(); } map.OpenMap(MapTypes.Internal); // Lists all weapons for (int i = 0; i < map.MetaInfo.TagType.Length; i++) { if ((map.MetaInfo.TagType[i] == "itmc") || (map.MetaInfo.TagType[i] == "vehc")) { CollectionInfo Weapon = new CollectionInfo(); Meta m = new Meta(map); m.ReadMetaFromMap(i, false); Weapon.ItmcTagNumber = i; // Base address of ITMC tag, offset of WEAP pointer (+20) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.ItmcTagNumber] + 20; Weapon.WeapTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); if (Weapon.WeapTagNumber == -1) { continue; } // Base address of WEAP tag, offset of HLMT pointer (+56) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.WeapTagNumber] + 56; Weapon.HlmtTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); if (Weapon.HlmtTagNumber != -1) { // Base address of HLMT tag, offset of MODE pointer (+4) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.HlmtTagNumber] + 4; Weapon.ModelTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); m.ReadMetaFromMap(Weapon.ModelTagNumber, false); Weapon.Model = new ParsedModel(ref m); ParsedModel.DisplayedInfo.LoadDirectXTexturesAndBuffers(ref device, ref Weapon.Model); // Store names into Weapon Weapon.TagPath = map.FileNames.Name[i]; Weapon.TagType = map.MetaInfo.TagType[i]; int xx = map.Functions.ForMeta.FindByNameAndTagType(Weapon.TagType, Weapon.TagPath); string[] NameSplit = map.FileNames.Name[xx].Split('\\'); Weapon.Name = NameSplit[NameSplit.Length - 1]; Weapon.Name = Weapon.Name.Replace('_', ' '); WeaponsList.Add(Weapon); } } } map.CloseMap(); }
public void RemoveMagicKeyInfo(CollectionInfo info) { if (info == null || info.gameObject == null) { return; } info.gameObject.SetActive(false); m_CacheMagicKeyInfo.Push(info); }
public async Task <bool> MoveNextAsync(CancellationToken cancellationToken) { var resultFound = false; var hasCurrent = false; while (!resultFound) { cancellationToken.ThrowIfCancellationRequested(); if (_entries == null) { var nextCollectionInfo = _collections.Dequeue(); _collection = nextCollectionInfo.Collection; _currentDepth = nextCollectionInfo.Depth; var children = nextCollectionInfo.Children ?? await _collection.GetChildrenAsync(cancellationToken); _entries = children.GetEnumerator(); } if (_entries.MoveNext()) { var coll = _entries.Current as ICollection; if (_currentDepth < _maxDepth && coll != null) { IReadOnlyCollection <IEntry> children; try { children = await coll.GetChildrenAsync(cancellationToken); } catch (Exception) { // Ignore errors children = new IEntry[0]; } var collectionInfo = new CollectionInfo(coll, children, _currentDepth + 1); _collections.Enqueue(collectionInfo); } if (_currentDepth >= 0) { Current = _entries.Current; resultFound = true; hasCurrent = true; } } else { Current = null; _entries.Dispose(); _entries = null; resultFound = _collections.Count == 0; } } return(hasCurrent); }
protected override void Seed(EntityDataContext context) { var category = new Category() { Name = ".NET", Value = "DotNet" }; var category2 = new Category() { Name = "jQuery", Value = "jQuery" }; var collection = new CollectionInfo() { Name = "Blog" }; var person = new Person() { DisplayName = "Ronald", EmailHash = "*****@*****.**" }; //context.People.Add(person); var entry1 = new BlogEntry() { Title = "Entry title", CreationDate = DateTimeOffset.Now, Content = "<p>This is some content</p>", StrippedDownTitle = "entry_title", Author = person, Categories = { category, category2 }, BlogEntryId = Guid.NewGuid(), TotalComments = 0 }; var entry2 = new BlogEntry() { Title = "Another Entry title", CreationDate = DateTimeOffset.Now, Content = "<p>This is some content</p>", StrippedDownTitle = "another_entry_title", Author = person, Categories = { category }, BlogEntryId = Guid.NewGuid(), TotalComments = 0 }; context.BlogEntries.Add(entry1); context.BlogEntries.Add(entry2); //context.Categories.Add(category); //context.Categories.Add(category2); context.CollectionInfos.Add(collection); }
public async Task <ActionResult <CollectionInfo> > DeleteCollection(int postId) { var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!int.TryParse(userId, out int uid)) { return(BadRequest(new { error = "Unknow user ID." })); } return(CollectionInfo.FromCollection(await _repo.DeleteCollection(uid, postId))); }
public void OnBeginLoadScen(GameEvent ge, EventParameter parameter) { Dictionary <long, CollectionInfo> .Enumerator iter = m_MagicKeyInfo.GetEnumerator(); while (iter.MoveNext()) { CollectionInfo v = iter.Current.Value; GameObject.Destroy(v.gameObject); } m_MagicKeyInfo.Clear(); }
public ActionResult Edit([Bind(Include = "id,user_id,title,url")] CollectionInfo collectionInfo) { if (ModelState.IsValid) { db.Entry(collectionInfo).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(collectionInfo)); }
//a method that returns whether a resource type can be further collected or not: public bool CanCollectResourceType(CollectionInfo ci) { //get the collection info: if (ci != null) { return(collectorRegulatorIns.GetCurrentInstances().Count *ci.maxCollectorsRatioRange.getRandomValue() > ci.collectorsAmount); } return(false); }
/// <summary> /// Creates the collection. /// </summary> /// <returns></returns> private IEnumerable <CollectionInfo> CreateCollection() { List <CollectionInfo> list = new List <CollectionInfo>(); var collection = new CollectionInfo(); collection.Name = "TestCollection"; list.Add(collection); return(list.AsEnumerable()); }
public ActionResult MakeCollection(long resid, string resname, string rescategorymain, string rescategorysecond, string resprice, string seller, string sellerphone, string sellerschool, string collector, string collectorphone, string collectorschool) { var newcollection = new CollectionInfo(); var updatethingcolnum = res.Things.Find(resid); var ownercollection = collection.Collections.ToList(); string result = "true"; var findthing = res.Things.ToList(); var collectionpic = ""; var whethersell = ""; var whetherdown = ""; long thingcolnum = 0;; for (var x = 0; x < ownercollection.Count; x++) { if (ownercollection[x].ResID == resid && ownercollection[x].Collector == collector && ownercollection[x].WhetherCancel == "0") { result = "false"; break; } } if (result == "true") { collectionpic = updatethingcolnum.ResPicture; whethersell = updatethingcolnum.WhetherSell; whetherdown = updatethingcolnum.WhetherDown; thingcolnum = updatethingcolnum.ResColNum + 1; updatethingcolnum.ResColNum = thingcolnum; res.Entry(updatethingcolnum).State = EntityState.Modified;//点击收藏后收藏数量加1 res.SaveChanges(); newcollection.ResID = resid; newcollection.ResName = resname; newcollection.ResCategoryMain = rescategorymain; newcollection.ResCategorySecond = rescategorysecond; newcollection.ResPrice = resprice; newcollection.ResPicture = collectionpic; newcollection.Seller = seller; newcollection.SellerPhone = sellerphone; newcollection.SellerSchool = sellerschool; newcollection.ShelfTime = updatethingcolnum.ShelfTime; newcollection.WhetherSell = whethersell; newcollection.WhetherDown = whetherdown; newcollection.Collector = collector; newcollection.CollectorPhone = collectorphone; newcollection.CollectorSchool = collectorschool; newcollection.WhetherCancel = "0"; collection.Collections.Add(newcollection);//保存收藏信息 collection.SaveChanges(); } return(Content(result)); }
protected CollectionInfo GetCollectionInfo(WebDavTicket ticket) { CollectionInfo retVal = new CollectionInfo(); retVal.Name = "root"; retVal.Created = DateTime.MinValue; retVal.Modified = DateTime.MinValue; retVal.AbsolutePath = ticket.ToString(); return(retVal); }
public override Mediachase.Net.Wdom.WebDavElementInfo GetElementInfo(string path) { WebDavElementInfo retVal = null; retVal = new CollectionInfo(); retVal.Name = "root"; retVal.Created = DateTime.Now; retVal.Modified = retVal.Created; retVal.AbsolutePath = path; return retVal; }
/// <summary> /// The load weapons. /// </summary> /// <param name="WeaponsList">The weapons list.</param> /// <remarks></remarks> public void LoadWeapons(ref List<CollectionInfo> WeaponsList) { if (WeaponsList == null) { WeaponsList = new List<CollectionInfo>(); } else { WeaponsList.Clear(); } map.OpenMap(MapTypes.Internal); // Lists all weapons for (int i = 0; i < map.MetaInfo.TagType.Length; i++) { if ((map.MetaInfo.TagType[i] == "itmc") || (map.MetaInfo.TagType[i] == "vehc")) { CollectionInfo Weapon = new CollectionInfo(); Meta m = new Meta(map); m.ReadMetaFromMap(i, false); Weapon.ItmcTagNumber = i; // Base address of ITMC tag, offset of WEAP pointer (+20) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.ItmcTagNumber] + 20; Weapon.WeapTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); if (Weapon.WeapTagNumber == -1) { continue; } // Base address of WEAP tag, offset of HLMT pointer (+56) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.WeapTagNumber] + 56; Weapon.HlmtTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); if (Weapon.HlmtTagNumber != -1) { // Base address of HLMT tag, offset of MODE pointer (+4) map.BR.BaseStream.Position = map.MetaInfo.Offset[Weapon.HlmtTagNumber] + 4; Weapon.ModelTagNumber = map.Functions.ForMeta.FindMetaByID(map.BR.ReadInt32()); m.ReadMetaFromMap(Weapon.ModelTagNumber, false); Weapon.Model = new ParsedModel(ref m); ParsedModel.DisplayedInfo.LoadDirectXTexturesAndBuffers(ref device, ref Weapon.Model); // Store names into Weapon Weapon.TagPath = map.FileNames.Name[i]; Weapon.TagType = map.MetaInfo.TagType[i]; int xx = map.Functions.ForMeta.FindByNameAndTagType(Weapon.TagType, Weapon.TagPath); string[] NameSplit = map.FileNames.Name[xx].Split('\\'); Weapon.Name = NameSplit[NameSplit.Length - 1]; Weapon.Name = Weapon.Name.Replace('_', ' '); WeaponsList.Add(Weapon); } } } map.CloseMap(); }
protected CollectionInfo GetCollectionInfo(WebDavTicket ticket) { CollectionInfo retVal = new CollectionInfo(); retVal.Name = "root"; retVal.Created = DateTime.MinValue; retVal.Modified = DateTime.MinValue; retVal.AbsolutePath = ticket.ToString(); return retVal; }
/// <summary> /// The load weapons. /// </summary> /// <param name="WeaponsList">The weapons list.</param> /// <remarks></remarks> public void LoadWeapons(ref List<CollectionInfo> WeaponsList) { if (WeaponsList == null) { WeaponsList = new List<CollectionInfo>(); } else { WeaponsList.Clear(); } map.OpenMap(MapTypes.Internal); // Lists all weapons for (int i = 0; i < map.MetaInfo.TagType.Length; i++) { if ((map.MetaInfo.TagType[i] == "itmc") || (map.MetaInfo.TagType[i] == "vehc")) { CollectionInfo Weapon = new CollectionInfo(); Meta m = new Meta(map); m.ReadMetaFromMap(i, false); Weapon.ModelTagNumber = map.Functions.FindModelByBaseClass(i); if (Weapon.ModelTagNumber != -1) { m.ReadMetaFromMap(Weapon.ModelTagNumber, false); Weapon.Model = new ParsedModel(ref m); ParsedModel.DisplayedInfo.LoadDirectXTexturesAndBuffers(ref device, ref Weapon.Model); // Store names into Weapon Weapon.TagPath = map.FileNames.Name[i]; Weapon.TagType = map.MetaInfo.TagType[i]; int xx = map.Functions.ForMeta.FindByNameAndTagType(Weapon.TagType, Weapon.TagPath); string[] NameSplit = map.FileNames.Name[xx].Split('\\'); Weapon.Name = NameSplit[NameSplit.Length - 1]; Weapon.Name = Weapon.Name.Replace('_', ' '); WeaponsList.Add(Weapon); } } } map.CloseMap(); }
private bool loadCollection(string path) { if (!File.Exists(path)) return false; CollectionInfo info = new CollectionInfo(); info.Path = path; //Load collection from file try { TextReader reader = new StreamReader(path); info.Item = Collection.Deserialize(reader); reader.Close(); } catch (Exception ex) { MessageBox.Show("Error loading collection from file: \n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } collections.Add(info); newCollectionWindow(info.Item); return true; }
private static void Maintainance(object o) { try { var url = o as MongodbServerUrl; LocalLoggingService.Info("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "服务器", string.Format("对服务器 '{0}' 开始一次维护", url.Name)); Stopwatch sw = Stopwatch.StartNew(); ServerInfo oldServerInfo = null; locker.EnterReadLock(); if (servers.ContainsKey(url)) oldServerInfo = servers[url]; locker.ExitReadLock(); var serverInfo = new ServerInfo(); serverInfo.Url = url; serverInfo.Databases = new List<DatabaseInfo>(); var server = MongoServer.Create(url.Master); //元数据 var metaDatabase = server.GetDatabase(MongodbServerConfiguration.MetaDataDbName); var metaCollectionNames = metaDatabase.GetCollectionNames().Where(name => !name.Contains("system.index") && !name.Contains("$")).ToList(); var descriptions = new List<MongodbDatabaseDescription>(); foreach (var metaCollectionName in metaCollectionNames) { try { var metaCollection = metaDatabase.GetCollection(metaCollectionName); descriptions.Add(metaCollection.FindOneAs<MongodbDatabaseDescription>()); } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "获取元数据出错",ex.Message); } } serverInfo.Descriptions = descriptions; //获取所有的数据库 var databaseNames = server.GetDatabaseNames().Where(name => { var categories = descriptions.Select(description => description.DatabasePrefix).Distinct(); foreach (var categoryName in categories) { if (name.StartsWith(categoryName)) return true; } return false; }).ToList(); Parallel.ForEach(databaseNames, databaseName => { var swdb = Stopwatch.StartNew(); if (!databaseName.Contains("__")) { LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("数据库名 '{0}' 不包含__", databaseName)); return; } var datepart = databaseName.Substring(databaseName.LastIndexOf("__") + 2); if (datepart.Length != 6) { LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("数据名 '{0}' 日期部分长度不为6", databaseName)); return; } try { if (fristLoaded && oldServerInfo != null && oldServerInfo.Databases.Exists(db => db.DatabaseName == databaseName) && datepart != DateTime.Now.ToString("yyyyMM")) { var oldDb = oldServerInfo.Databases.SingleOrDefault(db => db.DatabaseName == databaseName); if (oldDb != null) { if (!serverInfo.Databases.Contains(oldDb)) { serverInfo.Databases.Add(oldDb); } LocalLoggingService.Debug("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("对数据库 '{0}' 完成一次维护,直接使用现有数据.oldServerInfo", databaseName)); return; } } } catch (Exception ex) { string reason = ""; if (oldServerInfo.Databases == null) reason = "oldServerInfo.Databases == null"; else if (oldServerInfo.Databases.Exists(d => d == null)) reason = "oldServerInfo.Databases.Exists(d => d == null)"; else reason = "other"; LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", string.Format("获取已有数据库 {0} 出错:{1}", databaseName, reason), ex.ToString()); } var database = server.GetDatabase(databaseName); var databaseInfo = new DatabaseInfo(); databaseInfo.DatabaseName = databaseName; try { var databaseStatusResult = database.GetStats();//获取数据库信息 if (databaseStatusResult != null) { var databaseStatus = new DatabaseStatus { AverageObjectSize = databaseStatusResult.AverageObjectSize, CollectionCount = databaseStatusResult.CollectionCount, DataSize = databaseStatusResult.DataSize, FileSize = databaseStatusResult.FileSize, IndexSize = databaseStatusResult.IndexSize, IndexCount = databaseStatusResult.IndexCount, ExtentCount = databaseStatusResult.ExtentCount, ObjectCount = databaseStatusResult.ObjectCount, StorageSize = databaseStatusResult.StorageSize, }; databaseInfo.DatabaseStatus = databaseStatus; } } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", string.Format("获取数据库 '{0}' 状态出错", databaseName), ex.ToString()); } var prefixPart = databaseName.Substring(0, databaseName.LastIndexOf("__")); databaseInfo.DatabasePrefix = prefixPart; var date = DateTime.MinValue; if (DateTime.TryParse(string.Format("{0}/{1}/{2}", datepart.Substring(0, 4), datepart.Substring(4, 2), "01"), out date)) { databaseInfo.DatabaseDate = date; } else { LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", string.Format("数据库名 '{0}' 日期部分解析错误", databaseName)); return; } var description = descriptions.Where(d => d.DatabasePrefix == prefixPart).FirstOrDefault(); if (description == null) { LocalLoggingService.Warning("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("没有取到数据描述 '{0}'", prefixPart)); return; } databaseInfo.Collections = new List<CollectionInfo>(); var expireDays = description.ExpireDays; if (expireDays > 0) { if (databaseInfo.DatabaseDate.AddMonths(1).AddDays(-1).AddDays(expireDays) < DateTime.Now && datepart != DateTime.Now.ToString("yyyyMM")) { database.Drop(); LocalLoggingService.Info("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("清除历史数据-删除库:{0}", databaseName)); return; } } var collectionNames = database.GetCollectionNames().Where(name => !name.Contains("system.index") && !name.Contains("$") && !name.Contains("__")).ToList(); foreach (var collectionName in collectionNames) { var swcoll = Stopwatch.StartNew(); try { var collection = database.GetCollection(collectionName); //if (expireDays > 0) //{ // var statTimeColumn = description.MongodbColumnDescriptionList.FirstOrDefault(c => c.IsTimeColumn); // if (statTimeColumn != null) // { // var query = Query.LT(statTimeColumn.ColumnName, DateTime.Now.AddDays(-expireDays)); // collection.Remove(query); // if (collection.Count() == 0) // { // collection.Drop(); // LocalLoggingService.Info("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter 清除历史数据-无数据删除表", databaseName, collectionName); // continue; // } // } //} var collectionInfo = new CollectionInfo(); collectionInfo.CollectionName = collectionName; collectionInfo.ListFilterColumns = new List<ListFilterColumnInfo>(); collectionInfo.CascadeFilterColumns = new List<CascadeFilterColumnInfo>(); collectionInfo.TextboxFilterColumns = new List<TextboxFilterColumnInfo>(); var collectionStatus = new CollectionStatus { IndexStatusList = new List<IndexStatus>(), }; CollectionStatsResult collectionStatusResult = null; try { if (collection.Count() > 0) { collectionStatusResult = collection.GetStats(); collectionStatus.AverageObjectSize = collectionStatusResult.AverageObjectSize; collectionStatus.DataSize = collectionStatusResult.DataSize; collectionStatus.StorageSize = collectionStatusResult.StorageSize; collectionStatus.LastExtentSize = collectionStatusResult.LastExtentSize; collectionStatus.Namespace = collectionStatusResult.Namespace; collectionStatus.ExtentCount = collectionStatusResult.ExtentCount; collectionStatus.Flags = collectionStatusResult.Flags; collectionStatus.IndexCount = collectionStatusResult.IndexCount; collectionStatus.ObjectCount = collectionStatusResult.ObjectCount; collectionStatus.PaddingFactor = collectionStatusResult.PaddingFactor; collectionStatus.TotalIndexSize = collectionStatusResult.TotalIndexSize; } } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter 获取表状态出错", string.Format("库名:{0} 表名:{1}", databaseName, collectionName), ex.ToString()); } var indexes = collection.GetIndexes(); collectionStatus.IndexStatusList = indexes.Select(i => new IndexStatus { Name = i.Name, Namespace = i.Namespace, Unique = i.IsUnique, }).ToList(); collectionStatus.IndexStatusList.ForEach(i => { if (collectionStatusResult != null && collectionStatusResult.IndexSizes.ContainsKey(i.Name)) i.Size = collectionStatusResult.IndexSizes[i.Name]; }); collectionInfo.CollectionStatus = collectionStatus; var indexColumnDescriptions = description.MongodbColumnDescriptionList.Where(c => c.MongodbIndexOption != MongodbIndexOption.None).ToList(); foreach (var indexColumnDescription in indexColumnDescriptions) { try { switch (indexColumnDescription.MongodbIndexOption) { case MongodbIndexOption.Ascending: { collection.EnsureIndex(IndexKeys.Ascending(indexColumnDescription.ColumnName), IndexOptions.SetBackground(true)); break; } case MongodbIndexOption.Descending: { collection.EnsureIndex(IndexKeys.Descending(indexColumnDescription.ColumnName), IndexOptions.SetBackground(true)); break; } case MongodbIndexOption.AscendingAndUnique: { collection.EnsureIndex(IndexKeys.Ascending(indexColumnDescription.ColumnName), IndexOptions.SetBackground(true).SetUnique(true).SetDropDups(true)); break; } case MongodbIndexOption.DescendingAndUnique: { collection.EnsureIndex(IndexKeys.Descending(indexColumnDescription.ColumnName), IndexOptions.SetBackground(true).SetUnique(true).SetDropDups(true)); break; } } } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "创建索引出错", ex.Message); } } collectionInfo.CollectionStatus.LastEnsureIndexTime = DateTime.Now; //加载数据库中的元数据 var metaCollection = database.GetCollection("Metadata__" + collectionInfo.CollectionName); var meta = metaCollection.FindOneAs<CollectionMetadata>(); if (meta == null) { meta = new CollectionMetadata { CollectionName = collectionInfo.CollectionName, ListFilterColumns = new List<ListFilterColumnInfo>(), CascadeFilterColumns = new List<CascadeFilterColumnInfo>(), TextboxFilterColumns = new List<TextboxFilterColumnInfo>(), }; } var textboxColumnDescriptions = description.MongodbColumnDescriptionList.Where(c => c.MongodbFilterOption == MongodbFilterOption.TextBoxFilter).ToList(); foreach (var textboxColumnDescription in textboxColumnDescriptions) { if (!collectionInfo.CollectionStatus.IndexStatusList.Exists(index => index.Name.Contains(textboxColumnDescription.ColumnName))) continue; var textboxColumnInfo = new TextboxFilterColumnInfo(); textboxColumnInfo.ColumnName = textboxColumnDescription.ColumnName; collectionInfo.TextboxFilterColumns.Add(textboxColumnInfo); if (meta.TextboxFilterColumns.Count(c => c.ColumnName == textboxColumnInfo.ColumnName) == 0) meta.TextboxFilterColumns.Add(textboxColumnInfo); } var filterColumnDescriptions = description.MongodbColumnDescriptionList.Where (c => c.MongodbFilterOption == MongodbFilterOption.DropDownListFilter || c.MongodbFilterOption == MongodbFilterOption.CheckBoxListFilter).ToList(); foreach (var filterColumnDescription in filterColumnDescriptions) { try { if (!collectionInfo.CollectionStatus.IndexStatusList.Exists(index => index.Name.Contains(filterColumnDescription.ColumnName))) continue; var filterColumnInfo = new ListFilterColumnInfo(); filterColumnInfo.ColumnName = filterColumnDescription.ColumnName; filterColumnInfo.DistinctValues = new List<ItemPair>(); if (oldServerInfo != null && oldServerInfo.Databases != null) { var oldDatabase = oldServerInfo.Databases.FirstOrDefault(d => d != null && d.DatabaseName == databaseInfo.DatabaseName); if (oldDatabase != null && oldDatabase.Collections != null) { var oldCollection = oldDatabase.Collections.FirstOrDefault(d => d != null && d.CollectionName == collectionInfo.CollectionName); if (oldCollection != null && oldCollection.ListFilterColumns != null) { var oldColumn = oldCollection.ListFilterColumns.FirstOrDefault(d => d != null && d.ColumnName == filterColumnInfo.ColumnName); if (oldColumn != null) { filterColumnInfo.DistinctValues = oldColumn.DistinctValues; } } } } var column = meta.ListFilterColumns.SingleOrDefault(c => c.ColumnName == filterColumnDescription.ColumnName); if (column != null) { foreach (var value in filterColumnInfo.DistinctValues) { if (column.DistinctValues.Count(v => string.Equals(v.Value.ToString(), value.Value.ToString(), StringComparison.InvariantCultureIgnoreCase)) == 0) { LocalLoggingService.Debug("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "列", string.Format("添加新过滤索引项 {0} 到元数据 {1}.{2}.{3}", value.Value.ToString(), databaseName, collectionName, column.ColumnName)); column.DistinctValues.Add(value); } } filterColumnInfo.DistinctValues = column.DistinctValues; } else { meta.ListFilterColumns.Add(filterColumnInfo); } collectionInfo.ListFilterColumns.Add(filterColumnInfo); } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3} {4}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "列", "创建过滤数据出错", ex.Message); } } var cascadeFilterColumnDescriptions = description.MongodbColumnDescriptionList.Where(c => c.MongodbCascadeFilterOption != MongodbCascadeFilterOption.None).ToList(); foreach (var cascadeFilterColumnDescription in cascadeFilterColumnDescriptions) { try { if (!collectionInfo.CollectionStatus.IndexStatusList.Exists(index => index.Name.Contains(cascadeFilterColumnDescription.ColumnName))) continue; var filterColumnInfo = new CascadeFilterColumnInfo(); filterColumnInfo.ColumnName = cascadeFilterColumnDescription.ColumnName; filterColumnInfo.DistinctValues = new List<string>(); if (oldServerInfo != null && oldServerInfo.Databases != null) { var oldDatabase = oldServerInfo.Databases.FirstOrDefault(d => d != null && d.DatabaseName == databaseInfo.DatabaseName); if (oldDatabase != null && oldDatabase.Collections != null) { var oldCollection = oldDatabase.Collections.FirstOrDefault(d => d != null && d.CollectionName == collectionInfo.CollectionName); if (oldCollection != null && oldCollection.CascadeFilterColumns != null) { var oldColumn = oldCollection.CascadeFilterColumns.FirstOrDefault(d => d != null && d.ColumnName == filterColumnInfo.ColumnName); if (oldColumn != null) { filterColumnInfo.DistinctValues = oldColumn.DistinctValues; } } } } var column = meta.CascadeFilterColumns.SingleOrDefault(c => c.ColumnName == cascadeFilterColumnDescription.ColumnName); if (column != null) { foreach (var value in filterColumnInfo.DistinctValues) { if (column.DistinctValues.Count(v => string.Equals(v, value, StringComparison.InvariantCultureIgnoreCase)) == 0) { LocalLoggingService.Debug("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "列", string.Format("添加新级联过滤索引项 {0} 到元数据 {1}.{2}.{3}", value, databaseName, collectionName, column.ColumnName)); column.DistinctValues.Add(value); } } filterColumnInfo.DistinctValues = column.DistinctValues; } else { meta.CascadeFilterColumns.Add(filterColumnInfo); } collectionInfo.CascadeFilterColumns.Add(filterColumnInfo); } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3} {4}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "列", "创建级联过滤数据出错", ex.Message); } } try { metaCollection.Save(meta); } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3} {4}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "表", "保存表元数据出错", ex.Message); } databaseInfo.Collections.Add(collectionInfo); } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2} {3} {4}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "表", "维护其它出错", ex.Message); } } if (databaseInfo.Collections.Count == 0) { //database.Drop(); //AppInfoCenterService.LoggingService.Debug(MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", // string.Format("清除历史数据-删除库:{0}", databaseName)); } else { if (!serverInfo.Databases.Contains(databaseInfo)) { serverInfo.Databases.Add(databaseInfo); } } LocalLoggingService.Debug("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "数据库", string.Format("对数据库 '{0}' 完成一次维护,耗时 {1} 毫秒", databaseName, swdb.ElapsedMilliseconds)); }); LocalLoggingService.Info("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", "服务器", string.Format("对服务器 '{0}' 完成一次维护,耗时 {1} 毫秒", url.Name, sw.ElapsedMilliseconds)); locker.EnterWriteLock(); if (servers.ContainsKey(url)) servers[url] = serverInfo; else servers.Add(url, serverInfo); locker.ExitWriteLock(); fristLoaded = true; } catch (Exception ex) { LocalLoggingService.Error("{0} {1} {2}", MongodbServerConfiguration.ModuleName, "MongodbServerMaintainceCenter", ex.Message); } }
public iFolderWeb(CollectionInfo c) { this.DomainID = c.DomainID; this.Name = c.Name; this.ID = c.ID; this.CollectionID = c.CollectionID; this.Description = c.Description; this.IsSubscription = true; this.EnumeratedState = (int) SubscriptionStates.Ready; this.Owner = c.OwnerFullName; this.CurrentUserID = c.MemberUserID; Domain domain = Store.GetStore().GetDomain(c.DomainID); if(domain != null) { Simias.Storage.Member member = domain.GetMemberByID(c.OwnerID); if(member != null) this.Owner = member.FN; } this.OwnerID = c.OwnerID; this.CurrentUserRights = c.UserRights; this.State = "WaitSync"; if( c.encryptionAlgorithm != null) this.encryptionAlgorithm = c.encryptionAlgorithm; else this.encryptionAlgorithm = ""; this.MigratediFolder = c.MigratediFolder; this.iFolderSize = c.Size; }
private void importToolStripMenuItem_Click(object sender, EventArgs e) { // Prompt the user for the file to import string extension = "csv"; OpenFileDialog ofd = new OpenFileDialog(); ofd.DefaultExt = extension; ofd.CheckFileExists = true; ofd.AddExtension = true; ofd.AutoUpgradeEnabled = true; ofd.Multiselect = false; ofd.Title = "Select Default Collection..."; ofd.Filter = string.Concat("Media Collections (*." + extension + ")|*." + extension + "|All files (*.*)|*.*"); if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; if (!File.Exists(ofd.FileName)) { MessageBox.Show("Could not find file specified.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Parse the CSV, creating a collection from it int line = 1; try { CollectionInfo info = new CollectionInfo(); using (CsvReader csv = new CsvReader(new StreamReader(ofd.FileName), true)) { int fieldCount = csv.FieldCount; string[] headers = csv.GetFieldHeaders(); while (csv.ReadNextRecord()) { Book b = new Book(); b.Series = csv[0]; b.Title = csv[1]; b.SeriesNumber = uint.Parse(csv[2]); b.Author = csv[3]; b.Genre = new List<string>(csv[4].Replace(" ", string.Empty).Split(',')); // csv[5] is page count b.FirstPublicationDate = new DateTime(int.Parse(csv[6]), 1, 1); b.PublicationDate = new DateTime(int.Parse(csv[7]), 1, 1); // csv[8] is comments info.Item.Add(b); line++; } } info.Item.Comments = "Imported from " + ofd.SafeFileName + " on " + DateTime.Now.ToShortDateString() + "."; info.Item.Title = ofd.SafeFileName.Substring(0, ofd.SafeFileName.LastIndexOf(".")); collections.Add(info); newCollectionWindow(info.Item); } catch (Exception ex) { MessageBox.Show("Could not parse the file \"" + ofd.FileName + "\".\n" + "Error at line " + line + ": \n" + ex.Message , "Parse Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
///<summary> /// Returns an array list of Child Collections of the object ///</summary> public System.Collections.ArrayList GetChildrenCollections(SchemaExplorer.TableSchema table, SchemaExplorer.TableSchemaCollection tables) { //System.Diagnostics.Debugger.Break(); //CleanUp if(CurrentTable != table.Name) { _collections.Clear(); _renderedChildren.Clear(); CurrentTable = table.Name; } if (_collections.Count > 0) return _collections; //Provides Informatoin about the foreign keys TableKeySchemaCollection fkeys = table.ForeignKeys; //Provides information about the indexes contained in the table. IndexSchemaCollection indexes = table.Indexes; TableKeySchemaCollection primaryKeyCollection = table.PrimaryKeys; foreach(TableKeySchema keyschema in primaryKeyCollection) { // add the relationship only if the linked table is part of the selected tables (ie: omit tables without primary key) if (!tables.Contains(keyschema.ForeignKeyTable.Owner, keyschema.ForeignKeyTable.Name)) { continue; } //Add 1-1 relations if(IsRelationOneToOne(keyschema)) { CollectionInfo collectionInfo = new CollectionInfo(); collectionInfo.PkColName = table.PrimaryKey.MemberColumns[0].Name; collectionInfo.PkIdxName = keyschema.Name; collectionInfo.PrimaryTable = table.Name; collectionInfo.SecondaryTable = keyschema.ForeignKeyTable.Name; collectionInfo.SecondaryTablePkColName = keyschema.ForeignKeyTable.PrimaryKey.MemberColumns[0].Name; collectionInfo.CollectionRelationshipType = RelationshipType.OneToOne; collectionInfo.CleanName = keyschema.ForeignKeyTable.Name;//GetClassName(keyschema.ForeignKeyTable.Name); collectionInfo.CollectionName = GetCollectionClassName(collectionInfo.CleanName); collectionInfo.CallParams = GetFunctionRelationshipCallParameters(keyschema.ForeignKeyMemberColumns); collectionInfo.GetByKeysName = "GetBy" + GetKeysName(keyschema.ForeignKeyMemberColumns); collectionInfo.TableKey = keyschema; _collections.Add(collectionInfo); } //Add 1-N,N-1 relations else { CollectionInfo collectionInfo = new CollectionInfo(); collectionInfo.PkColName = table.PrimaryKey.MemberColumns[0].Name; collectionInfo.PkIdxName = keyschema.Name; collectionInfo.PrimaryTable = table.Name; collectionInfo.SecondaryTable = keyschema.ForeignKeyTable.Name; collectionInfo.SecondaryTablePkColName = keyschema.ForeignKeyTable.PrimaryKey.MemberColumns[0].Name; collectionInfo.CollectionRelationshipType = RelationshipType.OneToMany; collectionInfo.CleanName = keyschema.ForeignKeyTable.Name; //GetClassName(keyschema.ForeignKeyTable.Name); collectionInfo.CollectionName = GetCollectionClassName(collectionInfo.CleanName); collectionInfo.CallParams = GetFunctionRelationshipCallParameters(table.PrimaryKey.MemberColumns); //collectionInfo.CallParams = GetFunctionRelationshipCallParameters(keyschema.ForeignKeyMemberColumns); collectionInfo.GetByKeysName = "GetBy" + GetKeysName(keyschema.ForeignKeyMemberColumns); collectionInfo.TableKey = keyschema; //collectionInfo.GetByKeysName = "GetBy" + GetKeysName(keyschema.ForeignKeyTable.PrimaryKey.MemberColumns); _collections.Add(collectionInfo); } } //Add N-N relations // TODO -> only if option is activated foreach(TableKeySchema key in primaryKeyCollection) { // Check that the key is related to a junction table and that this key relate a PK in this junction table if ( tables.Contains(key.ForeignKeyTable.Owner, key.ForeignKeyTable.Name) && IsJunctionTable(key.ForeignKeyTable) && IsJunctionKey(key)) { TableSchema junctionTable = key.ForeignKeyTable; // Search for the other(s) key(s) of the junction table' primary key foreach(TableKeySchema junctionTableKey in junctionTable.ForeignKeys) { if ( tables.Contains(junctionTableKey.ForeignKeyTable.Owner, junctionTableKey.ForeignKeyTable.Name) && IsJunctionKey(junctionTableKey) && junctionTableKey.Name != key.Name ) { TableSchema secondaryTable = junctionTableKey.PrimaryKeyTable; CollectionInfo collectionInfo = new CollectionInfo(); collectionInfo.PkColName = table.PrimaryKey.MemberColumns[0].Name; collectionInfo.PkIdxName = junctionTableKey.Name; collectionInfo.PrimaryTable = table.Name; collectionInfo.SecondaryTable = junctionTableKey.PrimaryKeyTable.Name; collectionInfo.SecondaryTablePkColName = junctionTableKey.PrimaryKeyTable.PrimaryKey.MemberColumns[0].Name; collectionInfo.JunctionTable = junctionTable.Name; collectionInfo.CollectionName = string.Format("{0}_From_{1}", GetCollectionClassName( collectionInfo.SecondaryTable), GetCleanName(collectionInfo.JunctionTable)); //GetManyToManyName(GetCollectionClassName( collectionInfo.SecondaryTable), collectionInfo.JunctionTable); collectionInfo.CollectionRelationshipType = RelationshipType.ManyToMany; collectionInfo.CallParams = "entity." + GetPropertyName(collectionInfo.PkColName); ///Find FK junc table key, used for loading scenarios if(junctionTable.PrimaryKey.MemberColumns[0] == junctionTableKey.ForeignKeyMemberColumns[0]) { collectionInfo.FkColName = junctionTable.PrimaryKey.MemberColumns[1].Name; } else { collectionInfo.FkColName = junctionTable.PrimaryKey.MemberColumns[0].Name; } collectionInfo.CallParams = "entity." + GetPropertyName(collectionInfo.PkColName); //collectionInfo.GetByKeysName = collectionInfo.PkColName + "From" + GetClassName(junctionTable.Name); collectionInfo.GetByKeysName = FKColumnName(key) + "From" + GetCleanName(junctionTable.Name); collectionInfo.TableKey = key; //GetManyToManyName(junctionTable.PrimaryKey.MemberColumns, collectionInfo.JunctionTable); //collectionInfo.GetByKeysName = GetManyToManyName(table.PrimaryKey.MemberColumns, GetClassName(junctionTable.Name));; collectionInfo.CleanName = string.Format("{0}From{1}", GetCleanName(collectionInfo.SecondaryTable), GetCleanName(junctionTable.Name)); //GetManyToManyName(collectionInfo.SecondaryTable, junctionTable.Name); _collections.Add(collectionInfo); } } } }// end N-N relations return _collections; }