milosev.com
  • 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

Custom attribute in App.config

Details
Written by: Stanko Milosev
Category: C#
Published: 08 June 2019
Last Updated: 09 November 2021
Hits: 4882
This article I have mostly copy / pasted from here.

Here I've already explained how to create custom section in App.config, but now I need more complicated stuff, I need to have more attributes then just key / value pair.

Here is the example:

using System;
using System.Collections.Specialized;
using System.Configuration;

namespace CustomConfig
{
  class Program
  {
    static void Main(string[] args)
    {
      MilosevBlogConfig links = (MilosevBlogConfig)ConfigurationManager.GetSection("milosev.com");
      string homePage = ConfigurationManager.AppSettings.Get("homePage");

      Console.WriteLine("Home page: " + homePage);

      foreach (MilosevBlogCategoriesElement link in links.MilosevBlogInstances)
      {
        Console.WriteLine("Blog category: " + link.BlogCategory);
      }

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

  public class MilosevBlogCategoriesElement : ConfigurationElement
  {
    [ConfigurationProperty("BlogCategory", IsKey = true, IsRequired = true)]
    public string BlogCategory
    {
      get
      {
        return (string)base["BlogCategory"];
      }
      set
      {
        base["BlogCategory"] = value;
      }
    }
  }

  public class MilosevBlogCategoriesElementCollection : ConfigurationElementCollection
  {
    public MilosevBlogCategoriesElement this[int index]
    {
      get
      {

        return (MilosevBlogCategoriesElement)BaseGet(index);
      }
      set
      {
        if (BaseGet(index) != null)
          BaseRemoveAt(index);

        BaseAdd(index, value);
      }
    }

    protected override ConfigurationElement CreateNewElement()
    {
      return new MilosevBlogCategoriesElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
      return ((MilosevBlogCategoriesElement)element).BlogCategory;
    }
  }

  public class MilosevBlogConfig : ConfigurationSection
  {
    [ConfigurationProperty("categories")]
    [ConfigurationCollection(typeof(MilosevBlogCategoriesElementCollection))]
    public MilosevBlogCategoriesElementCollection MilosevBlogInstances
    {
      get
      {
        return (MilosevBlogCategoriesElementCollection)this["categories"];
      }
    }
  }
}
App.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="milosev.com" type="CustomConfig.MilosevBlogConfig, CustomConfig"></section>
  </configSections>

  <milosev.com>
    <categories>
      <add BlogCategory="csharp"/>
      <add BlogCategory="asp.net MVC"/>
    </categories>
  </milosev.com>

