Micro blog about Answer to the Ultimate Question of Life, the Universe, and Everything.
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. C#

JSON in .NET

Details
Written by: Stanko Milosev
Category: C#
Published: 22 December 2019
Last Updated: 22 December 2019
Hits: 3245
Recently I was trying to deserialize JSON which I have received from Google Reverse Geocoding (Address Lookup). First I was playing with example which is described here, but I didn't like that method, since it is too complicated. In order to deserialize JSON into an object, first I have to create that object, and in case of Google it is too complicated. Here is my partial solution, when I definitely decided to give up. I needed name of the city, and state of location:
using (JsonDocument document = JsonDocument.Parse(doc))
{
	Console.WriteLine($"plus_code: {document.RootElement.GetProperty("plus_code")}");
	foreach (JsonElement element in document.RootElement.GetProperty("results").EnumerateArray())
	{
		foreach (JsonElement addComp in element.GetProperty("address_components").EnumerateArray())
		{
			Console.WriteLine($"long_name: {addComp.GetProperty("long_name")}, short_name: {addComp.GetProperty("short_name")}");
			foreach (JsonElement type in addComp.GetProperty("types").EnumerateArray())
			{
				Console.WriteLine($"type: {type.ToString()}");
			}
		}
	}
}
I have decided to go further using this (Newtonsoft.Json) solution. Just with one line of code:
JObject myJObject = JObject.Parse(doc);
I have basically extracted everything I need.

Example of generic list

Details
Written by: Stanko Milosev
Category: C#
Published: 15 December 2019
Last Updated: 15 December 2019
Hits: 3015
From Microsoft web site:

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type. A generic class, such as GenericList listed in Introduction to Generics, cannot be used as-is because it is not really a type; it is more like a blueprint for a type.

In my case I wanted to have two different generic list names, generated from different classes, but those classes would be inherited from one class, something like this:

  class IDName
  {
    public Guid ID;
    public string Name;
  }

  class FirstIDName: IDName { }
  class SecondIDName : IDName { }
Then I need one method to fill those classes:
public static void AddToIDName<T>(List<T> iDNameList, string name) where T : IDName, new()
{
  iDNameList.Add(new T
  {
	ID = Guid.NewGuid(),
	Name = name
  });
}

Here notice constraint "where T : IDName, new()". I needed constraint new because of line: "iDNameList.Add(new T"

Whole example:

using System;
using System.Collections.Generic;

namespace GenericList
{
  class Program
  {
    static void Main(string[] args)
    {
      List<FirstIDName> firstIDNames = new List<FirstIDName>();
      List<SecondIDName> secondIDNames = new List<SecondIDName>();

      AddToIDName(firstIDNames, "firstIDNameTestOne");
      AddToIDName(firstIDNames, "firstIDNameTestTwo");

      AddToIDName(secondIDNames, "secondIDNameTestOne");
      AddToIDName(secondIDNames, "secondIDNameTestTwo");
      AddToIDName(secondIDNames, "secondIDNameTestThree");

      Console.WriteLine("FirstIDName");
      foreach (FirstIDName firstIDName in firstIDNames)
      {
        Console.WriteLine($"id: {firstIDName.ID}, name: {firstIDName.Name}");
      }

      Console.WriteLine("SecondIDName");
      foreach (SecondIDName secondIDName in secondIDNames)
      {
        Console.WriteLine($"id: {secondIDName.ID}, name: {secondIDName.Name}");
      }

      Console.WriteLine("");
      Console.WriteLine("The end");
      Console.ReadKey();
    }

    public static void AddToIDName<T>(List<T> iDNameList, string name) where T : IDName, new()
    {
      iDNameList.Add(new T
      {
        ID = Guid.NewGuid(),
        Name = name
      });
    }
  }
}

GetEnumerator

Details
Written by: Stanko Milosev
Category: C#
Published: 07 October 2019
Last Updated: 09 November 2021
Hits: 3537
Example of converting dictionary to IEnumerable.
using System;
using System.Collections;
using System.Collections.Generic;

namespace GetEnumerator
{
    class Program
    {
        static void Main(string[] args)
        {
            GetEnumeratorDict getEnumerator = new GetEnumeratorDict();

            foreach (KeyValuePair<int, string> getEnumeratorItem in getEnumerator)
            {
                Console.WriteLine($"getEnumeratorItem: {getEnumeratorItem}");
            }

            Console.WriteLine("Press any key ");
            Console.ReadKey();
        }
    }

    class GetEnumeratorDict : IEnumerable
    {
        readonly Dictionary<int, string> m_internalDictionary = new Dictionary<int, string>();

        public GetEnumeratorDict()
        {
            m_internalDictionary[1] = "test";
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return m_internalDictionary.GetEnumerator();
        }

    }
}
In code line:
IEnumerator IEnumerable.GetEnumerator()
{
	return m_internalDictionary.GetEnumerator();
}
You can implement your own OrderBy, something like I already explained hier. Difference between IEnumerator and IEnumerable you can read hier

