/// ------------------------------------------------------------------------------------ private void SetGridSettings(SettingsPropertyValue propVal, XmlNode propNode) { var gridSettings = propVal.PropertyValue as GridSettings; if (gridSettings == null) { return; } propNode.RemoveAll(); var attrib = m_settingsXml.CreateAttribute("type"); attrib.Value = typeof(GridSettings).FullName; propNode.Attributes.Append(attrib); propNode.InnerXml = (XmlSerializationHelper.SerializeToString(gridSettings, true) ?? string.Empty); }
private void HandleResponse(Package package) { if (package.Sender == 10) { if (package.Event == 10) { Todo newTodo = XmlSerializationHelper.Desirialize <Todo>(package.Data); lock (todoLock) TodoList.Add(newTodo); } else if (package.Event == 9) { List <Todo> newTodos = XmlSerializationHelper.Desirialize <List <Todo> >(package.Data); lock (todoLock) foreach (Todo newTodo in newTodos) { TodoList.Add(newTodo); } } else if (package.Event == 2) { //fillMode = false; //sw.Stop();//int packagesCount = 1000;//MessageBox.Show(string.Format("{0} Packages in {1} Milliseconds ~ {2} packages per millisecond and {3} packages per second.", packagesCount, sw.ElapsedMilliseconds, packagesCount / sw.ElapsedMilliseconds, (packagesCount / sw.ElapsedMilliseconds) * 1000)); } } else if (package.Sender == 12) { if (package.Event == 10) { Project newProject = XmlSerializationHelper.Desirialize <Project>(package.Data); lock (todoLock) ProjectList.Add(newProject); } else if (package.Event == 9) { List <Project> newTodos = XmlSerializationHelper.Desirialize <List <Project> >(package.Data); lock (projectLock) foreach (Project newTodo in newTodos) { ProjectList.Add(newTodo); } } else if (package.Event == 2) { //sw.Stop();//int packagesCount = 1000;//MessageBox.Show(string.Format("{0} Packages in {1} Milliseconds ~ {2} packages per millisecond and {3} packages per second.", packagesCount, sw.ElapsedMilliseconds, packagesCount / sw.ElapsedMilliseconds, (packagesCount / sw.ElapsedMilliseconds) * 1000)); } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates a session object by deserializing the specified file. The file can be just /// the name of the file, without the path, or the full path specification. If that /// fails, null is returned or, when there's an exception, it is thrown. /// </summary> /// ------------------------------------------------------------------------------------ public static Session Load(SpongeProject prj, string pathName, out string errorMsg) { errorMsg = null; var fileName = Path.GetFileName(pathName); var folder = fileName; if (folder.EndsWith("." + Sponge.SessionFileExtension)) { folder = fileName.Remove(folder.Length - (Sponge.SessionFileExtension.Length + 1)); } else { fileName += ("." + Sponge.SessionFileExtension); } folder = Path.Combine(prj.SessionsFolder, folder); var path = Path.Combine(folder, fileName); if (!File.Exists(path)) { errorMsg = string.Format("The session file at \"{0}\" is missing.", path); return(null); } Exception e; var session = XmlSerializationHelper.DeserializeFromFile <Session>(path, out e); if (e != null) { errorMsg = ExceptionHelper.GetAllExceptionMessages(e); return(null); } if (session == null) //jh: I've noticed that DeserializeFromFile likes to return null, with no error. { errorMsg = "Cause unknown"; return(null); } session.Project = prj; session.Id = Path.GetFileNameWithoutExtension(fileName); return(session); }
public void Save() { StreamWriter projectsXMLFile = new StreamWriter(projectXMLFilePath); projectsXMLFile.WriteLine(XmlSerializationHelper.Serialize(projectBindingSource.List)); projectsXMLFile.Close(); StreamWriter todosXMLFile = new StreamWriter(todoXMLFilePath); todosXMLFile.WriteLine(XmlSerializationHelper.Serialize(todoBindingSource.List)); todosXMLFile.Close(); StreamWriter sprintsXMLFile = new StreamWriter(sprintXMLFilePath); sprintsXMLFile.WriteLine(XmlSerializationHelper.Serialize(sprintBindingSource.List)); sprintsXMLFile.Close(); taskPlanningPanel1.SaveCalendars(); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Called after data has been determined to be dirty, verified and OK is clicked or /// the user has confirmed saving the changes. /// </summary> /// <returns>False if closing the form should be canceled. Otherwise, true.</returns> /// ------------------------------------------------------------------------------------ protected override bool SaveChanges() { RenumberArticulators(); m_symbols.AddRange(m_nonEditableSymbols); m_symbols = m_symbols.OrderBy(x => x.Decimal).ToList(); var xml = XmlSerializationHelper.SerializeToString(m_symbols, true); var newSymbols = XElement.Parse(xml); newSymbols.Name = "symbols"; var element = XElement.Load(m_xmlFilePath); element.Element("symbols").ReplaceWith(newSymbols); element.Save(m_xmlFilePath); return(true); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates a SessionFile object for the specified file name. The first attempt to /// create a SessionFile object is via deserializing the specified file's standoff /// markup file. If that fails, it's assumed there is no standoff markup, therefore, /// a new SessionFile is instantiated. /// </summary> /// ------------------------------------------------------------------------------------ public static SessionFile Create(string fileName) { var standOffPath = GetStandoffFile(fileName); Exception e; var sessionFile = XmlSerializationHelper.DeserializeFromFile <SessionFile>(standOffPath, out e); if (e != null) { var msg = ExceptionHelper.GetAllExceptionMessages(e); Utils.MsgBox(msg); } if (sessionFile == null) { return(new SessionFile(fileName)); } sessionFile.FullFilePath = fileName; // Initialize each field's display text from the template's field definitions. var template = sessionFile.Template; if (template != null) { //review: (jh) seemed to leave things empty if they didn't already have data: foreach (var sfd in sessionFile.Fields) foreach (var def in template.Fields) { //var def = template.GetFieldDefinition(sfd.Name); var field = sessionFile.Fields.FirstOrDefault(x => x.Name == def.FieldName); if (field == null) { sessionFile.Fields.Add(new SessionFileField(def.FieldName, def.DisplayName)); } else { field.DisplayText = def.DisplayName; } } } return(sessionFile); }
/// ------------------------------------------------------------------------------------ public static void Save() { if (s_cache == null) { return; } if (string.IsNullOrEmpty(s_tmpFilename)) { s_tmpFilename = Path.GetTempFileName(); } var tmpList = s_cache.Select(e => new TempRecordCacheEntry(e.Key, e.Value)).ToList(); XmlSerializationHelper.SerializeToFile(s_tmpFilename, tmpList); s_cache.Clear(); tmpList.Clear(); s_cache = null; }
/// ------------------------------------------------------------------------------------ internal static void Load() { if (s_dbAccessInfo == null) { // Find the file that contains information about connecting to an FW database. s_accessInfoFile = FileLocationUtilities.GetFileDistributedWithApplication(App.ConfigFolderName, "FwDBAccessInfo.xml"); s_dbAccessInfo = XmlSerializationHelper.DeserializeFromFile <FwDBAccessInfo>(s_accessInfoFile); } if (s_dbAccessInfo == null && ShowMsgOnFileLoadFailure) { ErrorReport.NotifyUserOfProblem(LocalizationManager.GetString( "Miscellaneous.Messages.DataSourceReading.LoadingDBAccessInfoErorMsg", "The file that contains information to access FieldWork databases " + "older than version 7.x '{0}' is either missing or corrupt. Until " + "this problem is corrected, FieldWorks data sources cannot be " + "accessed or added as data sources."), s_accessInfoFile); } }
/// ------------------------------------------------------------------------------------ private void WriteRoot() { ProcessHelper.WriteStartElementWithAttrib(_writer, "inventory", "version", kVersion); WriteRootAttributes(); ProcessHelper.WriteMetadata(_writer, _project, true); XmlSerializationHelper.SerializeDataAndWriteAsNode(_writer, _project.TranscriptionChanges); XmlSerializationHelper.SerializeDataAndWriteAsNode(_writer, _project.AmbiguousSequences); if (_project.IgnoredSymbolsInCVCharts.Count > 0) { ProcessHelper.WriteStartElementWithAttrib(_writer, "symbols", "class", "ignoredInChart"); foreach (var symbol in _project.IgnoredSymbolsInCVCharts) { ProcessHelper.WriteStartElementWithAttribAndEmptyValue(_writer, "symbol", "literal", symbol); } _writer.WriteEndElement(); } else { if (!File.Exists(_project.CssFileName.Replace(".css", ".PhoneticInventory.xml"))) { ProcessHelper.WriteStartElementWithAttrib(_writer, "symbols", "class", "ignoredInChart"); ProcessHelper.WriteStartElementWithAttribAndEmptyValue(_writer, "symbol", "literal", "̩"); _writer.WriteEndElement(); _project.IgnoredSymbolsInCVCharts = new List <string> { "̩" }; _project.Save(); ProjectInventoryBuilder.Process(_project); } } _writer.WriteStartElement("segments"); WritePhones(); _writer.WriteEndElement(); // Close inventory _writer.WriteEndElement(); }
public void StrongNameSignInfoTest() { var signingInformation = GetTestInfo(); XElement serializationResult = XmlSerializationHelper.SigningInfoToXml(signingInformation); var strongNameSignInfos = serializationResult.Descendants("StrongNameSignInfo").ToList(); strongNameSignInfos.Count().Should().Be(2); var strongNameSignInfo1 = strongNameSignInfos.Where(x => x.Attribute("Include").Value.Equals("StrongName1")).Single(); strongNameSignInfo1.Attribute("PublicKeyToken").Value.Should().Be(PublicKeyToken1); strongNameSignInfo1.Attribute("CertificateName").Value.Should().Be(Certificate1Name); var strongNameSignInfo2 = strongNameSignInfos.Where(x => x.Attribute("Include").Value.Equals("StrongName2")).Single(); strongNameSignInfo2.Attribute("PublicKeyToken").Value.Should().Be(PublicKeyToken2); strongNameSignInfo2.Attribute("CertificateName").Value.Should().Be(Certificate2Name); }
/// <summary> /// Loads the points of interest. /// </summary> public void LoadPointsOfInterest() { OpenFileDialog OpenDialog = new OpenFileDialog(); Tc.PointsComboBox.Items.Clear(); string PATH = (string.Format(Application.StartupPath + "\\Documents\\Points of intrest")); OpenDialog.InitialDirectory = PATH; OpenDialog.FilterIndex = 0; if (OpenDialog.ShowDialog() == DialogResult.OK) { Navi.Reset(); Tasks.NavTask.Options.Points.Clear(); string PointsFilename = OpenDialog.FileName; Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Nav file loaded = {0}", PointsFilename)); try { Tasks.NavTask.Options.Points = XmlSerializationHelper.Deserialize <List <PointsOfInterest> >(PointsFilename) ?? new List <PointsOfInterest>(); OpenDialog.Dispose(); foreach (var item in Tasks.NavTask.Options.Points) { if (item.ID == Api.Player.ZoneId) { Tc.PointsComboBox.Items.Add(item.Name); } } Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Added {0} Points of interest", Tasks.NavTask.Options.Points.Count.ToString())); if (Tc.PointsComboBox.Items.Count > 0) { Tc.PointsComboBox.SelectedIndex = 0; } } catch (Exception ex) { Logger.AddDebugText(Tc.rtbDebug, string.Format(@"LoadWaypoints error {0}", ex.ToString())); } } }
protected override void ProcessPOST(ConnectorBase Connector, Package package) { try { DataItemAdded projectAdded = XmlSerializationHelper.Desirialize <DataItemAdded>(package.Data); Project newProject = new Project() { pId = projectAdded.PK }; lock (dataListLock) { dataList.Add(newProject.pId, newProject); } } catch (Exception ex) { RaiseLogEvent(LogType.Error, "ProjectNetList.ProcessPOST()" + ex.Message); } //base.ProcessPOST(t14Lab.MessageTree.Connector, package); }
/// <summary> /// 获取用户基本资料 /// </summary> /// <param name="UID">要查询的用户编号</param> /// <returns></returns> public UserInfoModel GetUserDetail(string UID) { UserInfoModel user = new UserInfoModel(); user.Error_Code = "10001"; if (string.IsNullOrEmpty(UID)) { return(user); } List <Parameter> Que = new List <Parameter>(); Que.Add(new Parameter("u_id", UID)); string UDetail = base.SyncRequest(TypeOption.MD_USER_DETAIL, Que, null); if (!string.IsNullOrEmpty(UDetail)) { return(XmlSerializationHelper.XmlToObject <UserInfoModel>(UDetail)); } return(null); }
/// <summary> /// Gets simple parameter value from it's markup. /// </summary> /// <returns></returns> public static object GetParameterValue(XElement parameterNode, ParameterProfile parameterProfile) { List <XElement> parameterElements = parameterNode.Elements(ParameterValueElementXName).ToList(); if (parameterElements.Any()) { return(parameterElements.Select(element => element.Attribute("value").Value).ToList()); } var valueAttr = parameterNode.Attribute("value"); if (valueAttr != null) { try { return(XmlSerializationHelper.Deserialize(valueAttr, parameterProfile.Type)); } catch (Exception ex) { Log.LogError(LogTitle, ex); return(parameterProfile.GetDefaultValue()); } } if (parameterNode.Elements().Any()) { Type paramType = parameterProfile.Type; if (paramType.IsSubclassOf(typeof(XContainer)) || (paramType.IsLazyGenericType() && paramType.GetGenericArguments()[0].IsSubclassOf(typeof(XContainer)))) { return(ValueTypeConverter.Convert(parameterNode.Elements().First(), parameterProfile.Type)); } throw new NotImplementedException("Not supported type of function parameter element node: '{0}'".FormatWith(paramType.FullName)); } return(parameterProfile.GetDefaultValue()); }
private BookScript GetSimpleBookScript() { const string bookScript = @" <book id=""MRK""> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""narrator-MRK"" userConfirmed=""false""> <verse num=""4"" /> <text>Mantsa tama, ka zlagaptá Yuhwana, mnda maga Batem ma mtak, kaʼa mantsa: </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""Made Up Guy"" userConfirmed=""false""> <text>«Mbəɗanafwa mbəɗa ta nzakwa ghuni, ka magaghunafta lu ta batem, ka plighunista Lazglafta ta dmakuha ghuni,» </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""Thomas/Andrew/Bartholomew"" userConfirmed=""true""> <text>«Gobbledy-gook» </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""6"" characterId=""Soup"" userConfirmed=""true""> <text>«Blah blah blah» </text> </block> </book>"; return(XmlSerializationHelper.DeserializeFromString <BookScript>(bookScript)); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Saves this instance of a SessionFile to it's standoff markup file. /// </summary> /// ------------------------------------------------------------------------------------ public void Save() { try { if (Directory.Exists(Path.GetDirectoryName(FullFilePath))) { XmlSerializationHelper.SerializeToFile(GetStandoffFile(FullFilePath), this); } else { //TODO: this happens because of renaming of the project, whic at the moment //can't happen while we have data which hasn't been saved already. Anyhow, //this all needs redesign, as the addition of renaming has led to many many //problems of this sort. } } catch (Exception e) { Palaso.Reporting.ErrorReport.NotifyUserOfProblem(e, "Could not save {0}", FullFilePath); } }
private VerseAnnotation CreateVerseAnnotationFromLine(string line) { string[] items = line.Split(new[] { "\t" }, StringSplitOptions.None); ScriptAnnotation annotation; string annotationXml = items[4]; //Enhance: find a way to get serialization to work properly on the base class directly if (annotationXml.StartsWith("<Sound")) { annotation = XmlSerializationHelper.DeserializeFromString <Sound>(annotationXml); } else { annotation = XmlSerializationHelper.DeserializeFromString <Pause>(annotationXml); } if (annotation == null) { throw new InvalidDataException(string.Format("The annotation {0} could not be deserialized", annotationXml)); } return(new VerseAnnotation(new BCVRef(BCVRef.BookToNumber(items[0]), int.Parse(items[1]), int.Parse(items[2])), annotation, int.Parse(items[3]))); }
/// <summary> /// 获取群组成员的用户信息 /// </summary> /// <param name="GroupID">群组编号</param> /// <returns></returns> public UserListModel GetUsersByGroup(string GroupID) { UserListModel users = new UserListModel(); users.Error_Code = "10001"; if (string.IsNullOrEmpty(GroupID)) { return(users); } List <Parameter> Que = new List <Parameter>(); Que.Add(new Parameter("g_id", GroupID)); string ResultList = base.SyncRequest(TypeOption.MD_GROUP_USER, Que, null); if (!string.IsNullOrEmpty(ResultList)) { return(XmlSerializationHelper.XmlToObject <UserListModel>(ResultList)); } return(null); }
/// <summary> /// 获取当前登录用户已经完成的并且托付的任务列表 /// </summary> /// <param name="pageindex">指定当前的页码</param> /// <param name="pagesize">指定要返回的记录条数(默认值20,最大值100)</param> /// <returns></returns> public TaskResultModel GetMyAssignFishished(string pageindex, string pagesize) { List <Parameter> Query = new List <Parameter>(); if (!string.IsNullOrEmpty(pageindex)) { Query.Add(new Parameter("pageindex", pageindex)); } if (!string.IsNullOrEmpty(pagesize)) { Query.Add(new Parameter("pagesize", pagesize)); } string Result = base.SyncRequest(TypeOption.MD_TASK_MYASSIGNFINISHED, Query, null); if (!string.IsNullOrEmpty(Result)) { return(XmlSerializationHelper.XmlToObject <TaskResultModel>(Result)); } return(null); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Loads the specified file. /// </summary> /// <param name="filename">The name of the OXESA file.</param> /// <param name="cache">The cache.</param> /// <param name="styleSheet">The style sheet.</param> /// <param name="e">Exception that was encountered or null</param> /// <returns>A loaded ScrAnnotationsList</returns> /// ------------------------------------------------------------------------------------ public static XmlScrAnnotationsList LoadFromFile(string filename, FdoCache cache, FwStyleSheet styleSheet, out Exception e) { XmlScrAnnotationsList list = XmlSerializationHelper.DeserializeFromFile <XmlScrAnnotationsList>(filename, true, out e); if (cache != null && styleSheet != null && list != null) { try { StyleProxyListManager.Initialize(styleSheet); list.WriteToCache(cache, styleSheet, Path.GetDirectoryName(filename)); } finally { StyleProxyListManager.Cleanup(); } } return(list ?? new XmlScrAnnotationsList()); }
/// <summary> /// 根据任务编号获取单条任务内容 /// </summary> /// <param name="TID">任务编号</param> /// <returns></returns> public TaskDetailResultModel GetTaskDetail(string TID) { TaskDetailResultModel T = new TaskDetailResultModel(); T.Error_Code = "10001"; if (string.IsNullOrEmpty(TID)) { return(T); } List <Parameter> Query = new List <Parameter>(); Query.Add(new Parameter("t_id", TID)); string Result = base.SyncRequest(TypeOption.MD_TASK_DETAIL, Query, null); if (!string.IsNullOrEmpty(Result)) { return(XmlSerializationHelper.XmlToObject <TaskDetailResultModel>(Result)); } return(null); }
/// <exclude /> public override XElement Serialize() { var element = new XElement(FunctionTreeConfigurationNames.ParamTag, new XAttribute(FunctionTreeConfigurationNames.NameAttribute, this.Name)); if (_constantValue is IEnumerable && !(_constantValue is string)) { foreach (object obj in (IEnumerable)_constantValue) { element.Add(new XElement(FunctionTreeConfigurationNames.ParamElementTag, new XAttribute(FunctionTreeConfigurationNames.ValueAttribute, XmlSerializationHelper.GetSerializableObject(obj)))); } return(element); } object xValue; if (_constantValue is XNode) { if (_constantValue is XDocument) { xValue = ((XDocument)_constantValue).Root; } else { xValue = _constantValue; } } else { xValue = new XAttribute(FunctionTreeConfigurationNames.ValueAttributeName, XmlSerializationHelper.GetSerializableObject(_constantValue) ?? string.Empty); } element.Add(xValue); return(element); }
/// <summary> /// Сериализует текущий объект пакета /// </summary> protected override void SerializePersonCurrent() { SerializeObject.VERS = "2.1"; SerializeObject.FILENAME = FileName; SerializeObject.SMOCOD = Batch.Receiver.Code; SerializeObject.NRECORDS = Count; SerializeObject.NERR = SerializeObject.REP.Count(x => x.CODE_ERP == CodeConfirm.CA); // Вычисляем код ПВП SerializeObject.PRZCOD = null; var splittedFileName = Batch.FileName.Split(new[] { '_' }); if (splittedFileName.Length == 3) { SerializeObject.PRZCOD = splittedFileName[1]; } try { // Сериализуем XmlSerializationHelper.SerializeToFile(SerializeObject, GetFileNameFull(), "rep_list"); base.SerializePersonCurrent(); // Пишем в базу код успешной выгрзуки var batch = ObjectFactory.GetInstance <IBatchManager>().GetById(BatchId); if (batch != null) { batch.CodeConfirm = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(CodeConfirm.AA); ObjectFactory.GetInstance <IBatchManager>().SaveOrUpdate(batch); ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush(); } } catch (Exception ex) { // Ошибка сериализации // Логгируем ошибку LogManager.GetCurrentClassLogger().Error(ex.Message, ex); throw; } }
private BookScript GetMultiBlockBookScript() { const string bookScript = @" <book id=""MRK""> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Start""> <verse num=""4"" /> <text>1 </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""4"" characterId=""secondCharacter"" userConfirmed=""true"" multiBlockQuote=""Continuation""> <text>2</text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Start""> <verse num=""5"" /> <text>3 </text> </block> <block style=""p"" chapter=""1"" initialStartVerse=""5"" characterId=""firstCharacter"" userConfirmed=""true"" multiBlockQuote=""Continuation""> <text>4</text> </block> </book>"; return(XmlSerializationHelper.DeserializeFromString <BookScript>(bookScript)); }
/// <summary> /// 5.1. Отправка объекта документа /// </summary> /// <param name="doc">Объект документа</param> /// <returns>Идентификатор документа</returns> public string SendDocument(Documents doc) { if (!LargeDocumentSize.HasValue) { LargeDocumentSize = GetLargeDocumentSize(); } // serialize the document and estimate data packet size var xml = XmlSerializationHelper.Serialize(doc, ApplicationName); var xmlBytes = Encoding.UTF8.GetByteCount(xml); var xmlBase64 = 4 * xmlBytes / 3; var overhead = 1024; // requestId + JSON serialization overhead var totalSize = xmlBase64 + SignatureSize + overhead; // prefer SendDocument for small documents if (totalSize < LargeDocumentSize) { return(SendDocument(xml)); } return(SendLargeDocument(xml)); }
/// <summary> /// 根据动态更新编号获取某条动态更新的回复列表信息 /// </summary> /// <param name="ID">动态更新编号</param> /// <returns></returns> public PostReplymentResultModel GetPostReplyByID(string ID) { PostReplymentResultModel postreply = new PostReplymentResultModel(); postreply.Error_Code = "10001"; if (string.IsNullOrEmpty(ID)) { return(postreply); } List <Parameter> Query = new List <Parameter>(); Query.Add(new Parameter("p_id", ID)); string Result = base.SyncRequest(TypeOption.MD_POST_REPLY, Query, null); if (!string.IsNullOrEmpty(Result)) { return(XmlSerializationHelper.XmlToObject <PostReplymentResultModel>(Result)); } return(null); }
/// <summary> /// Returns custom object for specified key /// </summary> public T GetCustomObject <T>(Guid pluginGuid) where T : class, ILayerMetadataBase { if (_rawObjects.ContainsKey(pluginGuid)) { XmlElement el = _rawObjects[pluginGuid]; var o = XmlSerializationHelper.DeserializeXmlElement <T>(el); if (o != null) { _rawObjects.Remove(pluginGuid); _customObjects[pluginGuid] = o; return(o); } } if (_customObjects.ContainsKey(pluginGuid)) { return(_customObjects[pluginGuid] as T); } return(default(T)); }
/// <summary> /// Loads information about a Digital Bible Library bundle from the specified projectFilePath. /// </summary> public static T Load <T>(string projectFilePath, out Exception exception) where T : DblMetadataBase <TL> { var metadata = XmlSerializationHelper.DeserializeFromFile <T>(projectFilePath, out exception); if (metadata == null) { if (exception == null) { exception = new ApplicationException(string.Format("Loading metadata ({0}) was unsuccessful.", projectFilePath)); } return(null); } try { metadata.InitializeMetadata(); } catch (Exception e) { exception = e; } return(metadata); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Loads the project's transcription changes. /// </summary> /// ------------------------------------------------------------------------------------ public static TranscriptionChanges Load(string projectPathPrefix) { string filename = GetFileForProject(projectPathPrefix); var transChanges = XmlSerializationHelper.DeserializeFromFile <TranscriptionChanges>(filename); // This should never need to be done, but just in case there are entries in // the list whose source transcription (i.e. Item) is null, remove them from // the list since those entries will cause problems further down the line. if (transChanges != null) { for (int i = transChanges.Count - 1; i >= 0; i--) { if (transChanges[i].WhatToReplace == null) { transChanges.RemoveAt(i); } } } return(transChanges ?? new TranscriptionChanges()); }
/// <summary> ///获取群组的动态更新 /// </summary> /// <param name="GroupID">群组编号</param> /// <param name="Keywords">关键词模糊搜索,当为空时则返回所有的动态更新</param> /// <param name="SinceId">若指定此参数,则只返回ID比since_id大的动态更新(即比since_id发表时间晚的动态更新)</param> /// <param name="MaxId">若指定此参数,则只返回ID比max_id小的动态更新(即比max_id发表时间早的动态更新)</param> /// <param name="PageSize">指定要返回的记录条数</param> /// <returns></returns> public PostResultModel GetDynamicInfoByGroup(string GroupID, string Keywords, string SinceId, string MaxId, string PageSize) { PostResultModel post = new PostResultModel(); post.Error_Code = "10001"; if (string.IsNullOrEmpty(GroupID)) { return(post); } List <Parameter> Query = new List <Parameter>(); Query.Add(new Parameter("g_id", GroupID)); if (!string.IsNullOrEmpty(Keywords)) { Query.Add(new Parameter("keywords", Keywords)); } if (!string.IsNullOrEmpty(SinceId)) { Query.Add(new Parameter("since_id", SinceId)); } if (!string.IsNullOrEmpty(MaxId)) { Query.Add(new Parameter("max_id", MaxId)); } if (!string.IsNullOrEmpty(PageSize)) { Query.Add(new Parameter("pagesize", PageSize)); } string Result = base.SyncRequest(TypeOption.MD_POST_GROUP, Query, null); if (!string.IsNullOrEmpty(Result)) { return(XmlSerializationHelper.XmlToObject <PostResultModel>(Result)); } return(null); }