  <appSettings>
    <add key="homePage" value="http://milosev.com/" />
  </appSettings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
</configuration>
POI in App.config:
  <configSections>
    <section name="milosev.com" type="CustomConfig.MilosevBlogConfig, CustomConfig"></section>
  </configSections>
Where MilosevBlogConfig looks like:
public class MilosevBlogConfig : ConfigurationSection
{
  [ConfigurationProperty("categories")]
  [ConfigurationCollection(typeof(MilosevBlogCategoriesElementCollection))]
  public MilosevBlogCategoriesElementCollection MilosevBlogInstances
  {
    get
    {
      return (MilosevBlogCategoriesElementCollection)this["categories"];
    }
  }
}
Source code you can download from here.

Fill the gap

Details
Written by: Stanko Milosev
Category: C#
Published: 30 May 2019
Last Updated: 30 May 2019
Hits: 3955
Interesting (and fast) way to fill the gap between numbers:

static void Main(string[] args)
{
  int[] gapNumbers = new int[] { 1, 3, 4, 7, 8, 10 };

  foreach (int number in FillTheGap(gapNumbers))
  {
	Console.WriteLine(number);
  }

  Console.ReadKey();
}

private static IEnumerable<int> FillTheGap(int[] gapNumbers)
{
  int prevNumber = 1;

  foreach (int number in gapNumbers)
  {
	if (prevNumber == number)
	{
	  yield return number;
	}
	else
	{
	  for (; prevNumber < number; prevNumber++)
	  {
		yield return prevNumber;
	  }
	  yield return number;
	}
	prevNumber++;
  }
}

POI:

foreach (int number in FillTheGap(gapNumbers))

Image resizing

Details
Written by: Stanko Milosev
Category: C#
Published: 22 May 2019
Last Updated: 06 April 2024
Hits: 4150
Recently I had to automatically resize images, but I ran into problem that some images were rotated. Problem was the EXIF data on some of the images was altering the orientation of the images. As explained here. So here is my method for image resizing:
    public void ResizeImage(string originalFilename, string saveTo,
                     int canvasWidth, int canvasHeight)
    {
      try
      {
        Image image = Image.FromFile(originalFilename);

        Image thumbnail = new Bitmap(canvasWidth, canvasHeight);
        Graphics graphic = Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        int originalWidth = image.Width;
        int originalHeight = image.Height;

        double ratioX = canvasWidth / (double)originalWidth;
        double ratioY = canvasHeight / (double)originalHeight;

        double ratio = ratioX < ratioY ? ratioX : ratioY;

        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

        graphic.Clear(Color.White); // white padding

        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
                         100L);

        int OrientationKey = 0x0112;
        const int NotSpecified = 0;
        const int NormalOrientation = 1;
        const int MirrorHorizontal = 2;
        const int UpsideDown = 3;
        const int MirrorVertical = 4;
        const int MirrorHorizontalAndRotateRight = 5;
        const int RotateLeft = 6;
        const int MirorHorizontalAndRotateLeft = 7;
        const int RotateRight = 8;

        if (image.PropertyIdList.Contains(OrientationKey))
        {
          if (image.PropertyIdList.Contains(OrientationKey))
          {
            var orientation = (int)image.GetPropertyItem(OrientationKey).Value[0];
            switch (orientation)
            {
              case NotSpecified: // Assume it is good.
              case NormalOrientation:
                // No rotation required.
                break;
              case MirrorHorizontal:
                thumbnail.RotateFlip(RotateFlipType.RotateNoneFlipX);
                break;
              case UpsideDown:
                thumbnail.RotateFlip(RotateFlipType.Rotate180FlipNone);
                break;
              case MirrorVertical:
                thumbnail.RotateFlip(RotateFlipType.Rotate180FlipX);
                break;
              case MirrorHorizontalAndRotateRight:
                thumbnail.RotateFlip(RotateFlipType.Rotate90FlipX);
                break;
              case RotateLeft:
                thumbnail.RotateFlip(RotateFlipType.Rotate90FlipNone);
                break;
              case MirorHorizontalAndRotateLeft:
                thumbnail.RotateFlip(RotateFlipType.Rotate270FlipX);
                break;
              case RotateRight:
                thumbnail.RotateFlip(RotateFlipType.Rotate270FlipNone);
                break;
              default:
                throw new NotImplementedException("An orientation of " + orientation + " isn't implemented.");
            }
          }
        }

        //thumbnail.RotateFlip(RotateFlipType.Rotate90FlipNone);
        thumbnail.Save(saveTo, info[1], encoderParameters);
        Debug.WriteLine($"Thumbnail from file: {originalFilename} created in {saveTo}");
      }
      catch (Exception e)
      {
        Debug.WriteLine($"Error creating thumbnail: {e.Message}");
      }
    }
POI:
int OrientationKey = 0x0112;
const int NotSpecified = 0;
const int NormalOrientation = 1;
const int MirrorHorizontal = 2;
const int UpsideDown = 3;
const int MirrorVertical = 4;
const int MirrorHorizontalAndRotateRight = 5;
const int RotateLeft = 6;
const int MirorHorizontalAndRotateLeft = 7;
const int RotateRight = 8;

if (image.PropertyIdList.Contains(OrientationKey))
{
  if (image.PropertyIdList.Contains(OrientationKey))
  {
	var orientation = (int)image.GetPropertyItem(OrientationKey).Value[0];
	switch (orientation)
	{
	  case NotSpecified: // Assume it is good.
	  case NormalOrientation:
		// No rotation required.
		break;
	  case MirrorHorizontal:
		thumbnail.RotateFlip(RotateFlipType.RotateNoneFlipX);
		break;
	  case UpsideDown:
		thumbnail.RotateFlip(RotateFlipType.Rotate180FlipNone);
		break;
	  case MirrorVertical:
		thumbnail.RotateFlip(RotateFlipType.Rotate180FlipX);
		break;
	  case MirrorHorizontalAndRotateRight:
		thumbnail.RotateFlip(RotateFlipType.Rotate90FlipX);
		break;
	  case RotateLeft:
		thumbnail.RotateFlip(RotateFlipType.Rotate90FlipNone);
		break;
	  case MirorHorizontalAndRotateLeft:
		thumbnail.RotateFlip(RotateFlipType.Rotate270FlipX);
		break;
	  case RotateRight:
		thumbnail.RotateFlip(RotateFlipType.Rotate270FlipNone);
		break;
	  default:
		throw new NotImplementedException("An orientation of " + orientation + " isn't implemented.");
	}
  }
}
With this code I was checking if image has to be rotated. Example application (at this moment still under development), you can see on my GitHub.

---

UPDATE 2024-04-06 Note that Image and are I disposable, so correct way would be:

