public void ForTypesWithoutInterfacesCustomSerializerSerializesTheSameAsDefaultSerializer( object instance, string defaultNamespace, Type[] extraTypes, string rootElementName, Encoding encoding, Formatting formatting, XmlSerializerNamespaces namespaces) { var defaultSerializer = (IXmlSerializer)Activator.CreateInstance( typeof(DefaultSerializer<>).MakeGenericType(instance.GetType()), defaultNamespace, extraTypes, rootElementName); var customSerializer = (IXmlSerializer)Activator.CreateInstance( typeof(CustomSerializer<>).MakeGenericType(instance.GetType()), defaultNamespace, extraTypes, rootElementName); var defaultXml = defaultSerializer.SerializeObject(instance, namespaces, encoding, formatting); var customXml = customSerializer.SerializeObject(instance, namespaces, encoding, formatting); Console.WriteLine("Default XML:"); Console.WriteLine(defaultXml); Console.WriteLine(); Console.WriteLine("Custom XML:"); Console.WriteLine(customXml); Assert.That(customXml, Is.EqualTo(defaultXml)); }
public string ToJson(Formatting format = Formatting.None) { JsonSerializerSettings setting = new JsonSerializerSettings(); setting.NullValueHandling = NullValueHandling.Ignore; string json = JsonConvert.SerializeObject(this, format, setting); return json; }
private static string GetTagName(Formatting formatting) { switch (formatting) { case Formatting.Bold: return "b"; case Formatting.Italic: return "i"; case Formatting.Underline: return "u"; case Formatting.Strikethrough: return "del"; case Formatting.Subscript: return "sub"; case Formatting.Superscript: return "sup"; default: throw new ArgumentOutOfRangeException("formatting"); } }
public DocumentWriter(Formatting formatting) : this(formatting, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }) { }
/// <summary> /// To provide custom serialization using the <see cref="Newtonsoft.Json.JsonSerializer" />. /// </summary> /// <param name="configuration">The bus configuration to apply the serializer to.</param> /// <param name="settings">To configure serialization settings.</param> /// <param name="formatting">To configure serialization formatting.</param> /// <param name="fallbackSerializer">To add a fallback serializer (if i.e you want to support both XML and Json)</param> /// <returns>Bus configuration.</returns> public static BusBuilderConfiguration.Config WithJsonSerializer( this BusBuilderConfiguration.Config configuration, JsonSerializerSettings settings, Formatting formatting = Formatting.None, ISerializer fallbackSerializer = null) { return configuration.WithSerializer(new JsonSerializer(settings, formatting, fallbackSerializer)); }
public JsonNetResult(object data, Formatting formatting = Formatting.None, JsonSerializerSettings settings = null) { Data = data; SerializerSettings = settings ?? new JsonSerializerSettings(); Formatting = formatting; }
public JsonNetResult(object data) { this.data = data; formatting = Formatting.None; serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; }
public string WriteObjectAsString(object obj, Formatting formatting = Formatting.None, TypeNameHandling nameHandling = TypeNameHandling.Auto) { return JsonConvert.SerializeObject(obj, formatting, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = nameHandling }); }
public void SaveToFile(object obj, string file, Formatting formatting = Formatting.Indented, TypeNameHandling nameHandling = TypeNameHandling.Auto) { var path = Util.Str.getFolder(file); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.WriteAllText(file, WriteObjectAsString(obj, formatting, nameHandling)); }
public static string Serialize(LanguageDefinition definition, Formatting formatting, bool serializeAsArrays = false) { //var json = JsonConvert.SerializeObject(definition, formatting, new InlineDefinitionJsonConverter(), new StringDefinitionJsonConverter(serializeAsArrays)); var settings = new JsonSerializerSettings();// {TypeNameHandling = TypeNameHandling.All}; settings.Converters.Add(new InlineDefinitionJsonConverter(serializeAsArrays)); settings.Converters.Add(new StringDefinitionJsonConverter(serializeAsArrays)); var json = JsonConvert.SerializeObject(definition, formatting, settings); return json; }
internal override string InternalToString(Formatting format, int depth) { if (Value != null && Value.Length > 0) return string.Concat("\"base64:", Convert.ToBase64String(this.Value), "\""); else return "\"base64:\""; }
public static string SinglePage(Formatting.FormattedHtml htmlContent) { var m = new Models.SingleFileModel() { Stylesheets = new[] { htmlContent.Stylesheet }, PreformattedHtml = htmlContent.Html, Javascript = new[] { htmlContent.Javascript } }; return RenderSingleFile(m); }
public JsonNetResult() { SerializerSettings = new JsonSerializerSettings(); //SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter()); SerializerSettings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; Formatting = Formatting.None; }
public JsonNetResult() { SerializerSettings = new JsonSerializerSettings(); //SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter()); SerializerSettings.Converters.Add(new IsoDateTimeConverter()); Formatting = Formatting.Indented; SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }
public DocumentWriter(Formatting formatting) : this( formatting, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), DateFormatHandling = DateFormatHandling.IsoDateFormat, DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFF'Z'", }) { }
public static string ObjectToJson(this IHtmlHelper helper, object input, Formatting jsonFormatting, params JsonConverter[] converters) { JsonSerializerSettings settings = new JsonSerializerSettings(); if (converters != null) { foreach (JsonConverter converter in converters) { settings.Converters.Add(converter); } } return JsonConvert.SerializeObject(input, jsonFormatting, settings); }
public CustomJsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet; JsonSerializer = new JsonSerializerSettings { Converters = new List<JsonConverter> { new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" } } }; Formatting = Formatting.None; }
public PlayerSaveData() { PlayerName = typeof( PlayerSaveData ).Name; PlayerColor = Color.green; EnemyColor = Color.red; Modules = new List<BaseUnitModule>(); UnitDefinitions = new List<UnitDefinition>(); Money = 1000; m_serializerSettings = new JsonSerializerSettings(); m_serializerFormatting = Formatting.None; m_onSaveDataChanged = null; }
public LayoutOptions() { this.ContainerHeaderHeight = 0.25; this.Padding = 0.125; this.ItemVerticalSpacing = 0.125; this.ItemHeight = 0.25; this.ContainerHorizontalDistance = 1.0; this.ItemWidth = 2.0; this.ContainerFormatting = new Formatting(); this.ContainerItemFormatting = new Formatting(); this.ContainerFormatting.TextBlockCells.VerticalAlign = "0"; }
/// <summary> /// Serializes the object in simple mode. /// </summary> /// <param name="value">The value.</param> /// <param name="formatting">The formatting.</param> /// <param name="jsonSettings">The json settings.</param> /// <returns></returns> public static string SerializeObjectInSimpleMode( object value, Formatting formatting, JsonSerializerSettings jsonSettings ) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault( jsonSettings ); jsonSerializer.Formatting = formatting; var stringWriter = new StringWriter( new StringBuilder( 256 ), CultureInfo.InvariantCulture ); using ( var jsonTextWriter = new Rock.Utility.RockJsonTextWriter( stringWriter, true ) ) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize( jsonTextWriter, value, null ); } return stringWriter.ToString(); }
private static JsonSerializerSettings CreateSettings(Formatting formatting, params JsonConverter[] converters) { var ret = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = formatting, MissingMemberHandling = MissingMemberHandling.Error }; foreach (var converter in converters) { ret.Converters.Add(converter); } return ret; }
public static string ToJSON(EntityCollection collection, Formatting format) { var space = format == Formatting.Indented ? " " : ""; StringBuilder sb = new StringBuilder(); sb.Append("{" + EntitySerializer.Sep(format, 1) + "\"entities\":" + space + "["); List<string> entities = new List<string>(); foreach (Entity entity in collection.Entities) { entities.Add(EntitySerializer.ToJSON(entity, format, 2)); } sb.Append(string.Join(",", entities)); sb.Append(EntitySerializer.Sep(format, 1) + "]" + EntitySerializer.Sep(format, 0) + "}"); return sb.ToString(); }
/// <summary>Serialize an entity</summary> /// <param name="entity">Entity to serialize</param> /// <param name="formatting">Formatting, determines if indentation and line feeds are used in the file</param> public static string Serialize(this Entity entity, Formatting formatting) { using (var stringWriter = new StringWriter()) { var serializer = new DataContractSerializer(typeof(Entity), null, int.MaxValue, false, false, null, new KnownTypesResolver()); var writer = new XmlTextWriter(stringWriter) { Formatting = formatting }; serializer.WriteObject(writer, entity); writer.Close(); return stringWriter.ToString(); } }
public static string ToJson(this VersionInformationEntity entity, Formatting formatting) { if (entity == null) { return string.Empty; } var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }; return JsonConvert.SerializeObject(entity, formatting, settings); }
public void TypeWithInterfaceSerializesSameAsTypeWithAbstract( object instanceWithInterface, object instanceWithAbstract, string defaultNamespace, Type[] extraTypes, string rootElementName, Encoding encoding, Formatting formatting, XmlSerializerNamespaces namespaces, IEnumerable<Tuple<string, string>> defaultXmlReplacements) { var defaultSerializer = new System.Xml.Serialization.XmlSerializer( instanceWithAbstract.GetType(), null, extraTypes, string.IsNullOrWhiteSpace(rootElementName) ? null : new XmlRootAttribute(rootElementName), defaultNamespace); var customSerializer = (IXmlSerializerInternal)Activator.CreateInstance( typeof(CustomSerializer<>).MakeGenericType(instanceWithInterface.GetType()), null, new TestXmlSerializerOptions { DefaultNamespace = defaultNamespace, ExtraTypes = extraTypes, RootElementName = rootElementName }); var defaultXml = defaultSerializer.SerializeObject(instanceWithAbstract, encoding, formatting, new TestSerializeOptions(namespaces)).StripXsiXsdDeclarations(); var customXml = customSerializer.SerializeObject(instanceWithInterface, encoding, formatting, new TestSerializeOptions(namespaces)).StripXsiXsdDeclarations(); Console.WriteLine("Default XML:"); Console.WriteLine(defaultXml); Console.WriteLine(); Console.WriteLine("Custom XML:"); Console.WriteLine(customXml); if (defaultXmlReplacements != null) { defaultXml = defaultXmlReplacements.Aggregate(defaultXml, (current, replacement) => current.Replace(replacement.Item1, replacement.Item2)); } Assert.That(customXml, Is.EqualTo(defaultXml)); }
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) { var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, TypeNameHandling = TypeNameHandling.Objects, ContractResolver = new EdContractResolver(), Binder = new EdSerializationBinder(), Converters = converters }; var serializer = JsonSerializer.Create(settings); using (var writer = new JTokenWriter()) { serializer.Serialize(writer, value); var root = (JObject)writer.Token; root = GraphRewriter.Deconstruct(root); return root.ToString(formatting); } }
public static string SerializeObject( this System.Xml.Serialization.XmlSerializer serializer, object instance, Encoding encoding, Formatting formatting, ISerializeOptions options) { var sb = new StringBuilder(); using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8)) { using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options)) { xmlWriter.Formatting = formatting; serializer.Serialize(xmlWriter, instance, options.Namespaces); } } return sb.ToString(); }
private static void InsertPicture(DocX doc, string filename, Formatting format) { using (MemoryStream memoryStream = new MemoryStream()) { System.Drawing.Image myImg = System.Drawing.Image.FromFile(filename); myImg.Save(memoryStream, myImg.RawFormat); // Save your picture in a memory stream. memoryStream.Seek(0, SeekOrigin.Begin); Novacode.Image img = doc.AddImage(memoryStream); // Create image. Paragraph p = doc.InsertParagraph("", false); Picture pic1 = img.CreatePicture(); // Create picture. p.InsertPicture(pic1, 0); // Insert picture into paragraph. doc.Save(); } }
public JsonNetFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); //Settings.Converters.Add(new StringEnumConverter()); _jSerializer = new JsonSerializer(); _jSerializer.DateParseHandling = DateParseHandling.None; _jSerializer.Converters.Add(new IsoDateTimeConverter()); //jSerializer.NullValueHandling = NullValueHandling.Ignore; if (File.Exists(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "iLoopAPISettings.txt"))) using (var sr = new StreamReader(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "iLoopAPISettings.txt"))) { try { var settings = JsonConvert.DeserializeObject<GlobalSettings>(sr.ReadToEnd()); Formatting = settings.Indent ? Formatting.Indented : Formatting.None; Settings.DefaultValueHandling = settings.RemoveDefaults ? DefaultValueHandling.Ignore : Settings.DefaultValueHandling; Settings.NullValueHandling = settings.RemoveNulls ? NullValueHandling.Ignore : Settings.NullValueHandling; Settings.DateFormatHandling = settings.UseIsoFormat ? DateFormatHandling.IsoDateFormat : Settings.DateFormatHandling; Settings.ContractResolver = settings.UseCamelCase ? new CamelCasePropertyNamesContractResolver() : Settings.ContractResolver; SystemConstants.TemporaryTokenExpiryTimeInMinutes = settings.TemporaryTokenExpiryTimeInMinutes; } catch (Exception) { // ignored } } //JsonConvert.DefaultSettings = () => new JsonSerializerSettings //{ // Formatting = Formatting.Indented, // DateFormatHandling = DateFormatHandling.IsoDateFormat, // DefaultValueHandling = DefaultValueHandling.Populate, // NullValueHandling = NullValueHandling.Include // //ContractResolver = new CamelCasePropertyNamesContractResolver() //}; }
public void ForTypesWithoutInterfacesCustomSerializerSerializesTheSameAsDefaultSerializer( object instance, string defaultNamespace, Type[] extraTypes, string rootElementName, Encoding encoding, Formatting formatting, XmlSerializerNamespaces namespaces) { var defaultSerializer = new System.Xml.Serialization.XmlSerializer( instance.GetType(), null, extraTypes, string.IsNullOrWhiteSpace(rootElementName) ? null : new XmlRootAttribute(rootElementName), defaultNamespace); var customSerializer = (IXmlSerializerInternal)Activator.CreateInstance( typeof(CustomSerializer<>).MakeGenericType(instance.GetType()), null, new TestXmlSerializerOptions { DefaultNamespace = defaultNamespace, ExtraTypes = extraTypes, RootElementName = rootElementName }); var defaultXml = defaultSerializer.SerializeObject(instance, encoding, formatting, new TestSerializeOptions(namespaces)).StripXsiXsdDeclarations(); var customXml = customSerializer.SerializeObject(instance, encoding, formatting, new TestSerializeOptions(namespaces)).StripXsiXsdDeclarations(); Console.WriteLine("Default XML:"); Console.WriteLine(defaultXml); Console.WriteLine(); Console.WriteLine("Custom XML:"); Console.WriteLine(customXml); Assert.That(customXml, Is.EqualTo(defaultXml)); }
public static string ToJson(ExpandoObject value, Formatting formatting = Formatting.Indented) { return(JsonConvert.SerializeObject(value, formatting, _filteredExpandoObjectConverter)); }
public static string ObjectToString(object obj, Formatting formatting = Formatting.Indented) => JToken.FromObject(obj, Serializer).ToString(formatting);
/// <summary> /// Converts an object of T to a JSON string with additional Formatting and JsonSerializerSettings /// </summary> /// <example> /// var json = root.ToJson(settings: new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Serialize }); /// </example> public static string ToJson <T>(this T instance, Formatting formatting = Formatting.None, JsonSerializerSettings settings = null) where T : class => JsonConvert.SerializeObject(instance, formatting, settings);
/// <summary> /// Serializes the specified object to a JSON string using the specified <paramref name="formatting"/>. /// </summary> /// <param name="obj"> /// The object to serialize. /// </param> /// <param name="formatting"> /// Indicates how the output is formatted. /// </param> /// <returns> /// A JSON string representation of the object. /// </returns> public static string SerializeObject(Object obj, Formatting formatting = Formatting.None) { return(JsonConvert.SerializeObject(obj, formatting, SerializerSettings)); }
public int Run(ResultMatchSetOptions options) { int returnCode = SUCCESS; options.OutputFolderPath = options.OutputFolderPath ?? Path.Combine(options.FolderPath, "Out"); ISarifLogMatcher matcher = ResultMatchingBaselinerFactory.GetDefaultResultMatchingBaseliner(); Formatting formatting = options.PrettyPrint ? Formatting.Indented : Formatting.None; // Remove previous results. if (_fileSystem.DirectoryExists(options.OutputFolderPath) && options.Force) { _fileSystem.DeleteDirectory(options.OutputFolderPath, true); } // Create output folder. _fileSystem.CreateDirectory(options.OutputFolderPath); string previousFileName = ""; string previousGroup = ""; SarifLog previousLog = null, currentLog = null; foreach (string filePath in Directory.GetFiles(options.FolderPath, "*.sarif")) { string fileName = Path.GetFileName(filePath); string currentGroup = GetGroupName(fileName); try { currentLog = ReadSarifFile <SarifLog>(_fileSystem, filePath); // Compare each log with the previous one in the same group. if (currentGroup.Equals(previousGroup) && currentLog?.Runs?[0]?.Results.Count != 0 && previousLog?.Runs?[0]?.Results.Count != 0) { Console.WriteLine(); Console.WriteLine($"{previousFileName} -> {fileName}:"); SarifLog mergedLog = matcher.Match(new[] { previousLog }, new[] { currentLog }).First(); // Write the same and different count and different IDs. WriteDifferences(mergedLog); // Write the log, if there were any changed results if (mergedLog.Runs[0].Results.Any(r => r.BaselineState != BaselineState.Unchanged)) { string outputFilePath = Path.Combine(options.OutputFolderPath, fileName); if (DriverUtilities.ReportWhetherOutputFileCanBeCreated(outputFilePath, options.Force, _fileSystem)) { WriteSarifFile(_fileSystem, mergedLog, outputFilePath, formatting); } else { returnCode = FAILURE; } } } } catch (Exception ex) when(!Debugger.IsAttached) { Console.WriteLine(ex.ToString()); returnCode = FAILURE; } previousFileName = fileName; previousGroup = currentGroup; previousLog = currentLog; } return(returnCode); }
public void Finish() { // Finish populating scene _container.materials = _materials.Values.ToList(); _container.geometries = _geometries.Values.ToList(); _container.obj.children = _objects.Values.ToList(); // Serialise scene //using( FileStream stream // = File.OpenWrite( filename ) ) //{ // DataContractJsonSerializer serialiser // = new DataContractJsonSerializer( // typeof( Va3cContainer ) ); // serialiser.WriteObject( stream, _container ); //} JsonSerializerSettings settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore; Formatting formatting = UserSettings.JsonIndented ? Formatting.Indented : Formatting.None; myjs = JsonConvert.SerializeObject( _container, formatting, settings); File.WriteAllText(_filename, myjs); #if USE_DYNAMIC_JSON // This saves the whole hassle of explicitly // defining a whole hierarchy of C# classes // to serialise to JSON - do it all on the // fly instead. // https://github.com/va3c/GHva3c/blob/master/GHva3c/GHva3c/va3c_geometry.cs dynamic jason = new ExpandoObject(); //populate object properties jason.geometry = new ExpandoObject(); jason.groups = new object[0]; jason.material = matName; jason.position = new object[3]; jason.position[0] = 0; jason.position[1] = 0; jason.position[2] = 0; jason.rotation = new object[3]; jason.rotation[0] = 0; jason.rotation[1] = 0; jason.rotation[2] = 0; jason.quaternion = new object[4]; jason.quaternion[0] = 0; jason.quaternion[1] = 0; jason.quaternion[2] = 0; jason.quaternion[3] = 0; jason.scale = new object[3]; jason.scale[0] = 1; jason.scale[1] = 1; jason.scale[2] = 1; jason.visible = true; jason.castShadow = true; jason.receiveShadow = false; jason.doubleSided = true; //populate geometry object jason.geometry.metadata = new ExpandoObject(); jason.geometry.metadata.version = 3.1; jason.geometry.metadata.generatedBy = "RvtVa3c Revit va3c exporter"; jason.geometry.metadata.vertices = mesh.Vertices.Count; jason.geometry.metadata.faces = mesh.Faces.Count; jason.geometry.metadata.normals = 0; jason.geometry.metadata.colors = 0; jason.geometry.metadata.uvs = 0; jason.geometry.metadata.materials = 0; jason.geometry.metadata.morphTargets = 0; jason.geometry.metadata.bones = 0; jason.geometry.scale = 1.000; jason.geometry.materials = new object[0]; jason.geometry.vertices = new object[mesh.Vertices.Count * 3]; jason.geometry.morphTargets = new object[0]; jason.geometry.normals = new object[0]; jason.geometry.colors = new object[0]; jason.geometry.uvs = new object[0]; jason.geometry.faces = new object[mesh.Faces.Count * 3]; jason.geometry.bones = new object[0]; jason.geometry.skinIndices = new object[0]; jason.geometry.skinWeights = new object[0]; jason.geometry.animation = new ExpandoObject(); //populate vertices int counter = 0; int i = 0; foreach (var v in mesh.Vertices) { jason.geometry.vertices[counter++] = mesh.Vertices[i].X; jason.geometry.vertices[counter++] = mesh.Vertices[i].Y; jason.geometry.vertices[counter++] = mesh.Vertices[i].Z; i++; } //populate faces counter = 0; i = 0; foreach (var f in mesh.Faces) { jason.geometry.faces[counter++] = mesh.Faces[i].A; jason.geometry.faces[counter++] = mesh.Faces[i].B; jason.geometry.faces[counter++] = mesh.Faces[i].C; i++; } return(JsonConvert.SerializeObject(jason)); #endif // USE_DYNAMIC_JSON }
public Artifact(List <Property> properties, World world) : base(properties, world) { Name = "Untitled"; Type = "Unknown"; WrittenContentIds = new List <int>(); foreach (Property property in properties) { switch (property.Name) { case "name": Name = Formatting.InitCaps(property.Value); break; case "item": if (property.SubProperties != null) { property.Known = true; foreach (Property subProperty in property.SubProperties) { switch (subProperty.Name) { case "name_string": Item = string.Intern(Formatting.InitCaps(subProperty.Value)); break; case "page_number": PageCount = Convert.ToInt32(subProperty.Value); break; case "page_written_content_id": case "writing_written_content_id": if (!WrittenContentIds.Contains(Convert.ToInt32(subProperty.Value))) { WrittenContentIds.Add(Convert.ToInt32(subProperty.Value)); } break; } } } else { Item = Formatting.InitCaps(property.Value); } break; case "item_type": Type = string.Intern(Formatting.InitCaps(property.Value)); break; case "item_subtype": SubType = string.Intern(property.Value); break; case "item_description": Description = Formatting.InitCaps(property.Value); break; case "mat": Material = string.Intern(property.Value); break; case "page_count": PageCount = Convert.ToInt32(property.Value); break; case "abs_tile_x": AbsTileX = Convert.ToInt32(property.Value); break; case "abs_tile_y": AbsTileY = Convert.ToInt32(property.Value); break; case "abs_tile_z": AbsTileZ = Convert.ToInt32(property.Value); break; case "writing": if (!WrittenContentIds.Contains(Convert.ToInt32(property.Value))) { WrittenContentIds.Add(Convert.ToInt32(property.Value)); } break; case "site_id": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "subregion_id": Region = world.GetRegion(Convert.ToInt32(property.Value)); break; case "holder_hfid": HolderId = Convert.ToInt32(property.Value); break; case "structure_local_id": Structure = Site?.Structures.FirstOrDefault(structure => structure.Id == Convert.ToInt32(property.Value)); break; } } if (AbsTileX > 0 && AbsTileY > 0) { Coordinates = new Location(AbsTileX / 816, AbsTileY / 816); } else if (Site != null) { Coordinates = Site.Coordinates; } }
public static string SerializeObject(object?value, Formatting formatting, JsonSerializerSettings?settings) { return(SerializeObject(value, null, formatting, settings)); }
/// <summary> /// Serializes the <see cref="XmlNode"/> to a JSON string using formatting. /// </summary> /// <param name="node">The node to serialize.</param> /// <param name="formatting">Indicates how the output should be formatted.</param> /// <returns>A JSON string of the <see cref="XmlNode"/>.</returns> public static string SerializeXmlNode(XmlNode?node, Formatting formatting) { XmlNodeConverter converter = new XmlNodeConverter(); return(SerializeObject(node, formatting, converter)); }
public DocumentWriter(Formatting formatting, JsonSerializerSettings settings) { _serializer = JsonSerializer.CreateDefault(settings); _serializer.Formatting = formatting; }
/// <summary> /// 将一个 <see cref="System.Object"/> 对象序列化转换为 JSON 格式字符串。 /// </summary> /// <param name="_this">要序列化的对象。</param> /// <param name="type">定义序列化对象的转换类型。</param> /// <param name="formatting">定义序列化结果的输出格式。</param> /// <param name="settings">定义序列化对象时采用的序列化设置。</param> /// <returns>序列化的 JSON 字符串。</returns> /// <remarks>该方法调用 Newtonsoft.Json.dll 组件的 JsonConvert.SerializeObject 方法来执行序列化操作。</remarks> public static string ToJson(this object _this, Type type, Formatting formatting, JsonSerializerSettings settings) { return(JsonSerializer.Serialize(_this, type, formatting, settings)); }
/// <summary> /// 将一个 <see cref="System.Object"/> 对象序列化转换为 JSON 格式字符串。 /// </summary> /// <param name="_this">要序列化的对象。</param> /// <param name="formatting">定义序列化结果的输出格式。</param> /// <param name="converters">定义序列化对象时的转换器集合。</param> /// <returns>序列化的 JSON 字符串。</returns> /// <remarks>该方法调用 Newtonsoft.Json.dll 组件的 JsonConvert.SerializeObject 方法来执行序列化操作。</remarks> public static string ToJson(this object _this, Formatting formatting, params JsonConverter[] converters) { return(JsonSerializer.Serialize(_this, formatting, converters)); }
public static bool WriteProtocol(IEnumerable <Protocol> people, string nameFile, DateTime from, DateTime to) { try { var doc = DocX.Create(nameFile); doc.PageLayout.Orientation = Novacode.Orientation.Landscape; doc.MarginTop = 20; doc.MarginLeft = 20; doc.MarginRight = 20; doc.MarginBottom = 20; var header = new Formatting(); header.FontFamily = new System.Drawing.FontFamily("Times New Roman"); header.Size = 16; header.Bold = true; var titleName = new Formatting(); titleName.FontFamily = new System.Drawing.FontFamily("Times New Roman"); titleName.Size = 11; var contenttext = new Formatting(); contenttext.FontFamily = new System.Drawing.FontFamily("Times New Roman"); contenttext.Size = 9D; doc.InsertParagraph("Протокол тестування ", false, header).Alignment = Alignment.center; doc.InsertParagraph(string.Format("Період проведення з {0} до {1}", from.ToString("dd-MM-yyyy"), to.ToString("dd-MM-yyyy")), false, titleName).Alignment = Alignment.left; Table table = doc.AddTable(people.Count() + 1, 10); table.Rows[0].Cells[0].Paragraphs.First().Append(" № "); table.Rows[0].Cells[1].Paragraphs.First().Append("Прізвище"); table.Rows[0].Cells[2].Paragraphs.First().Append("Таб. ном."); table.Rows[0].Cells[3].Paragraphs.First().Append("Білет"); table.Rows[0].Cells[4].Paragraphs.First().Append("Дата"); table.Rows[0].Cells[5].Paragraphs.First().Append("На комп'ютері"); table.Rows[0].Cells[6].Paragraphs.First().Append("Клас "); table.Rows[0].Cells[7].Paragraphs.First().Append("Відповіді"); table.Rows[0].Cells[8].Paragraphs.First().Append("Помилки"); table.Rows[0].Cells[9].Paragraphs.First().Append("Результат"); List <Protocol> people_ = people.ToList(); for (int z = 0; z < people_.Count(); z++) { table.Rows[z + 1].Cells[0].Paragraphs.First().Append((z + 1).ToString()); table.Rows[z + 1].Cells[1].Paragraphs.First().Append(people_[z].ticket.user.Lname); table.Rows[z + 1].Cells[2].Paragraphs.First().Append(people_[z].ticket.user.ID.ToString()); table.Rows[z + 1].Cells[3].Paragraphs.First().Append(people_[z].ticket.ID.ToString()); table.Rows[z + 1].Cells[4].Paragraphs.First().Append(people_[z].ticket.date.ToString("dd-MM-yyyy")); table.Rows[z + 1].Cells[5].Paragraphs.First().Append(people_[z].ticket.IsOffline.Equals("ні")?"так": "ні"); table.Rows[z + 1].Cells[6].Paragraphs.First().Append(people_[z].ticket.level); table.Rows[z + 1].Cells[7].Paragraphs.First().Append(people_[z].answers.ToString()); table.Rows[z + 1].Cells[8].Paragraphs.First().Append(people_[z].errors.ToString()); table.Rows[z + 1].Cells[9].Paragraphs.First().Append(people_[z].ticket.IsPassed); if (people_[z].ticket.IsPassed.Equals("ні")) { for (int i = 0; i < 10; i++) { table.Rows[z + 1].Cells[i].FillColor = System.Drawing.Color.OrangeRed; } } } doc.InsertTable(table); doc.InsertParagraph(""); doc.InsertParagraph(""); doc.InsertParagraph(@"Підпис членів комісії ________________________________________________________ ________________________________________________________ ________________________________________________________", false, contenttext).Alignment = Alignment.left; doc.Save(); return(true); } catch (Exception ex) { throw new Exception("WriteTicketToWord " + ex.Message); } }
public override string ToString() => $"Enum.Parse(typeof({Formatting.FriendlyName(typeof(TValue))}), <arg>)";
protected override void LoadKernelDefaultConfigurationDataObjects(TransactionTypeEnum transactionTypeEnum, IConfigurationProvider configProvider) { Logger.Log("Using Global Kernel 3 Values:"); Kernel3Configuration = XMLUtil <Kernel3Configuration> .Deserialize(configProvider.GetKernel3GlobalConfigurationDataXML()); #region 3.3.4.2 and 3.3.4.3 TERMINAL_TRANSACTION_QUALIFIERS_9F66_KRN ttq = new TERMINAL_TRANSACTION_QUALIFIERS_9F66_KRN(this); if (Kernel3Configuration.FDDAForOnlineSupported) { ttq.Value.OfflineDataAuthenticationForOnlineAuthorizationsSupported = true; } else { ttq.Value.OfflineDataAuthenticationForOnlineAuthorizationsSupported = false; } #endregion Logger.Log("Using Kernel 3 Defaults:"); KernelConfigurationDataForTransactionType kcdott = new KernelConfigurationDataForTransactionType() { TransactionTypeEnum = transactionTypeEnum, KernelConfigurationDataObjects = TLVListXML.XmlDeserialize(configProvider.GetKernel3ConfigurationDataXML(Formatting.ByteArrayToHexString(new byte[] { (byte)transactionTypeEnum }))) }; int depth = 0; Logger.Log("Transaction Type: " + transactionTypeEnum + " Using Kernel3 Defaults: \n" + kcdott.KernelConfigurationDataObjects.ToPrintString(ref depth)); KernelConfigurationData.Add(kcdott); }
public static string SerializeObject(object?value, Formatting formatting) { return(SerializeObject(value, formatting, (JsonSerializerSettings?)null)); }
public async Task <bool> Process(string[] args) { try { ArgumentSyntax.Parse(args, syntax => { syntax.HandleErrors = false; registerOptions = DefineRegisterCommand(syntax); authorizationOptions = DefineAuthorizationCommand(syntax); certificateOptions = DefineCertificateCommand(syntax); }); } catch (ArgumentSyntaxException ex) { consoleLogger.Error(ex.Message); } jsonSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }; jsonSettings.Converters.Add(new StringEnumConverter()); #if DEBUG formatting = Formatting.Indented; #endif try { switch (command) { case Command.Register: await this.ProcessCommand <RegisterCommand, RegisterOptions>(new RegisterCommand(registerOptions, this.consoleLogger)); break; case Command.Authorization: await this.ProcessCommand <AuthorizationCommand, AuthorizationOptions>(new AuthorizationCommand(authorizationOptions, this.consoleLogger)); break; case Command.Certificate: await this.ProcessCommand <CertificateCommand, CertificateOptions>(new CertificateCommand(certificateOptions, this.consoleLogger)); break; } return(true); } catch (AggregateException ex) { foreach (var err in ex.InnerExceptions) { consoleLogger.Error(err, err.Message); } } catch (Exception ex) { consoleLogger.Error(ex, ex.Message); } return(false); }
/// <summary> /// Serializes the <see cref="XNode"/> to a JSON string using formatting. /// </summary> /// <param name="node">The node to convert to JSON.</param> /// <param name="formatting">Indicates how the output should be formatted.</param> /// <returns>A JSON string of the <see cref="XNode"/>.</returns> public static string SerializeXNode(XObject?node, Formatting formatting) { return(SerializeXNode(node, formatting, false)); }
public SerializerSettings(DateFormatHandling dateFormat = DateFormatHandling.MicrosoftDateFormat, Formatting formatting = Formatting.None) { Formatting = formatting; DateFormat = dateFormat; }
public HistoricalFigure(List <Property> properties, World world) : base(properties, world) { Initialize(); foreach (Property property in properties) { switch (property.Name) { case "appeared": Appeared = Convert.ToInt32(property.Value); break; case "birth_year": BirthYear = Convert.ToInt32(property.Value); break; case "birth_seconds72": BirthSeconds72 = Convert.ToInt32(property.Value); break; case "death_year": DeathYear = Convert.ToInt32(property.Value); break; case "death_seconds72": DeathSeconds72 = Convert.ToInt32(property.Value); break; case "name": Name = Formatting.InitCaps(property.Value.Replace("'", "`")); break; case "race": Race = world.GetCreatureInfo(property.Value); break; case "caste": Caste = string.Intern(Formatting.InitCaps(property.Value.ToLower().Replace('_', ' '))); break; case "associated_type": AssociatedType = string.Intern(Formatting.InitCaps(property.Value.ToLower().Replace('_', ' '))); break; case "deity": Deity = true; property.Known = true; break; case "skeleton": Skeleton = true; property.Known = true; break; case "force": Force = true; property.Known = true; Race = world.GetCreatureInfo("Force"); break; case "zombie": Zombie = true; property.Known = true; break; case "ghost": Ghost = true; property.Known = true; break; case "hf_link": //Will be processed after all HFs have been loaded world.AddHFtoHfLink(this, property); property.Known = true; List <string> knownSubProperties = new List <string> { "hfid", "link_strength", "link_type" }; if (property.SubProperties != null) { foreach (string subPropertyName in knownSubProperties) { Property subProperty = property.SubProperties.FirstOrDefault(property1 => property1.Name == subPropertyName); if (subProperty != null) { subProperty.Known = true; } } } break; case "entity_link": case "entity_former_position_link": case "entity_position_link": world.AddHFtoEntityLink(this, property); property.Known = true; if (property.SubProperties != null) { foreach (string subPropertyName in KnownEntitySubProperties) { Property subProperty = property.SubProperties.FirstOrDefault(property1 => property1.Name == subPropertyName); if (subProperty != null) { subProperty.Known = true; } } } break; case "entity_reputation": world.AddReputation(this, property); property.Known = true; if (property.SubProperties != null) { foreach (string subPropertyName in Reputation.KnownReputationSubProperties) { Property subProperty = property.SubProperties.FirstOrDefault(property1 => property1.Name == subPropertyName); if (subProperty != null) { subProperty.Known = true; } } } break; case "entity_squad_link": case "entity_former_squad_link": property.Known = true; if (property.SubProperties != null) { foreach (string subPropertyName in KnownEntitySquadLinkProperties) { Property subProperty = property.SubProperties.FirstOrDefault(property1 => property1.Name == subPropertyName); if (subProperty != null) { subProperty.Known = true; } } } break; case "relationship_profile_hf": property.Known = true; if (property.SubProperties != null) { RelationshipProfiles.Add(new RelationshipProfileHf(property.SubProperties, RelationShipProfileType.Unknown)); } break; case "relationship_profile_hf_visual": property.Known = true; if (property.SubProperties != null) { RelationshipProfiles.Add(new RelationshipProfileHf(property.SubProperties, RelationShipProfileType.Visual)); } break; case "relationship_profile_hf_historical": property.Known = true; if (property.SubProperties != null) { RelationshipProfiles.Add(new RelationshipProfileHf(property.SubProperties, RelationShipProfileType.Historical)); } break; case "site_link": world.AddHFtoSiteLink(this, property); property.Known = true; if (property.SubProperties != null) { foreach (string subPropertyName in KnownSiteLinkSubProperties) { Property subProperty = property.SubProperties.FirstOrDefault(property1 => property1.Name == subPropertyName); if (subProperty != null) { subProperty.Known = true; } } } break; case "hf_skill": property.Known = true; if (property.SubProperties != null) { var skill = new Skill(property.SubProperties); Skills.Add(skill); } break; case "active_interaction": ActiveInteractions.Add(string.Intern(property.Value)); break; case "interaction_knowledge": InteractionKnowledge.Add(string.Intern(property.Value)); break; case "animated": Animated = true; property.Known = true; break; case "animated_string": if (AnimatedType != "") { throw new Exception("Animated Type already exists."); } AnimatedType = Formatting.InitCaps(property.Value); break; case "journey_pet": JourneyPets.Add(Formatting.FormatRace(property.Value)); break; case "goal": Goal = Formatting.InitCaps(property.Value); break; case "sphere": Spheres.Add(property.Value); break; case "current_identity_id": CurrentIdentityId = Convert.ToInt32(property.Value); break; case "used_identity_id": UsedIdentityIds.Add(Convert.ToInt32(property.Value)); break; case "ent_pop_id": EntityPopulationId = Convert.ToInt32(property.Value); break; case "holds_artifact": var artifact = world.GetArtifact(Convert.ToInt32(property.Value)); HoldingArtifacts.Add(artifact); artifact.Holder = this; break; case "adventurer": Adventurer = true; property.Known = true; break; case "breed_id": BreedId = property.Value; if (!string.IsNullOrWhiteSpace(BreedId)) { if (world.Breeds.ContainsKey(BreedId)) { world.Breeds[BreedId].Add(this); } else { world.Breeds.Add(BreedId, new List <HistoricalFigure> { this }); } } break; case "sex": property.Known = true; break; case "site_property": // is resolved in SiteProperty.Resolve() property.Known = true; if (property.SubProperties != null) { foreach (Property subProperty in property.SubProperties) { switch (subProperty.Name) { case "site_id": subProperty.Known = true; break; case "property_id": subProperty.Known = true; break; } } } break; case "vague_relationship": property.Known = true; if (property.SubProperties != null) { VagueRelationships.Add(new VagueRelationship(property.SubProperties)); } break; case "honor_entity": property.Known = true; if (property.SubProperties != null) { HonorEntity = new HonorEntity(property.SubProperties, world); } break; case "intrigue_actor": property.Known = true; if (property.SubProperties != null) { IntrigueActors.Add(new IntrigueActor(property.SubProperties)); } break; case "intrigue_plot": property.Known = true; if (property.SubProperties != null) { IntriguePlots.Add(new IntriguePlot(property.SubProperties)); } break; } } if (string.IsNullOrWhiteSpace(Name)) { Name = !string.IsNullOrWhiteSpace(AnimatedType) ? Formatting.InitCaps(AnimatedType) : "(Unnamed)"; } if (Adventurer) { world.AddPlayerRelatedDwarfObjects(this); } }
public void createDocument(string fileName, string txt, int scene) { // CREATING DOCX FILE, TO RECORD THE USER STORY string pathFileName = @"C:/Users/parad/Desktop/StoryTelling1/StoryTelling1/bin/Debug/" + fileName; string headlineText = "Defend Your Kingdom \n Your Interactive Storytelling"; string paraOne = "" + txt; // A formatting object for our normal paragraph text: var paraScene = new Formatting(); paraScene.FontFamily = new System.Drawing.FontFamily("Calibri"); paraScene.Size = 9D; paraScene.Bold = true; //Console.WriteLine("HERE ---- " + pathFileName + " || " + paraOne); //string curFile = @"c:\temp\test.txt"; //Your path if (!File.Exists(pathFileName)) { Console.WriteLine("Docx -- " + pathFileName); // A formatting object for our headline: var headLineFormat = new Formatting(); headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black"); headLineFormat.Size = 14D; headLineFormat.Position = 12; headLineFormat.FontColor = System.Drawing.Color.Green; // Create the document in memory: var doc = DocX.Create(fileName); // A formatting object for our normal paragraph text: var paraFormat = new Formatting(); paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); paraFormat.Size = 9D; Paragraph title = doc.InsertParagraph(headlineText, false, headLineFormat); title.Alignment = Alignment.center; Paragraph scenes = doc.InsertParagraph("Scene " + scene, false, paraScene); scenes.Alignment = Alignment.left; Paragraph texts = doc.InsertParagraph(paraOne, false, paraFormat); // Save to the output directory: doc.Save(); } else { // Create the document in memory: using (DocX doc = DocX.Load(@fileName)) { doc.ReplaceText("Novacode.DocX", "", true, RegexOptions.IgnoreCase); doc.InsertParagraph(Environment.NewLine); //string docText = doc.ToString() + txt; var paraFormat = new Formatting(); paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri"); paraFormat.Size = 9D; Paragraph scenes = doc.InsertParagraph("Scene " + scene, false, paraScene); scenes.Alignment = Alignment.left; //doc.InsertParagraph(docText, false, paraFormat); doc.InsertParagraph(txt, false, paraFormat); // Save to the output directory: doc.Save(); } } }
public string SerializeObject(object o, Formatting f) { return(JsonConvert.SerializeObject(o, f, _converter)); }
public static string SerializeToAnonymousObject(this object o, string indentation = "\t\t\t\t", Formatting format = Formatting.Indented) { if (o is string) { return(o.ToString().SurroundWithQuotes()); } var serializer = new JsonSerializer() { Formatting = format }; var stringWriter = new StringWriter(); var writer = new JsonTextWriter(stringWriter); writer.QuoteName = false; serializer.Serialize(writer, o); writer.Close(); //anonymousify the json var anon = stringWriter.ToString() .Replace("{", "new {") .Replace("]", "}") .Replace("[", "new [] {") .Replace(":", "=") .Replace("http=", "http:"); //match indentation of the view anon = Regex.Replace(anon, @"^(\s+)?", (m) => { if (m.Index == 0) { return(m.Value); } return("\t\t\t\t" + m.Value.Replace(" ", "\t")); }, RegexOptions.Multiline); //escape c# keywords in the anon object anon = anon.Replace("default=", "@default=").Replace("params=", "@params="); //docs contain different types of anon objects, quick fix by making them a dynamic[] anon = anon.Replace("docs= new []", "docs= new dynamic[]"); //fix empty untyped arrays, default to string anon = Regex.Replace(anon, @"new \[\] \{[\s\t\r\n]*\}", "new string[] {}"); //quick fixes for settings: index.* and discovery.zen.* //needs some recursive regex love perhaps in the future anon = Regex.Replace(anon, @"(index|discovery)\.([^=]+)=([^\r\n,]+)", " { \"$1.$2\", $3 }", RegexOptions.Multiline); anon = Regex.Replace(anon, @"new \{(\r\n\s+\{ "")(index|discovery)", "new Dictionary<string, object> {$1$2", RegexOptions.Multiline); return(anon); }
public override string ToPrintString() { string header = "Start ADPU Request: " + this.GetType().Name; string body = "P1: " + Formatting.ByteArrayToHexString(new byte[] { P1 }) + " P2: " + Formatting.ByteArrayToHexString(new byte[] { P2 }); string footer = "End ADPU Request: " + this.GetType().Name; StringBuilder sb = new StringBuilder(); sb.AppendLine(header).AppendLine(body).Append(footer); return(sb.ToString()); }
public static string ToJson(this object value, Formatting formatting = Formatting.None) { return(JsonConvert.SerializeObject(value, formatting)); }
/// <summary> /// Outgoing objects will be serialized into a JSON wrapper object using the Newtonsoft.Json library /// </summary> /// <param name="builder"></param> /// <param name="formatting"></param> /// <returns></returns> public static IHypermediaResolverBuilder WithSingleNewtonsoftJsonObjectParameterSerializer(this IHypermediaResolverBuilder builder, Formatting formatting = Formatting.None) { return(builder.WithCustomParameterSerializer(() => new SingleNewtonsoftJsonObjectParameterSerializer(formatting))); }
public override void Table(string tableName) { base.Table(Formatting.Pluralize(tableName)); }
public ChangeHfState(List <Property> properties, World world) : base(properties, world) { foreach (Property property in properties) { switch (property.Name) { case "state": switch (property.Value) { case "settled": State = HfState.Settled; break; case "wandering": State = HfState.Wandering; break; case "scouting": State = HfState.Scouting; break; case "snatcher": State = HfState.Snatcher; break; case "refugee": State = HfState.Refugee; break; case "thief": State = HfState.Thief; break; case "hunting": State = HfState.Hunting; break; case "visiting": State = HfState.Visiting; break; default: State = HfState.Unknown; property.Known = false; break; } break; case "substate": SubState = Convert.ToInt32(property.Value); break; case "coords": Coordinates = Formatting.ConvertToLocation(property.Value); break; case "hfid": HistoricalFigure = world.GetHistoricalFigure(Convert.ToInt32(property.Value)); break; case "site_id": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "subregion_id": Region = world.GetRegion(Convert.ToInt32(property.Value)); break; case "feature_layer_id": UndergroundRegion = world.GetUndergroundRegion(Convert.ToInt32(property.Value)); break; case "site": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "mood": switch (property.Value) { case "macabre": Mood = Mood.Macabre; break; case "secretive": Mood = Mood.Secretive; break; case "insane": Mood = Mood.Insane; break; case "possessed": Mood = Mood.Possessed; break; case "berserk": Mood = Mood.Berserk; break; case "fey": Mood = Mood.Fey; break; case "melancholy": Mood = Mood.Melancholy; break; case "fell": Mood = Mood.Fell; break; case "catatonic": Mood = Mood.Catatonic; break; default: Mood = Mood.Unknown; property.Known = false; break; } break; case "reason": switch (property.Value) { case "failed mood": Reason = ChangeHfStateReason.FailedMood; break; case "gather information": Reason = ChangeHfStateReason.GatherInformation; break; case "be with master": Reason = ChangeHfStateReason.BeWithMaster; break; case "flight": Reason = ChangeHfStateReason.Flight; break; case "scholarship": Reason = ChangeHfStateReason.Scholarship; break; case "on a pilgrimage": Reason = ChangeHfStateReason.Pilgrimage; break; case "lack of sleep": Reason = ChangeHfStateReason.LackOfSleep; break; case "great deal of stress": Reason = ChangeHfStateReason.GreatDealOfStress; break; default: if (property.Value != "-1") { property.Known = false; } break; } break; } } if (HistoricalFigure != null) { HistoricalFigure.AddEvent(this); HistoricalFigure.States.Add(new HistoricalFigure.State(State, Year)); HistoricalFigure.State lastState = HistoricalFigure.States.LastOrDefault(); if (lastState != null) { lastState.EndYear = Year; } HistoricalFigure.CurrentState = State; } Site.AddEvent(this); Region.AddEvent(this); UndergroundRegion.AddEvent(this); }
public bool WriteTicketToWord(IDictionary <QuestionInfo, IEnumerable <AnswerInfo> > ticket, UserInfo user, int ticketID, string namefile) { try { var doc = DocX.Create(namefile); doc.MarginTop = 20; doc.MarginLeft = 20; doc.MarginRight = 20; doc.MarginBottom = 20; var header = new Formatting(); header.FontFamily = new System.Drawing.FontFamily("Times New Roman"); header.Size = 16; header.Bold = true; var titleName = new Formatting(); titleName.FontFamily = new System.Drawing.FontFamily("Times New Roman"); titleName.Size = 11; var titleQuestion = new Formatting(); titleQuestion.FontFamily = new System.Drawing.FontFamily("Times New Roman"); titleQuestion.Size = 9; titleQuestion.Bold = true; var titleInfo = new Formatting(); titleInfo.FontFamily = new System.Drawing.FontFamily("Times New Roman"); titleInfo.Size = 9D; titleInfo.Italic = true; var contenttext = new Formatting(); contenttext.FontFamily = new System.Drawing.FontFamily("Times New Roman"); contenttext.Size = 9D; doc.InsertParagraph("Тест для підвищення / пониження класності водіям та розрядів машиністам " + ticket.First().Key.Level, false, header).Alignment = Alignment.center; doc.InsertParagraph(string.Format("Іспит складає {0} {1}\tТаб. № {2}", PrepareString(user.Fname), PrepareString(user.Lname), new string('_', 20)), false, titleName).Alignment = Alignment.left; doc.InsertParagraph(DateTime.Now.ToString(), false, titleName).Alignment = Alignment.left; doc.InsertParagraph("Білет № " + ticketID, false, titleName).Alignment = Alignment.center; foreach (var question in ticket) { doc.InsertParagraph(question.Key.Topic, false, titleInfo); doc.InsertParagraph(question.Key.Question, false, titleQuestion); doc.InsertParagraph(question.Key.Info, false, titleInfo); foreach (var answer in question.Value) { doc.InsertParagraph(answer.Text, false, contenttext); } } doc.InsertParagraph(""); Paragraph p = doc.InsertParagraph("Підпис працівника який проходить тестування ___________________________________", false, contenttext); p.Alignment = Alignment.left; doc.InsertParagraph(""); doc.InsertParagraph(@"Підпис членів комісії ________________________________________________________ ________________________________________________________ ________________________________________________________", false, contenttext).Alignment = Alignment.left; doc.Save(); return(true); } catch (Exception ex) { throw new Exception("WriteTicketToWord " + ex.Message); } }
public Battle(List <Property> properties, World world) : base(properties, world) { Initialize(); var attackerSquadRace = new List <string>(); var attackerSquadEntityPopulation = new List <int>(); var attackerSquadNumbers = new List <int>(); var attackerSquadDeaths = new List <int>(); var attackerSquadSite = new List <int>(); var defenderSquadRace = new List <string>(); var defenderSquadEntityPopulation = new List <int>(); var defenderSquadNumbers = new List <int>(); var defenderSquadDeaths = new List <int>(); var defenderSquadSite = new List <int>(); foreach (Property property in properties) { switch (property.Name) { case "outcome": switch (property.Value) { case "attacker won": Outcome = BattleOutcome.AttackerWon; break; case "defender won": Outcome = BattleOutcome.DefenderWon; break; default: Outcome = BattleOutcome.Unknown; world.ParsingErrors.Report("Unknown Battle Outcome: " + property.Value); break; } break; case "name": Name = Formatting.InitCaps(property.Value); break; case "coords": Coordinates = Formatting.ConvertToLocation(property.Value); break; case "war_eventcol": ParentCollection = world.GetEventCollection(Convert.ToInt32(property.Value)); break; case "subregion_id": Region = world.GetRegion(Convert.ToInt32(property.Value)); break; case "feature_layer_id": UndergroundRegion = world.GetUndergroundRegion(Convert.ToInt32(property.Value)); break; case "site_id": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "attacking_hfid": NotableAttackers.Add(world.GetHistoricalFigure(Convert.ToInt32(property.Value))); break; case "defending_hfid": NotableDefenders.Add(world.GetHistoricalFigure(Convert.ToInt32(property.Value))); break; case "attacking_squad_race": attackerSquadRace.Add(Formatting.FormatRace(property.Value)); break; case "attacking_squad_entity_pop": attackerSquadEntityPopulation.Add(Convert.ToInt32(property.Value)); break; case "attacking_squad_number": attackerSquadNumbers.Add(Convert.ToInt32(property.Value)); break; case "attacking_squad_deaths": attackerSquadDeaths.Add(Convert.ToInt32(property.Value)); break; case "attacking_squad_site": attackerSquadSite.Add(Convert.ToInt32(property.Value)); break; case "defending_squad_race": defenderSquadRace.Add(Formatting.FormatRace(property.Value)); break; case "defending_squad_entity_pop": defenderSquadEntityPopulation.Add(Convert.ToInt32(property.Value)); break; case "defending_squad_number": defenderSquadNumbers.Add(Convert.ToInt32(property.Value)); break; case "defending_squad_deaths": defenderSquadDeaths.Add(Convert.ToInt32(property.Value)); break; case "defending_squad_site": defenderSquadSite.Add(Convert.ToInt32(property.Value)); break; case "noncom_hfid": NonCombatants.Add(world.GetHistoricalFigure(Convert.ToInt32(property.Value))); break; } } if (Collection.OfType <AttackedSite>().Any()) { Attacker = Collection.OfType <AttackedSite>().First().Attacker; Defender = Collection.OfType <AttackedSite>().First().Defender; } else if (Collection.OfType <FieldBattle>().Any()) { Attacker = Collection.OfType <FieldBattle>().First().Attacker; Defender = Collection.OfType <FieldBattle>().First().Defender; } foreach (HistoricalFigure attacker in NotableAttackers) { attacker.Battles.Add(this); } foreach (HistoricalFigure defender in NotableDefenders) { defender.Battles.Add(this); } foreach (HistoricalFigure nonCombatant in NonCombatants) { nonCombatant.Battles.Add(this); } for (int i = 0; i < attackerSquadRace.Count; i++) { AttackerSquads.Add(new Squad(attackerSquadRace[i], attackerSquadNumbers[i], attackerSquadDeaths[i], attackerSquadSite[i], attackerSquadEntityPopulation[i])); } for (int i = 0; i < defenderSquadRace.Count; i++) { DefenderSquads.Add(new Squad(defenderSquadRace[i], defenderSquadNumbers[i], defenderSquadDeaths[i], defenderSquadSite[i], defenderSquadEntityPopulation[i])); } var groupedAttackerSquads = from squad in AttackerSquads group squad by squad.Race into squadRace select new { Race = squadRace.Key, Count = squadRace.Sum(squad => squad.Numbers), Deaths = squadRace.Sum(squad => squad.Deaths) }; foreach (var squad in groupedAttackerSquads) { Attackers.Add(new Squad(squad.Race, squad.Count + NotableAttackers.Count(attacker => attacker.Race == squad.Race), squad.Deaths + Collection.OfType <HfDied>().Count(death => death.HistoricalFigure.Race == squad.Race && NotableAttackers.Contains(death.HistoricalFigure)), -1, -1)); } foreach (var attacker in NotableAttackers.Where(hf => Attackers.Count(squad => squad.Race == hf.Race) == 0).GroupBy(hf => hf.Race).Select(race => new { Race = race.Key, Count = race.Count() })) { Attackers.Add(new Squad(attacker.Race, attacker.Count, Collection.OfType <HfDied>().Count(death => NotableAttackers.Contains(death.HistoricalFigure) && death.HistoricalFigure.Race == attacker.Race), -1, -1)); } AttackersAsList = new List <string>(); foreach (Squad squad in Attackers) { for (int i = 0; i < squad.Numbers; i++) { AttackersAsList.Add(squad.Race); } } var groupedDefenderSquads = from squad in DefenderSquads group squad by squad.Race into squadRace select new { Race = squadRace.Key, Count = squadRace.Sum(squad => squad.Numbers), Deaths = squadRace.Sum(squad => squad.Deaths) }; foreach (var squad in groupedDefenderSquads) { Defenders.Add(new Squad(squad.Race, squad.Count + NotableDefenders.Count(defender => defender.Race == squad.Race), squad.Deaths + Collection.OfType <HfDied>().Count(death => death.HistoricalFigure.Race == squad.Race && NotableDefenders.Contains(death.HistoricalFigure)), -1, -1)); } foreach (var defender in NotableDefenders.Where(hf => Defenders.Count(squad => squad.Race == hf.Race) == 0).GroupBy(hf => hf.Race).Select(race => new { Race = race.Key, Count = race.Count() })) { Defenders.Add(new Squad(defender.Race, defender.Count, Collection.OfType <HfDied>().Count(death => NotableDefenders.Contains(death.HistoricalFigure) && death.HistoricalFigure.Race == defender.Race), -1, -1)); } DefendersAsList = new List <string>(); foreach (Squad squad in Defenders) { for (int i = 0; i < squad.Numbers; i++) { DefendersAsList.Add(squad.Race); } } Deaths = new List <string>(); foreach (Squad squad in Attackers.Concat(Defenders)) { for (int i = 0; i < squad.Deaths; i++) { Deaths.Add(squad.Race); } } AttackerDeathCount = Attackers.Sum(attacker => attacker.Deaths); DefenderDeathCount = Defenders.Sum(defender => defender.Deaths); if (Outcome == BattleOutcome.AttackerWon) { Victor = Attacker; } else if (Outcome == BattleOutcome.DefenderWon) { Victor = Defender; } if (ParentCollection is War parentWar) { if (parentWar.Attacker == Attacker) { parentWar.AttackerDeathCount += AttackerDeathCount; parentWar.DefenderDeathCount += DefenderDeathCount; } else { parentWar.AttackerDeathCount += DefenderDeathCount; parentWar.DefenderDeathCount += AttackerDeathCount; } parentWar.DeathCount += attackerSquadDeaths.Sum() + defenderSquadDeaths.Sum() + Collection.OfType <HfDied>().Count(); if (Attacker == parentWar.Attacker && Victor == Attacker) { parentWar.AttackerVictories.Add(this); } else { parentWar.DefenderVictories.Add(this); } } if (Site != null) { Site.Warfare.Add(this); } if (Region != null) { Region.Battles.Add(this); } if (UndergroundRegion != null) { UndergroundRegion.Battles.Add(this); } if (attackerSquadDeaths.Sum() + defenderSquadDeaths.Sum() + Collection.OfType <HfDied>().Count() == 0) { Notable = false; } if (attackerSquadNumbers.Sum() + NotableAttackers.Count > (defenderSquadNumbers.Sum() + NotableDefenders.Count) * 10 && //NotableDefenders outnumbered 10 to 1 Victor == Attacker && AttackerDeathCount < (NotableAttackers.Count + attackerSquadNumbers.Sum()) * 0.1) //NotableAttackers lossses < 10% { Notable = false; } }