public void DeleteObject(IPObject obj) { if (Root.Id != obj.Id) { obj.onwerCollection.RemoveObject(obj); _storage.DeleteObject(obj.Id); } }
public FFormat(int left, int top, IPObject formatObject, string template, IMHost host, IMValueGetter overloads) { InitializeComponent(); _left = left; _top = top; _formatObject = formatObject; _template = template; _host = host; _overloads = overloads; backgroundWorkerFormat.WorkerSupportsCancellation = true; }
// прогоняет весь путь, заменяя индекс -1 на индекс последнего элемента public void Normalize(IPObject withObject) { int cnt = this.Parts.Count; IPObject o = withObject; for (int i = 0; i < cnt; i++) { PNavigatorPathPart part = this.Parts[i]; IPCollection coll = o.GetCollection(part.LevelName); int index = part.PositionInLevel; if (index == -1) { index = coll.Count - 1; part.PositionInLevel = index; } o = coll.GetObject(index); } }
/// <summary> /// Tries to identify the string and return an object of that class. /// </summary> /// <param name="addr">String to parse.</param> /// <param name="result">IPObject to return.</param> /// <returns>True if the value parsed successfully.</returns> private static bool TryParse(string addr, out IPObject result) { if (!string.IsNullOrEmpty(addr)) { // Is it an IP address if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) { result = nw; return(true); } if (IPHost.TryParse(addr, out IPHost h)) { result = h; return(true); } } result = IPNetAddress.None; return(false); }
IEnumerator RequestWeather() { /*if (System.IO.File.Exists(Application.persistentDataPath + "/request.txt")) * { * System.IO.FileInfo info = new System.IO.FileInfo(Application.persistentDataPath + "/request.txt"); * int time = int.Parse(DateTimeToStamp( info.CreationTimeUtc ))- int.Parse(DateTimeToStamp(System.DateTime.Now)); * if (time < 3600 * 6) * { * WeatherObject Weather = JsonConvert.DeserializeObject<WeatherObject>(System.IO.File.ReadAllText(Application.persistentDataPath + "/request.txt")); * OnWeatherInit(Weather.data.Today, city.data.city); * * } * }*/ UnityWebRequest ipRequest = UnityWebRequest.Get("http://pv.sohu.com/cityjson?ie=utf-8"); yield return(ipRequest.SendWebRequest()); IPObject ip = JsonConvert.DeserializeObject <IPObject>(ipRequest.downloadHandler.text.Replace("var returnCitySN = ", "").Replace(";", "")); UnityWebRequest cityRequest = UnityWebRequest.Get("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip.cip); yield return(cityRequest.SendWebRequest()); CityObject city = JsonConvert.DeserializeObject <CityObject>(cityRequest.downloadHandler.text); UnityWebRequest weatherRequest = UnityWebRequest.Get("http://wthrcdn.etouch.cn/weather_mini?citykey=" + CityCode(city.data.city)); weatherRequest.SetRequestHeader("Content-Type", "application/octet-stream"); weatherRequest.SetRequestHeader("Content-Encoding", "gzip"); yield return(weatherRequest.SendWebRequest()); System.IO.File.WriteAllBytes(Application.persistentDataPath + "/request.zip", weatherRequest.downloadHandler.data); System.IO.FileStream inStream = new System.IO.FileStream(Application.persistentDataPath + "/request.zip", System.IO.FileMode.Open); System.IO.FileStream outStream = new System.IO.FileStream(Application.persistentDataPath + "/request.txt", System.IO.FileMode.Create); GZip.Decompress(inStream, outStream, true); WeatherObject Weather = JsonConvert.DeserializeObject <WeatherObject>(System.IO.File.ReadAllText(Application.persistentDataPath + "/request.txt")); OnWeatherInit(Weather.data.Today, city.data.city); }
// устанавливает атрибут объекта и сохраняет в БД protected void _setObjectAttr(IPObject obj, string attrName, string val) { obj.SetAttr(attrName, val); obj.StorageUpdateAttr(attrName); _modelStorage.Commit(); }
protected string genOptHtml(IPObject obj, out List<string> navLevels, out List<string> navCaptions) { string html = ""; // по-умолчанию пустые списки navLevels = new List<string>(); navCaptions = new List<string>(); if (obj != null) { string template; if (!obj.GetAttr(_conf.DetailTemplate, true, out template)) throw new Exception(string.Format(@"Шаблон просмотра деталей (атрибут {0}) не найден!", _conf.DetailTemplate)); using (FFormat form = new FFormat(this.Width / 2 - 150, this.Height / 2 - 81, obj, template, this, null)) { form.ShowDialog(); if (form.ExceptionMessage != "") throw new Exception(form.ExceptionMessage); html = form.GeneratedHtml; // заменяем navLevels = form.parsedNavLevels; navCaptions = form.parsedNavCaptions; } } if (html != "") html = _addScriptsToBody(html); return html; }
protected string formatMasterItem(IPObject obj) { string template; if (!obj.GetAttr(_conf.MasterItemTemplate, true, out template)) throw new Exception(string.Format("Шаблон наименования оптимизации (атрибут {0}) не найден!", _conf.MasterItemTemplate)); return PTemplates.FormatObject(obj, template, host: this, overloads: null, worker: null, navInfo: null); }
public PNavigator(IPObject owner, PNavigatorPath path) { _base = owner; _path = path!=null?path:new PNavigatorPath(null); _pointer = NavigateFromObject(_base, _path, true); }
public void RemoveObject(IPObject obj) { try { this._items.Remove((PObject)obj); } catch (Exception ex) { throw new Exception(String.Format("Не удалось получить экземпляр обьекта.Невозможно удалить объект из коллекции {0}. {1}", this.Name, ex.Message)); } }
protected static IPObject NavigateFromObject(IPObject baseObj, PNavigatorPath path, bool partialReturn) { IPObject o = baseObj; int cnt = path.Parts.Count; for (int ii = 0; ii < cnt; ii++) { PNavigatorPathPart level = path.Parts[ii]; IPCollection collection = o.GetCollection(level.LevelName); if (collection == null) throw new Exception(string.Format(@"Коллекция {0} не найдена на уровне {1}", level.LevelName, ii)); try { o = collection.GetObject(level.PositionInLevel); } catch { if (partialReturn) return o; // если объект с запрашиваемым индексом не найден - вернём тот, что был найден последний раз else throw; } } return o; }
public IPObject Navigate(PNavigatorPath path) { _path.copyPositions(from:path, partial:true); this.Pointer = this.GetObjectAtPathLevel(_path.Parts.Count-1, partialReturn: true); return this.Pointer; }
public IPObject Navigate(int depth, NAV_DIRECTION dir, bool overStep) { if (this._base == null) throw new Exception("Текущий объект не задан"); if (depth >= this._path.Parts.Count()) throw new Exception("Задана глубина больше чем уровней в навигаторе"); List<int> newPath = new List<int>(); for (int ii = 0; ii <= depth; ii++) { newPath.Add(this._path.Parts[ii].PositionInLevel); } if (_tryGetNewPath(ref newPath, dir, overStep)) { int cnt = this._path.Parts.Count; for (int ii = 0; ii < cnt; ii++) { _path.Parts[ii].PositionInLevel = (ii <= depth) ? newPath[ii] : 0; } this._path.Normalize(this._base); this.Pointer = this.GetObjectAtPathLevel(_path.Parts.Count-1, false); return Pointer; } else { if (this.OnNavigated != null) { OnNavigated(this, new NavigatedEventArgs(this.Pointer, this.Pointer)); } return null; } }
public PNavigatorPath GetPathTo(IPObject child) { IPObject o = child; if (child.Id == this._base.Id) throw new Exception(string.Format(@"Попытка получить путь от объекта до самого себя (id={0})", child.Id)); int baseId = this._base.Id; PNavigatorPath retPath = new PNavigatorPath(null); while (o.onwerCollection != null) { IPCollection coll = o.onwerCollection; retPath.Parts.Insert(0, new PNavigatorPathPart(coll.CollectionName, coll.IndexOf(o))); o = coll.ownerObject; if (o != null && o.Id == baseId) return retPath; } throw new Exception(string.Format(@"Объект id={0} не принадлежит объекту id={1}", child.Id, this._base.Id)); }
public static string FormatObject(IPObject obj, string template, IMHost host, IMValueGetter overloads, BackgroundWorker worker, PNavigationInfo navInfo) { List<PTemplateAttr> attrs; List<PTemplateCollection> fcollects; _parse(template, out attrs, out fcollects); template = template.Replace("%id%", obj.Id.ToString()); foreach (var attr in attrs) { string val = ""; string moduleName = attr.Module.Trim().ToLower(); string attrName = attr.Name; bool valFound = false; if (moduleName == "") { if (overloads != null) valFound = overloads.QueryValue(attrName, false, out val); if (!valFound) valFound = obj.GetAttr(attr.Name, true, out val); } else if (moduleName == "host") { if (host != null) valFound = host.QueryValue(attr.Name, false, out val); } else { valFound = _queryToModule(moduleName, attrName, out val); } if (!valFound) val = "<" + attr.ToString() + ">"; template = template.Replace(attr.OperatorText, val); } foreach (var fcollect in fcollects) { IPCollection coll = obj.GetCollection(fcollect.collectionName); if (coll != null) { string val = ""; int cnt = coll.Count; for (int i = 0; i < cnt; i++) { IPObject cobj = coll.GetObject(i); string tmp = ""; if (cobj.GetAttr(fcollect.templateName, true, out tmp)) { if (worker != null && worker.CancellationPending) return ""; bool navAdded = false; if (fcollect.navigatorLevelCaption != "") { if (navInfo != null) { navInfo.captions.Add(fcollect.navigatorLevelCaption); navInfo.levels.Add(fcollect.collectionName); navAdded = true; } } val += FormatObject(cobj, tmp, host, overloads, worker, navInfo); // теперь, если уровень навигации добавлялся - нужно сбросить переменную, чтоб в этом цикле не добавить соседние подходящие коллекции if (navAdded) navInfo = null; } else val += "<!" + fcollect.templateName + "!>"; val += (fcollect.endsWithNewLine ? "\n" : ""); } template = template.Replace(fcollect.OperatorText, val); } } // ToDo: может надо else что-нибудь вывести? Коллекция не найдена return template; }
public bool FindAttr(string attrName, out IPObject obj, out string val) { PObject o = this; obj = null; while (!o.GetAttr(attrName, false, out val)) { PCollection coll = o._ownerCollection; if (coll == null) return false; o = coll.OwnerObject; } obj = o; return true; /* ДАЛЕЕ НЕПРАВИЛЬНЫЙ КОД: * ПРАВИЛЬНЫЙ ВЫШЕ if (_attrs.TryGetValue(name.ToLower(), out val)) { obj = this; return true; } else if (this._ownerCollection != null && findInOwners) // рекурсивно ищем во всех владельцах { obj = _ownerCollection.OwnerObject; return this._ownerCollection.OwnerObject.GetAttr(name, true, out val); // НЕПРАВИЛЬНО - этот метод надёт значение, но не скажет где } else { obj = null; return false; }*/ }
public NavigatedEventArgs(IPObject prevObject, IPObject newObject) { this.prevObject = prevObject; this.newObject = newObject; }
public int IndexOf(IPObject obj) { int refId = obj.Id; int cnt = this._items.Count(); for(int i = 0; i < cnt; i++) { if (this._items[i].Id == refId) return i; } return -1; }