    public void ResizeImage(string originalFilename, string saveTo,
                     int canvasWidth, int canvasHeight)
    {
      try
      {
        using (Image image = Image.FromFile(originalFilename))
        using (Image thumbnail = new Bitmap(canvasWidth, canvasHeight))
        using (Graphics graphic = Graphics.FromImage(thumbnail))
        {
...
Otherwise image file will stay locked.

Infragistics UltraGrid with hierarchical data

Details
Written by: Stanko Milosev
Category: C#
Published: 04 December 2018
Last Updated: 04 December 2018
Hits: 1820
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace UltraGridHierarchical
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<MyChild> stankosKids = new List<MyChild>();
            stankosKids.Add(new MyChild {Name = "Velimir", Gender = "Male"});
            stankosKids.Add(new MyChild {Name = "Hilda", Gender = "Female"});

            List<MyChild> arnoldsKids = new List<MyChild>();
            arnoldsKids.Add(new MyChild {Name = "Thomas", Gender = "Male"});
            arnoldsKids.Add(new MyChild {Name = "Sabrina", Gender = "Female"});

            List<MyChild> chucksKids = new List<MyChild>();
            chucksKids.Add(new MyChild {Name = "Bruce", Gender = "Male"});
            chucksKids.Add(new MyChild {Name = "Lee", Gender = "Female"});

            List<MyParent> list = new List<MyParent>();
            list.Add(new MyParent {ID = 1, FirstName = "Stanko", LastName = "Milosev", Address = "Herseler strasse 8", MyKids = stankosKids});
            list.Add(new MyParent {ID = 2, FirstName = "Arnold", LastName = "Schwarzeneger", Address = "Whitehouse 1", MyKids = arnoldsKids});
            list.Add(new MyParent {ID = 3, FirstName = "Chuck", LastName = "Norris", Address = "Las Vegas", MyKids = chucksKids});

            ultraGrid1.SetDataBinding(list, null);
        }

        public class MyParent
        {
            public int ID { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Address { get; set; }

            public List<MyChild> MyKids { get; set; }
        }

        public class MyChild
        {
            public string Name { get; set; }
            public string Gender { get; set; }
        }
    }
}
Source code.
  1. Custom section in App.Config
  2. Interpolated Strings vs Composite Formatting
  3. IEnumerable - new instance
  4. IComparer

Subcategories

C#

Azure

ASP.NET

JavaScript

Software Development Philosophy

MS SQL

IBM WebSphere MQ

MySQL

Joomla

Delphi

PHP

Windows

Life

Lazarus

Downloads

Android

CSS

Chrome

HTML

Linux

Eclipse

Page 15 of 168

  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19