Here are the examples of the csharp api System.Xml.Serialization.XmlSerializer.Deserialize(System.IO.TextReader) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
348 Examples
19
Source : AlifeConfigurator.cs
with MIT License
from 1upD
with MIT License
from 1upD
public static List<BaseAgent> ReadConfiguration(string filepath)
{
List<BaseAgent> agents = null;
try
{
log.Info(string.Format("Loading artificial life configuration from file: {0}", filepath));
XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));
StreamReader reader = new StreamReader(filepath);
agents = (List<BaseAgent>)serializer.Deserialize(reader);
reader.Close();
}
catch (Exception e)
{
log.Error(string.Format("Error reading artificial life configuration in file: {0}", filepath), e);
}
return agents;
}
19
Source : NailsConfig.cs
with MIT License
from 1upD
with MIT License
from 1upD
public static NailsConfig ReadConfiguration(string filepath)
{
NailsConfig config = null;
try
{
log.Info(string.Format("Loading Nails configuration from file: {0}", filepath));
XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));
StreamReader reader = new StreamReader(filepath);
config = (NailsConfig)serializer.Deserialize(reader);
reader.Close();
}
catch (Exception e)
{
log.Error(string.Format("Error reading Nails configuration in file: {0}", filepath), e);
}
return config;
}
19
Source : VisualizationSettings.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
public static VisualizationSettings LoadFromFile(string fileName)
{
using (var myReader = new StreamReader(fileName, false))
{
var xsSubmit = new XmlSerializer(typeof(VisualizationSettings));
var settings = (VisualizationSettings)xsSubmit.Deserialize(myReader);
return settings;
}
}
19
Source : XMLSerializer.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
public T Deserialize<T>(string input) //where T : clreplaced
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(input))
{
return (T)ser.Deserialize(sr);
}
}
19
Source : DmnParser.cs
with MIT License
from adamecr
with MIT License
from adamecr
public static DmnModel Parse(string filePath, DmnVersionEnum dmnVersion = DmnVersionEnum.V1_1)
{
if (string.IsNullOrWhiteSpace(filePath)) throw Logger.Fatal<DmnParserException>($"{nameof(filePath)} is null or empty");
if (!File.Exists(filePath)) throw Logger.Fatal<DmnParserException>($"File {filePath} doesn't exist");
DmnModel def;
// ReSharper disable once replacedignNullToNotNullAttribute
using (var rdr = new StreamReader(filePath))
{
try
{
Logger.Info($"Parsing DMN file {filePath}...");
switch (dmnVersion)
{
case DmnVersionEnum.V1_1:
def = (DmnModel)DmnDefinitionsSerializer.Deserialize(rdr);
break;
case DmnVersionEnum.V1_3:
def = (DmnModel)DmnDefinitionsSerializer13.Deserialize(rdr);
break;
default:
throw new ArgumentOutOfRangeException(nameof(dmnVersion), dmnVersion, null);
}
Logger.Info($"Parsed DMN file {filePath}");
}
catch (Exception ex)
{
throw Logger.Fatal<DmnParserException>($"Can't parse file {filePath}: {ex.Message}", ex);
}
}
return def;
}
19
Source : DmnParser.cs
with MIT License
from adamecr
with MIT License
from adamecr
public static DmnModel ParseString(string dmnDefinition, DmnVersionEnum dmnVersion = DmnVersionEnum.V1_1)
{
dmnDefinition = dmnDefinition?.Trim();
if (string.IsNullOrWhiteSpace(dmnDefinition)) throw Logger.Fatal<DmnParserException>("Missing DMN Model definition");
DmnModel def;
// ReSharper disable once replacedignNullToNotNullAttribute
using (var rdr = new StringReader(dmnDefinition))
{
try
{
Logger.Info($"Parsing DMN definition from given string...");
if (Logger.IsTraceEnabled)
Logger.Trace(dmnDefinition);
switch (dmnVersion)
{
case DmnVersionEnum.V1_1:
def = (DmnModel)DmnDefinitionsSerializer.Deserialize(rdr);
break;
case DmnVersionEnum.V1_3:
def = (DmnModel)DmnDefinitionsSerializer13.Deserialize(rdr);
break;
default:
throw new ArgumentOutOfRangeException(nameof(dmnVersion), dmnVersion, null);
}
Logger.Info($"Parsed DMN definition from given string");
}
catch (Exception ex)
{
throw Logger.Fatal<DmnParserException>($"Can't parse definition from given string: {ex.Message}", ex);
}
}
return def;
}
19
Source : FileManager.cs
with GNU General Public License v3.0
from AdamMYoung
with GNU General Public License v3.0
from AdamMYoung
public static ICollection<GroupViewModel> LoadGroups()
{
if (!File.Exists(GroupsFile))
return new List<GroupViewModel>();
var reader = new XmlSerializer(typeof(List<GroupViewModel>));
using (var file = new StreamReader(GroupsFile))
{
return (ICollection<GroupViewModel>) reader.Deserialize(file);
}
}
19
Source : Serialization.cs
with MIT License
from Aircoookie
with MIT License
from Aircoookie
public static ObservableCollection<WLEDDevice> Deserialize(string toDeserialize)
{
System.Diagnostics.Debug.WriteLine(toDeserialize);
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ObservableCollection<WLEDDevice>));
using (StringReader textReader = new StringReader(toDeserialize))
{
return xmlSerializer.Deserialize(textReader) as ObservableCollection<WLEDDevice>;
}
}
catch
{
return null;
}
}
19
Source : Forwarder.cs
with Apache License 2.0
from airbus-cert
with Apache License 2.0
from airbus-cert
public static Forwarder Build(ProviderGuid provider)
{
switch(provider.Type)
{
case ProviderGuid.ProviderType.Manifest:
var xml = RegisteredTraceEventParser.GetManifestForRegisteredProvider(provider.Guid);
XmlSerializer serializer = new XmlSerializer(typeof(Manifest.Manifest));
using (TextReader reader = new StringReader(xml))
{
var manifest = (Manifest.Manifest)serializer.Deserialize(reader);
return new Forwarder(new ManifestParser(manifest));
}
case ProviderGuid.ProviderType.TL:
return new Forwarder(new TraceLoggingParser());
case ProviderGuid.ProviderType.WPP:
return new Forwarder(new NullParser());
}
throw new NotImplementedException();
}
19
Source : Cipher.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
public static T DeSerializeFromFile<T>(string filePath, bool JSON = true) where T : new()
{
if (JSON)
{
var data = File.ReadAllText(filePath);
return new JavaScriptSerializer().Deserialize<T>(data);
}
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T) serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
19
Source : JailDropoff.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
internal static List<JailDropoff> DeserializeDropoffs()
{
if (Directory.Exists("Plugins/LSPDFR/Arrest Manager/JailDropoffs"))
{
foreach (string file in Directory.EnumerateFiles("Plugins/LSPDFR/Arrest Manager/JailDropoffs", "*.xml", SearchOption.TopDirectoryOnly))
{
try
{
using (var reader = new StreamReader(file))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<JailDropoff>),
new XmlRootAttribute("JailDropoffs"));
AllJailDropoffs.AddRange((List<JailDropoff>)deserializer.Deserialize(reader));
}
}
catch (Exception e)
{
Game.LogTrivial(e.ToString());
Game.LogTrivial("Arrest Manager - Error parsing XML from " + file);
}
}
}
else
{
}
if (AllJailDropoffs.Count == 0)
{
Game.DisplayNotification("Arrest Manager couldn't find a valid XML file with Jail Dropoffs in Plugins/LSPDFR/Arrest Manager/JailDropoffs.");
Game.LogTrivial("Arrest Manager couldn't find a valid XML file with Jail Dropoffs in Plugins/LSPDFR/Arrest Manager/JailDropoffs.");
}
return AllJailDropoffs;
}
19
Source : Offence.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
internal static List<Offence> DeserializeOffences()
{
List<Offence> AllOffences = new List<Offence>();
if (Directory.Exists("Plugins/LSPDFR/LSPDFR+/Offences"))
{
foreach (string file in Directory.EnumerateFiles("Plugins/LSPDFR/LSPDFR+/Offences", "*.xml", SearchOption.TopDirectoryOnly))
{
try
{
using (var reader = new StreamReader(file))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Offence>),
new XmlRootAttribute("Offences"));
AllOffences.AddRange((List<Offence>)deserializer.Deserialize(reader));
}
}
catch (Exception e)
{
Game.LogTrivial(e.ToString());
Game.LogTrivial("LSPDFR+ - Error parsing XML from " + file);
}
}
}
else
{
}
if (AllOffences.Count == 0)
{
AllOffences.Add(new Offence());
Game.DisplayNotification("~r~~h~LSPDFR+ couldn't find a valid XML file with offences in Plugins/LSPDFR/LSPDFR+/Offences. Setting just the default offence.");
}
CategorizedTrafficOffences = AllOffences.GroupBy(x => x.offenceCategory).ToDictionary(x => x.Key, x => x.ToList());
return AllOffences;
}
19
Source : SerializeUtils.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
19
Source : IdentityGeneratorType.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
public static T Deserialize<T>(this string toDeserialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StringReader textReader = new StringReader(toDeserialize))
{
return (T)xmlSerializer.Deserialize(textReader);
}
}
19
Source : HistoryManager.cs
with MIT License
from alexleen
with MIT License
from alexleen
private History Read()
{
History history = null;
if (!string.IsNullOrEmpty(mSettingManager.Get(mSettingName)))
{
XmlSerializer serializer = new XmlSerializer(typeof(History));
using (TextReader reader = new StringReader(mSettingManager.Get(mSettingName)))
{
history = (History)serializer.Deserialize(reader);
}
}
return history;
}
19
Source : TransaqClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public T Deserialize<T>(string data)
{
T newData;
var formatter = new XmlSerializer(typeof(T));
using (StringReader fs = new StringReader(data))
{
newData = (T)formatter.Deserialize(fs);
}
return newData;
}
19
Source : TargetInformation.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
internal void LoadProcessRenameFile(string processRenameFile)
{
if (String.IsNullOrEmpty(processRenameFile))
{
Renamer = new ProcessRenamer();
}
else if (!File.Exists(processRenameFile))
{
Renamer = new ProcessRenamer();
if (!Program.IsChild)
{
Console.WriteLine($"Warning: Process rename file {processRenameFile} was not found!");
}
}
else
{
XmlSerializer ser = new XmlSerializer(typeof(ProcessRenamer));
Renamer = (ProcessRenamer)ser.Deserialize(new StreamReader(processRenameFile));
}
}
19
Source : XmlHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public static T ParseFormByXml<T>(string xml,string rootName="root")
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
StringReader reader = new StringReader(xml);
T res = (T)serializer.Deserialize(reader);
reader.Close();
reader.Dispose();
return res;
}
19
Source : TickerTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public IList<Ticker> LoadFromFile(
string file)
{
var data = default(IList<Ticker>);
if (!File.Exists(file))
{
return data;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(table.GetType());
data = xs.Deserialize(sr) as IList<Ticker>;
if (data != null)
{
var id = this.table.Any() ?
this.table.Max(x => x.ID) + 1 :
1;
foreach (var item in data)
{
item.Guid = Guid.NewGuid();
item.ID = id++;
}
}
}
}
return data;
}
19
Source : ExportContainer.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static ExportContainer LoadFromFile(
string file)
{
var data = default(ExportContainer);
if (!File.Exists(file))
{
return data;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(ExportContainer));
data = xs.Deserialize(sr) as ExportContainer;
}
}
if (data == null)
{
return data;
}
if (data.Tag != null)
{
data.Tag.ID = Guid.NewGuid();
}
var panelIDConverter = new Dictionary<Guid, Guid>();
foreach (var panel in data.Panels)
{
var newID = Guid.NewGuid();
panelIDConverter[panel.ID] = newID;
panel.ID = newID;
}
var triggerIDDictionary = new Dictionary<Guid, Guid>();
var seq = default(long);
seq =
SpellTable.Instance.Table.Any() ?
SpellTable.Instance.Table.Max(x => x.ID) + 1 :
1;
foreach (var spell in data.Spells)
{
spell.ID = seq++;
var newID = Guid.NewGuid();
triggerIDDictionary[spell.Guid] = newID;
spell.Guid = newID;
if (panelIDConverter.ContainsKey(spell.PanelID))
{
spell.PanelID = panelIDConverter[spell.PanelID];
}
}
seq =
TickerTable.Instance.Table.Any() ?
TickerTable.Instance.Table.Max(x => x.ID) + 1 :
1;
foreach (var ticker in data.Tickers)
{
ticker.ID = seq++;
var newID = Guid.NewGuid();
triggerIDDictionary[ticker.Guid] = newID;
ticker.Guid = newID;
}
// 前提条件のIDを置き換える
Task.WaitAll(
Task.Run(() =>
{
foreach (var spell in data.Spells)
{
for (int i = 0; i < spell.TimersMustRunningForStart.Length; i++)
{
var id = spell.TimersMustRunningForStart[i];
if (triggerIDDictionary.ContainsKey(id))
{
spell.TimersMustRunningForStart[i] = triggerIDDictionary[id];
}
}
for (int i = 0; i < spell.TimersMustStoppingForStart.Length; i++)
{
var id = spell.TimersMustStoppingForStart[i];
if (triggerIDDictionary.ContainsKey(id))
{
spell.TimersMustStoppingForStart[i] = triggerIDDictionary[id];
}
}
}
}),
Task.Run(() =>
{
foreach (var ticker in data.Tickers)
{
for (int i = 0; i < ticker.TimersMustRunningForStart.Length; i++)
{
var id = ticker.TimersMustRunningForStart[i];
if (triggerIDDictionary.ContainsKey(id))
{
ticker.TimersMustRunningForStart[i] = triggerIDDictionary[id];
}
}
for (int i = 0; i < ticker.TimersMustStoppingForStart.Length; i++)
{
var id = ticker.TimersMustStoppingForStart[i];
if (triggerIDDictionary.ContainsKey(id))
{
ticker.TimersMustStoppingForStart[i] = triggerIDDictionary[id];
}
}
}
}));
return data;
}
19
Source : SpellPanelTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void Load()
{
lock (this)
{
try
{
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(this.DefaultFile))
{
var fi = new FileInfo(this.DefaultFile);
if (fi.Length <= 0)
{
File.Delete(this.DefaultFile);
}
}
if (!File.Exists(this.DefaultFile))
{
return;
}
// 旧形式を置換する
var text = File.ReadAllText(
this.DefaultFile,
new UTF8Encoding(false));
text = text.Replace("DoreplacedentElement", "ArrayOfPanelSettings");
File.WriteAllText(
this.DefaultFile,
text,
new UTF8Encoding(false));
using (var sr = new StreamReader(this.DefaultFile, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(this.table.GetType());
var data = xs.Deserialize(sr) as IList<SpellPanel>;
this.table.Clear();
foreach (var x in data)
{
// 旧Generalパネルの名前を置換える
if (x.PanelName == "General")
{
x.PanelName = SpellPanel.GeneralPanel.PanelName;
}
// NaNを潰す
x.Top = double.IsNaN(x.Top) ? 0 : x.Top;
x.Left = double.IsNaN(x.Left) ? 0 : x.Left;
x.Margin = double.IsNaN(x.Margin) ? 0 : x.Margin;
// ソートオーダーを初期化する
if (x.SortOrder == SpellOrders.None)
{
if (x.FixedPositionSpell)
{
x.SortOrder = SpellOrders.Fixed;
}
else
{
if (!Settings.Default.AutoSortEnabled)
{
x.SortOrder = SpellOrders.SortMatchTime;
}
else
{
if (!Settings.Default.AutoSortReverse)
{
x.SortOrder = SpellOrders.SortRecastTimeASC;
}
else
{
x.SortOrder = SpellOrders.SortRecastTimeDESC;
}
}
}
}
this.table.Add(x);
}
}
}
}
finally
{
var generalPanel = this.table.FirstOrDefault(x => x.PanelName == SpellPanel.GeneralPanel.PanelName);
if (generalPanel != null)
{
SpellPanel.SetGeneralPanel(generalPanel);
}
else
{
this.table.Add(SpellPanel.GeneralPanel);
}
}
}
}
19
Source : TimelineSettings.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static TimelineSettings Load(
string file)
{
var data = default(TimelineSettings);
lock (Locker)
{
try
{
autoSave = false;
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (!File.Exists(file))
{
if (File.Exists(MasterFile))
{
File.Copy(MasterFile, file);
}
else
{
data = new TimelineSettings();
return data;
}
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(TimelineSettings));
data = xs.Deserialize(sr) as TimelineSettings;
}
}
}
finally
{
if (data != null &&
!data.Styles.Any())
{
var style = TimelineStyle.SuperDefaultStyle;
style.IsDefault = true;
style.IsDefaultNotice = true;
data.Styles.Add(style);
}
autoSave = true;
}
}
return data;
}
19
Source : Settings.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void Load()
{
lock (lockObject)
{
try
{
IsInitializing = true;
var file = FilePath;
var activeConfig = this;
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (File.Exists(file))
{
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
var xs = new XmlSerializer(typeof(Settings));
instance = (Settings)xs.Deserialize(sr);
activeConfig = instance;
}
}
if (activeConfig != null)
{
// ステータスアラートの対象を初期化する
activeConfig.StatusAlertSettings?.SetDefaultAlertTargets();
// 棒読みちゃんのサーバーアドレスを置き換える
if (activeConfig.BoyomiServer.StartsWith("127.0.0."))
{
activeConfig.BoyomiServer = "localhost";
}
activeConfig.SasaraSettings.LoadRemoteConfig();
activeConfig.SasaraSettings.IsInitialized = true;
activeConfig.CevioAISettings.LoadRemoteConfig();
activeConfig.CevioAISettings.IsInitialized = true;
}
}
finally
{
IsInitializing = false;
}
}
}
19
Source : SpellTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public IList<Spell> LoadFromFile(
string file)
{
var data = default(IList<Spell>);
if (!File.Exists(file))
{
return data;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(table.GetType());
data = xs.Deserialize(sr) as IList<Spell>;
// IDは振り直す
if (data != null)
{
var id = this.table.Any() ?
this.table.Max(x => x.ID) + 1 :
1;
foreach (var item in data)
{
item.ID = id++;
item.Guid = Guid.NewGuid();
}
}
}
}
return data;
}
19
Source : TickerTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void Load(
string file,
bool isClear)
{
try
{
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (!File.Exists(file))
{
return;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(table.GetType());
var data = xs.Deserialize(sr) as IList<Ticker>;
if (isClear)
{
this.table.Clear();
}
foreach (var item in data)
{
this.table.Add(item);
}
}
}
}
finally
{
if (!this.table.Any())
{
this.table.AddRange(Ticker.SampleTickers);
}
}
this.Reset();
}
19
Source : TimelineModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static TimelineModel Load(
string file)
{
const string IgnoreLoadKeyword = "#ignore";
if (!File.Exists(file))
{
return null;
}
// ファイルサイズ0?
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
return null;
}
// 読込無効キーワード #ignore がある?
var text = File.ReadAllText(file, new UTF8Encoding(false));
if (text.ContainsIgnoreCase(IgnoreLoadKeyword))
{
return null;
}
var tl = default(TimelineModel);
var sb = default(StringBuilder);
try
{
// Razorエンジンで読み込む
sb = CompileRazor(file);
if (File.Exists(RazorDumpFile))
{
File.Delete(RazorDumpFile);
}
if (sb.Length > 0)
{
using (var sr = new StringReader(sb.ToString()))
{
var xs = new XmlSerializer(typeof(TimelineModel));
var data = xs.Deserialize(sr) as TimelineModel;
if (data != null)
{
tl = data;
tl.SourceFile = file;
}
}
}
}
catch (Exception ex)
{
tl = new TimelineModel();
tl.SourceFile = file;
tl.Name = tl.SourceFileName;
tl.HasError = true;
tl.Controller.Status = TimelineStatus.Error;
var msg = new StringBuilder();
msg.AppendLine($"Timeline load error.");
msg.AppendLine($"{tl.SourceFileName}");
msg.AppendLine();
msg.AppendLine($"{ex.Message}");
if (ex.InnerException != null)
{
msg.AppendLine($"{ex.InnerException.Message}");
}
tl.ErrorText = msg.ToString();
if (sb != null)
{
File.WriteAllText(
RazorDumpFile,
sb.ToString(),
new UTF8Encoding(false));
tl.CompiledText = sb.ToString();
}
return tl;
}
if (tl != null)
{
// 既定値を適用する
tl.SetDefaultValues();
}
// Compile後のテキストを保存する
tl.CompiledText = tl != null ?
sb.ToString() :
string.Empty;
return tl;
}
19
Source : Settings.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void Load()
{
lock (this.locker)
{
this.Reset();
if (!File.Exists(this.FileName))
{
this.isLoaded = true;
this.Save();
return;
}
var fi = new FileInfo(this.FileName);
if (fi.Length <= 0)
{
this.isLoaded = true;
this.Save();
return;
}
using (var sr = new StreamReader(this.FileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(this.GetType());
var data = xs.Deserialize(sr) as Settings;
if (data != null)
{
instance = data;
instance.isLoaded = true;
}
}
}
}
}
19
Source : SpellTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void Load(
string file,
bool isClear)
{
try
{
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (!File.Exists(file))
{
return;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(table.GetType());
var data = xs.Deserialize(sr) as IList<Spell>;
if (isClear)
{
this.table.Clear();
}
foreach (var item in data)
{
// パネルIDを補完する
if (item.PanelID == Guid.Empty)
{
item.PanelID = SpellPanelTable.Instance.Table
.FirstOrDefault(x => x.PanelName == item.PanelName)?
.ID ?? Guid.Empty;
if (item.PanelID == Guid.Empty)
{
item.PanelID = SpellPanel.GeneralPanel.ID;
}
}
else
{
if (!SpellPanelTable.Instance.Table.Any(x =>
x.ID == item.PanelID))
{
item.PanelID = SpellPanelTable.Instance.Table
.FirstOrDefault(x => x.PanelName == item.PanelName)?
.ID ?? SpellPanel.GeneralPanel.ID;
}
}
this.table.Add(item);
}
}
}
}
finally
{
if (!this.table.Any())
{
this.table.AddRange(Spell.SampleSpells);
}
this.Reset();
}
}
19
Source : TagTable.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public void Load()
{
lock (this)
{
var file = this.DefaultFile;
try
{
this.isLoaded = true;
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (!File.Exists(file))
{
return;
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(this.GetType());
var data = xs.Deserialize(sr) as TagTable;
this.Tags.Clear();
this.ItemTags.Clear();
this.ItemTags.AddRange(data.ItemTags);
this.Tags.AddRange(data.Tags);
}
}
}
finally
{
// インポートタグを追加する
var importsTag = this.Tags.FirstOrDefault(x => x.Name == Tag.ImportsTag.Name);
if (importsTag == null)
{
this.Tags.Add(Tag.ImportsTag);
}
else
{
Tag.SetImportTag(importsTag);
}
}
}
}
19
Source : Config.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static Config Load()
{
lock (Locker)
{
try
{
isInitializing = true;
if (!File.Exists(FileName))
{
return null;
}
var fi = new FileInfo(FileName);
if (fi.Length <= 0)
{
return null;
}
using (var sr = new StreamReader(FileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(Config));
if (xs.Deserialize(sr) is Config data)
{
instance = data;
}
}
}
return instance;
}
finally
{
isInitializing = false;
}
}
}
19
Source : Config.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static Config Load(
string fileName)
{
if (!File.Exists(fileName))
{
return new Config();
}
var fi = new FileInfo(fileName);
if (fi.Length <= 0)
{
return new Config();
}
using (var sr = new StreamReader(fileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(Config));
var data = xs.Deserialize(sr) as Config;
if (data != null)
{
return data;
}
}
}
return new Config();
}
19
Source : ReleaseNotes.cs
with MIT License
from anoyetta
with MIT License
from anoyetta
public static ReleaseNotes Deserialize(
string fileNameOrXMLText)
{
var source = string.Empty;
if (File.Exists(fileNameOrXMLText))
{
source = File.ReadAllText(fileNameOrXMLText, new UTF8Encoding(false));
}
else
{
source = fileNameOrXMLText;
}
if (string.IsNullOrEmpty(source))
{
return null;
}
var obj = default(ReleaseNotes);
using (var reader = new StringReader(source))
{
var xs = new XmlSerializer(typeof(ReleaseNotes));
obj = xs.Deserialize(reader) as ReleaseNotes;
}
return obj;
}
19
Source : Notes.cs
with MIT License
from anoyetta
with MIT License
from anoyetta
public void Load(
string fileName)
{
lock (this)
{
this.isLoading = true;
try
{
if (!File.Exists(fileName))
{
return;
}
using (var sr = new StreamReader(fileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length <= 0)
{
return;
}
var data = NotesSerializer.Deserialize(sr) as IEnumerable<Note>;
if (data != null)
{
this.NoteList.AddRange(data, true);
}
}
if (!this.NoteList.Any(x => x.IsDefault))
{
this.NoteList.Add(Note.DefaultNoteStyle);
}
this.NoteList.CollectionChanged += (_, __) => this.EnqueueSave();
foreach (var note in this.NoteList)
{
note.SetAutoSave();
}
}
finally
{
this.isLoading = false;
}
}
}
19
Source : Config.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static Config Load()
{
lock (ConfigBlocker)
{
if (File.Exists(OldFileName) &&
!File.Exists(FileName))
{
File.Move(OldFileName, FileName);
}
if (!File.Exists(FileName))
{
return null;
}
var fi = new FileInfo(FileName);
if (fi.Length <= 0)
{
return null;
}
MigrateConfig(FileName);
using (var sr = new StreamReader(FileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(Config));
var data = xs.Deserialize(sr) as Config;
if (data != null)
{
instance = data;
}
}
}
foreach (var item in instance.globalLogFilters)
{
item.FormatTextDelegate = (t, _) => FormatLogMessageType(t);
}
instance.globalLogFilterDictionary = instance.globalLogFilters.ToDictionary(x => x.Key);
if (instance.RegexCacheSize != RegexCacheSizeDefault)
{
if (instance.RegexCacheSize < RegexCacheSizeDefault)
{
instance.RegexCacheSize = instance.RegexCacheSize <= 0 ?
RegexCacheSizeDefaultOverride :
RegexCacheSizeDefault;
}
instance.ApplyRegexCacheSize();
}
return instance;
}
}
19
Source : TestConfig.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static T LoadFromDoreplacedentFormat (string path, Type[] extraTypes = null)
{
T SerializableObject = null;
using(TextReader reader = CreateTextReader(path))
{
XmlSerializer serializer = CreateXmlSerializer(extraTypes);
SerializableObject = serializer.Deserialize(reader) as T;
}
return SerializableObject;
}
19
Source : XmlUtils.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static object Deserialize(Type objType, string text)
{
if (null == text)
{
return null;
}
try
{
XmlSerializer serializer = new XmlSerializer(objType);
// Set the error handlers.
serializer.UnknownNode += serializer_UnknownNode;
serializer.UnknownElement += serializer_UnknownElement;
serializer.UnknownAttribute += serializer_UnknownAttribute;
return serializer.Deserialize(new StringReader(text));
}
catch (Exception ex)
{
Tracer.ErrorFormat("Error deserializing object: {0}", ex.Message);
return null;
}
}
19
Source : DynamicObjectSerializer.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
private static T XMLDoreplacedentLoader (System.Type[] extraTypes, string path)
{
T serializableObject = null;
using (TextReader textReader = TextFileReader (path))
{
XmlSerializer xmlSerializer = XmlSerializerCreation (extraTypes);
serializableObject = xmlSerializer.Deserialize (textReader) as T;
}
return serializableObject;
}
19
Source : FormBackground.cs
with MIT License
from AutoItConsulting
with MIT License
from AutoItConsulting
private bool OptionsReadCommandLineAndOptionsFile()
{
string[] arguments = Environment.GetCommandLineArgs();
string optionsFilename = string.Empty;
if (arguments.Length >= 2)
{
string arg = arguments[1].ToUpper();
if (arg == "/?" || arg == "?")
{
var usage = @"AutoIt.OSD.Background [/Close] | [Options.xml]";
MessageBox.Show(usage, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
if (arg == "/CLOSE" || arg == "CLOSE")
{
// If we are not the first instance, send a quit message along the pipe
if (!IsApplicationFirstInstance())
{
//KillPreviousInstance();
var namedPipeXmlPayload = new NamedPipeXmlPayload
{
SignalQuit = true
};
NamedPipeClientSendOptions(namedPipeXmlPayload);
}
return false;
}
// Get the options filename
optionsFilename = arguments[1];
}
// If no filename specified, use options.xml in current folder
if (arguments.Length == 1)
{
optionsFilename = _appPath + @"\Options.xml";
}
try
{
var deSerializer = new XmlSerializer(typeof(Options));
TextReader reader = new StreamReader(optionsFilename);
_options = (Options)deSerializer.Deserialize(reader);
_options.SanityCheck();
}
catch (Exception e)
{
string message = Resources.UnableToParseXml;
if (e.InnerException != null)
{
message += "\n\n" + e.InnerException.Message;
}
MessageBox.Show(message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// Additional parsing of some string values in useful fields
if (!OptionsXmlOptionsObjectToFields(_options))
{
return false;
}
// If are not the first instance then send a message to the running app with the new options and then quit
if (!IsApplicationFirstInstance())
{
var namedPipeXmlPayload = new NamedPipeXmlPayload
{
SignalQuit = false,
OsdBackgroundDir = _osdBackgroundDir,
OsdBackgroundWorkingDir = Directory.GetCurrentDirectory(),
Options = _options
};
NamedPipeClientSendOptions(namedPipeXmlPayload);
return false;
}
return true;
}
19
Source : XmlSerializer.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TEnreplacedy Deserialize<TEnreplacedy>(string content)
{
var serializer = new Xml.XmlSerializer(typeof(TEnreplacedy));
var reader = new StringReader(content);
#pragma warning disable CA5369 // Use XmlReader For Deserialize
var testRun = (TEnreplacedy)serializer.Deserialize(reader);
#pragma warning restore CA5369 // Use XmlReader For Deserialize
reader.Close();
return testRun;
}
19
Source : NativeTestsRunnerPluginService.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
private TEnreplacedy Deserialize<TEnreplacedy>(string content)
{
var serializer = new XmlSerializer(typeof(TEnreplacedy));
var reader = new StringReader(content);
var testRun = (TEnreplacedy)serializer.Deserialize(reader);
reader.Close();
return testRun;
}
19
Source : XmlSerializer.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public TEnreplacedy Deserialize<TEnreplacedy>(string content)
{
var serializer = new Xml.XmlSerializer(typeof(TEnreplacedy));
var reader = new StringReader(content);
var testRun = (TEnreplacedy)serializer.Deserialize(reader);
reader.Close();
return testRun;
}
19
Source : ConfigurationDiskOperations.cs
with MIT License
from avestura
with MIT License
from avestura
public static void LoadSettingsFromFile()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
var stream = new StreamReader(fileStream, Encoding.UTF8);
App.Configuration = (Configuration)serializer.Deserialize(stream);
}
}
catch(Exception ex)
{
var a = ex.Message;
App.Configuration = new Configuration();
App.Configuration.SaveSettingsToFile();
}
}
19
Source : ConfigurationDiskOperations.cs
with MIT License
from avestura
with MIT License
from avestura
public static void LoadSettingsFromFile()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
using (FileStream fileStream = new FileStream(FullPath, FileMode.Open))
{
var stream = new StreamReader(fileStream, Encoding.UTF8);
App.CurrentApp.Configuration = (Configuration)serializer.Deserialize(stream);
}
}
catch
{
App.CurrentApp.Configuration = new Configuration();
App.CurrentApp.Configuration.SaveSettingsToFile();
}
}
19
Source : Extensions.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public static T XmlDeserialize<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
19
Source : ConfigModel.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public static ConfigModelCollection LoadAllConfigs(string configurationsFolder, bool verbose = false)
{
var formatConfigsFile = Path.GetFullPath(Path.Combine(configurationsFolder, "Configs.xml"));
if (verbose)
Console.WriteLine("...loading formats configuration manifest {0}", formatConfigsFile);
try
{
var serializer = new XmlSerializer(typeof(ConfigModelCollection));
using (var fs = new FileStream(formatConfigsFile, FileMode.Open))
{
using (var reader = new StreamReader(fs))
{
return serializer.Deserialize(reader) as ConfigModelCollection;
}
}
}
catch (Exception e)
{
throw new InvalidDataException("Unable to retrieve content for formats manifest file " + formatConfigsFile, e);
}
}
19
Source : Program.cs
with MIT License
from AyrA
with MIT License
from AyrA
private static MakeMKV GetKey()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest WReq = WebRequest.CreateHttp("https://cable.ayra.ch/makemkv/api.php?xml");
WebResponse WRes;
//If you modify the tool, please add some personal twist to the user agent string
WReq.UserAgent = string.Format("AyrA/MakeMKVUpdater-{0} ({1}/{2};{3}) +https://github.com/AyrA/MakeMKV",
Settings.GetVersion(),
Environment.OSVersion.Platform,
Environment.OSVersion.Version,
Environment.OSVersion.VersionString);
try
{
WRes = WReq.GetResponse();
}
catch(Exception ex)
{
System.Diagnostics.Debug.Print(ex.Message);
return default(MakeMKV);
}
using (WRes)
{
using (var S = WRes.GetResponseStream())
{
using (var SR = new StreamReader(S))
{
var Ser = new XmlSerializer(typeof(MakeMKV));
try
{
return (MakeMKV)Ser.Deserialize(SR);
}
catch
{
return default(MakeMKV);
}
}
}
}
}
19
Source : Tools.cs
with MIT License
from AyrA
with MIT License
from AyrA
internal static T FromXml<T>(this string s)
{
XmlSerializer S = new XmlSerializer(typeof(T));
using (var SR = new StringReader(s))
{
return (T)S.Deserialize(SR);
}
}
19
Source : frmExport.cs
with MIT License
from AyrA
with MIT License
from AyrA
private void btnImport_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsText())
{
var Ser = new XmlSerializer(typeof(SaveFileEntry[]));
using (var SR = new StringReader(Clipboard.GetText()))
{
SaveFileEntry[] Entries;
try
{
Entries = (SaveFileEntry[])Ser.Deserialize(SR);
}
catch (Exception ex)
{
Log.Write(new Exception($"{GetType().Name}: Failed to parse clipboard for import", ex));
Tools.E("The text in your clipboard is not valid save file data", "No content");
return;
}
Log.Write("{0}: Importing {1} entries", GetType().Name, Entries.Length);
int ReplaceCount = -1;
//Replace all items with the same name
if (cbReplaceAll.Checked)
{
var Names = Entries.Select(m => m.ObjectData.Name).Distinct().ToArray();
var TotalStart = F.Entries.Count;
F.Entries.RemoveAll(m => Names.Contains(m.ObjectData.Name));
ReplaceCount = TotalStart - F.Entries.Count;
Log.Write("{0}: Removed {1} existing entries", GetType().Name, ReplaceCount);
}
//Automatically fix internal names by adding incrementing numbers until they're unique.
if (cbFixNames.Checked)
{
var Names = F.Entries.Select(m => m.ObjectData.InternalName).ToArray();
foreach (var E in Entries)
{
if (Names.Contains(E.ObjectData.InternalName))
{
string BaseName = E.ObjectData.InternalName;
if (BaseName.Contains("_"))
{
BaseName = BaseName.Substring(0, BaseName.LastIndexOf('_')) + "_";
}
string NewName = null;
int NameCounter = 0;
do
{
NewName = string.Format("{0}_{1}", BaseName, NameCounter++);
} while (Names.Contains(NewName));
Log.Write("{0}: Fixed name Old={0} New={1}", GetType().Name, E.ObjectData.InternalName, NewName);
E.ObjectData.InternalName = NewName;
}
else
{
Log.Write("{0}: No need to fix {1}", GetType().Name, E.ObjectData.InternalName);
}
}
}
F.Entries.AddRange(Entries);
FeatureReport.Used(FeatureReport.Feature.XmlImport);
Log.Write("{0}: Import complete", GetType().Name);
if (ReplaceCount >= 0)
{
MessageBox.Show(
$"Import complete. Deleted {ReplaceCount} existing entries", "Import complete",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(
$"Import complete", "Import complete",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
HasChange = true;
}
}
else
{
Log.Write("{0}: Tried to import empty clipboard", GetType().Name);
MessageBox.Show(
"Your clipboard is empty", "No content",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
19
Source : Settings.cs
with MIT License
from AyrA
with MIT License
from AyrA
public static Settings Load(string Content)
{
Log.Write("Settings: Loading settings");
var S = new XmlSerializer(typeof(Settings));
using (var SR = new StringReader(Content))
{
return (Settings)S.Deserialize(SR);
}
}
19
Source : UserApplicationStore.cs
with MIT License
from barry-jones
with MIT License
from barry-jones
private static object DeSerialize(string xmlToDeSerialize, Type objectType)
{
object deSerializedObject;
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(objectType);
System.IO.StringReader reader = new System.IO.StringReader(xmlToDeSerialize);
deSerializedObject = serializer.Deserialize(reader);
reader.Close();
return deSerializedObject;
}
See More Examples