Tree structure

Details
Written by: Stanko Milosev
Category: C#
Published: 24 August 2019
Last Updated: 24 August 2019
Hits: 3209
I did little bit of exercise for tree structure data, since I am always struggling with it.

Example I took from my family tree. My grandfathers name was "Stanko" (same as me btw), he had three kids: my fathers name "Velimir", "Svetlana" and "Julka"
My father "Velimir" also had three kids: "Anamaria", "Stanko" and "Nikola"
His sister "Svetlana" had two kids: "Dragan" and "Dragana"
Dragan had one kid "Sanja" and "Dragana" two kids "Jovana" and "Aleksa"
Julka had no kids.
Structure in string looks like this:

"Stanko|Velimir|Anamaria"
"Stanko|Velimir|Stanko"
"Stanko|Velimir|Nikola"
"Stanko|Velimir|Anamaria|Tatjana"
"Stanko|Svetlana|Dragan"
"Stanko|Svetlana|Dragana"
"Stanko|Julka"
"Stanko|Svetlana|Dragan|Sanja"
"Stanko|Svetlana|Dragana|Jovana"
"Stanko|Svetlana|Dragana|Aleksa"
Main code:
using System.Collections.Generic;

namespace TreeExample
{
  class Program
  {


    static void Main(string[] args)
    {
      List<string> treeDescriptions = new List<string> { "Stanko|Velimir|Anamaria" };
      treeDescriptions.Add("Stanko|Velimir|Stanko");
      treeDescriptions.Add("Stanko|Velimir|Nikola");
      treeDescriptions.Add("Stanko|Velimir|Anamaria|Tatjana");
      treeDescriptions.Add("Stanko|Svetlana|Dragan");
      treeDescriptions.Add("Stanko|Svetlana|Dragana");
      treeDescriptions.Add("Stanko|Julka");
      treeDescriptions.Add("Stanko|Svetlana|Dragan|Sanja");
      treeDescriptions.Add("Stanko|Svetlana|Dragana|Jovana");
      treeDescriptions.Add("Stanko|Svetlana|Dragana|Aleksa");

      TreeMethods geni = new TreeMethods();
      TreeStructure geniStructure;

      geniStructure = geni.CreateStructure(treeDescriptions);

    }
  }
}
Class:
using System;
using System.Collections.Generic;

namespace TreeExample
{
  class TreeStructure
  {
    public string Name { get; set; }
    public List<TreeStructure> Children;
  }

  class TreeMethods
  {
    private TreeStructure CreateTree(string structure, TreeStructure parentTree)
    {
      if (string.IsNullOrWhiteSpace(structure))
      {
        return null;
      }
      else
      {
        string[] levels = structure.Split('|');
        if (levels.Length > 1)
          structure = structure.Substring(levels[0].Length + 1, structure.Length - levels[0].Length - 1);
        else
          structure = string.Empty;

        if (parentTree is null)
        {
          parentTree = new TreeStructure();
          parentTree.Name = levels[0];

          if (!string.IsNullOrWhiteSpace(structure))
          {
            parentTree.Children = new List<TreeStructure>();
            parentTree.Children.Add(CreateTree(structure, null));
          }
        }
        else if (parentTree.Children is null)
        {
          if (!string.IsNullOrWhiteSpace(structure))
          {
            parentTree.Children = new List<TreeStructure>();
            parentTree.Children.Add(CreateTree(structure, null));
          }
        }
        else
        {
          bool found = false;
          foreach (TreeStructure child in parentTree.Children)
          {
            string[] levelsChildren = structure.Split('|');

            if (!(child is null))
            {
              if (string.Equals(child.Name, levelsChildren[0], StringComparison.InvariantCultureIgnoreCase))
              {
                CreateTree(structure, child);
              }
            }
          }

          foreach (TreeStructure child in parentTree.Children)
          {
            string[] levelsChildren = structure.Split('|');
            if (!(child is null))
            {
              found = string.Equals(child.Name, levelsChildren[0], StringComparison.InvariantCultureIgnoreCase);
              if (found)
              {
                break;
              }
            }
          }

          if (!found && !string.IsNullOrWhiteSpace(structure))
          {
            parentTree.Children.Add(CreateTree(structure, null));
          }

        }
      }

      //there are no more leafs, go out
      return parentTree;
    }

    public TreeStructure CreateStructure(List<string> structures)
    {
      TreeStructure treeStructure = null;

      foreach (string structure in structures)
      {
        int level = 0;
        string[] rootChildren = structure.Split('|');

        treeStructure = CreateTree(structure, treeStructure);
      }

      return treeStructure;
    }

  }
}
  1. Custom attribute in App.config
  2. Fill the gap
  3. Image resizing
  4. Infragistics UltraGrid with hierarchical data

Subcategories

WPF

Beginning

Code snippets

NUnit

LINQ

Windows Forms

Page 13 of 38

  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17