Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, December 23, 2025

Troubles with keyboard layout name

Recently, I've been experimenting with a Macro Deck, a simple programmable "keyboard" that can utilize an old Android tablet I already have to solve some practical problems or needs.


Like, what keyboard I'm using right now ?

I'm Slovak, but as a programmer, I use the English (US) keyboard layout for coding and the Slovak QWERTY layout for the Slovak language. There's also the Slovak QWERTZ layout, which is the standard, and sometimes I use Czech or German layouts just for specific words usually.

So, which keyboard layout is active after I press Windows + Space? That's the question.

So I set up my tablet and Macro Deck, with that Windows + Space , and of course a was trying to set up a label for a Macro Deck "button" to show me name of keyboard layout. There si a way to use plugins, but there is no plug in suitable, or simply I was not able to find one, so there is command line. But no AI, I mean Copilot with GPT 5.1 or Gemini 3.0, was able to prepare functional PowerShell script. I tried many times. So c# it is ... Of course some debugging was needed to get proper label by binary date returned by system, but it works. But c# exe was somehow big so I created also c++ version which is significantly smaller.

So here it is 
https://github.com/gasparovicm/KeyboardName/

Wednesday, October 14, 2020

How to show Serilog log in UI

What ? Well I tried to develop simple UI test application by which a tried to manually test my communication classes .

Of course there was idea to show log messages, errors or information messages, in UI, in this case in WPF app . 

But how  ?

So I created a field in UI, lately listBox, but how to fill that field.

Fortunately there is a simple solution , and that is sink "Observers".

_logger = new LoggerConfiguration()
    .WriteTo.Observers(events => events
       .Do(evt => {
           LogTextAppend(Environment.NewLine);
           LogTextAppend(evt.Timestamp.ToString());
           LogTextAppend(": ");
           LogTextAppend(evt.Level.ToString());
           LogTextAppend(": ");
           try
           {
               LogTextAppend(string.Format(evt.MessageTemplate.Text,
                      evt.Properties.ToArray()));
           }
           catch
           {
               LogTextAppend(evt.MessageTemplate.Text);
           }
           LogTextAppend(Environment.NewLine);
           if (!(evt.Exception is null))
           {
               LogTextAppend(JsonConvert.SerializeObject(evt.Exception));
               LogTextAppend(Environment.NewLine);
           }
       })
    .Subscribe())
    .CreateLogger();

Of course it can by simpler or more complicated, but that is up to you.

Just use nuget Serilog.Sinks.Observable


Saturday, August 17, 2019

Another LoggerWrapper

So another logger wrapper ...

In  I was working on project which should also provide library for third party developers.
And there was logging ... So main problem was we had been used an version of Log4Net and another team has been using another version ...
So we recognized that library version lock problem.

First solution was to hide our version by Costura Fody, which was not working very well, and then ... then there was more difficult solution to use reflection.

And here is : AnotherLoggerWrapper

Simple idea is that there is an interface similar to Log4Net, with some implementations, which you can use in your project, and if somebody would like to use  your library then he can provide an object which then will be "investigated" by reflection, if it is compatible with Log4Net common interface, and then will be used. Used means - delegates will be produced, so it is not so slow.

There are examples in unit tests of GitHub project LoggerWrapper.

Example - how to use :

            var logger = LoggerWrapper.CreateFromILogLikeObject(loggerMock.Object);
            logger.Info(
"testMessage");1. How delegate is created:

Example - how delegates are created:

1. MethodInfo
        private static MethodInfo GetWriteMessageMethodInfo(MethodInfo[] methods, String methodName)
        {
           
var specificMethods = from mi in methods
                                  let p = mi.GetParameters()
                                 
where p.Length == 1
                                        && (p[
0].ParameterType == typeof(object) || p[0].ParameterType == typeof(string))
                                        && mi.Name == methodName
                                        && mi.IsStatic ==
false
                                        && mi.IsPublic
                                 
select mi;
           
var specificMethodsArray = specificMethods.ToArray();
           
if (specificMethodsArray.Count() == 1)
            {
               
return specificMethodsArray[0];
            }
           
return null;
        } 2. Delegate from method info         private static LogMethods.WriteObject GetWriteMessageMethod(MethodInfo methodInfo, Object instance)
        {
            LogMethods.WriteObject method =
null;
           
if (methodInfo != null)
            {
                method = (LogMethods.WriteObject) Delegate.CreateDelegate(
typeof (LogMethods.WriteObject), instance, methodInfo);
            }

           
return method;
        } I also enjoyed development of unit tests of this project, so whole project is just fun ... Enjoy !

Wednesday, December 26, 2018

Tell mi why ...

It is Christmas Time ! :-)
Families are organizing  "meetings"... talking about everything ... also about programing.

But sometime it is ... why to hell somebody will create a method with 16 parameters when 9 of them are optional ? Why to hell ? Probably it was not done in one shot, so multiple times somebody added there a parameter , but why ? It is the worst multiparameter method I ever saw ... and then it become ... my nephew, younger then 30 , told me " I saw ones a method with 22 parameters and just one was mandatory".

Please don't do it. It is Christmas Time ...

Wednesday, July 26, 2017

Linq – Distinct - fun ?


Linq is nice. Usable. Readable. But … Distinct.
In short. There is no appropriate distinct in Linq.
What I mean “Appropriate” ?. Something like myList.Distinc(x=>x.id).
And there is nothing like that.

Possible solutions:

1. Group by

var queryLastNames =
        from student in students
        group student by student.LastName into newGroup
        orderby newGroup.Key
        select newGroup;

2. Morelinq library

  • it is a Nuget package
  • there is: 
    • myList.DistincBy(x=>x.id)
    • or myList.DistinctBy(x=>new {x.Id1,x.Id2,x.Id3)
  • it is from year 2009 … and it is still not implemented in Linq …
  • Thank you Pranay Rana

3. You can create your own TryToDictionary method


  private static Dictionary<T, K> TryToDictionary<T,K>(
         Func<K,T> getId,
         IEnumerable<K> list)
        {
            var result = new Dictionary<T, K>();
            foreach (var item in list)
            {
                if (result.ContainsKey(getId(item))) continue;
                result.Add(getId(item), item);
            }

            return result;
        }

        private static List<K> TryToUniqueList<T, K>(Func<K, T> getId, IEnumerable<K> list)
        {
            return TryToDictionary<T,K>(getId,list).Select(x => x.Value).ToList();
        }

4. Use original distinct with IEqualityComparer<T>

4.1 Implement IEqualityComparer<T>

.. Just if You really need one ...

4.2 But You can create a lambda version ! :-)

.. thank you Ruben Bartelink and Stackowerflow !

       public class LambdaEqualityComparer<T> : IEqualityComparer<T>
        {
            readonly Func<T, T, bool> _comparer;
            readonly Func<T, int> _hash;

            public LambdaEqualityComparer(Func<T, T, bool> comparer)
                : this(comparer, t => 0)
            {
            }

            public LambdaEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hash)
            {
                _comparer = comparer;
                _hash = hash;
            }

            public bool Equals(T x, T y)
            {
                return _comparer(x, y);
            }

            public int GetHashCode(T obj)
            {
                return _hash(obj);
            }
        }

then you can use it like this

myList.Distinct(new LambdaEqualityComparer<MyClass>((x,y)=>x.Property1.Equals(y.Property1)));


4.2.3 You can  also create it as extension method ...

Sunday, June 12, 2016

What is cost of casting or dynamic ?

Simple question: What is cost of casting or using dynamic ?

Answers:

  1. Simple Counter
    • Counter as long :
      • 00:00:02.6129381
    • Counter as object, and cast to long: 
      • 00:00:30.0840943
    •  Difference:
      •  casting from object to long is 11.51 times slower .
  2. Simple class with int property
    • No casting
      • 00:00:06.3978060
    • casting form object
      • 00:00:07.5841771
    • used as dynamic 
      • 00:01:27.3716838
    • Difference
      • casting from object to class is just 1.185 times slower ..
      • but dynamic.. is 13.65 times slower !
Code:


print 'hello world!'using System;
using System.Diagnostics;

namespace CsharpBoxingUnboxingAndGenericsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            objectAndLongComparison();
            objectAndClassComparison();
        }

        private static void objectAndLongComparison()
        {
            long longCounter = 0;
            object objectCounter = longCounter;
            DateTime timeLongStart, timeLongStop, timeObjectStart, timeObjectStop;
            Trace.WriteLine("Object and Long comparison:");
            timeLongStart = DateTime.Now;
            for (int i = 0; i < int.MaxValue; i++)
            {
                longCounter = longCounter + 1;
            }
            timeLongStop = DateTime.Now;
            Trace.WriteLine(timeLongStop - timeLongStart);

            timeObjectStart = DateTime.Now;
            for (int i = 0; i < int.MaxValue; i++)
            {
                objectCounter = ((long)objectCounter) + 1;
            }
            timeObjectStop = DateTime.Now;
            
            Trace.WriteLine(timeObjectStop - timeObjectStart);
        }

        private static void objectAndClassComparison()
        {

            var timeStart = new DateTime[3];
            var timeStop = new DateTime[3];
            Class1 myClass = new Class1();
            object myObject = myClass;
            dynamic myDynamic = myClass;

            Trace.WriteLine("Object and Class comparison:");
            timeStart[0] = DateTime.Now;

            for (int i = 0; i < int.MaxValue; i++)
            {
                myClass.MyProperty1 = i;
                //myClass.MyProperty2 = string.Empty;
            }
            timeStop[0] = DateTime.Now;
            Trace.WriteLine(timeStop[0] - timeStart[0]);

            timeStart[1] = DateTime.Now;
            for (int i = 0; i < int.MaxValue; i++)
            {
                ((Class1)myObject).MyProperty1 = i;
                //((Class1)myObject).MyProperty2 = string.Empty;
            }
            timeStop[1] = DateTime.Now;
            Trace.WriteLine(timeStop[1] - timeStart[1]);

            timeStart[2] = DateTime.Now;
            for (int i = 0; i < int.MaxValue; i++)
            {
                myDynamic.MyProperty1 = i;
                //myDynamic.MyProperty2 = string.Empty;
            }
            timeStop[2] = DateTime.Now;
            Trace.WriteLine(timeStop[2] - timeStart[2]);

        }
    }
} 

If you would like to play with code here it is on GitHub.

Saturday, June 4, 2016

c#.Virtual, override, new and hidden example.

Are you not sure what virtual , override, new or hidden means ?
No problem , it is easy. Here is example:

Code:

using System.Diagnostics;

namespace VirtualAndNewExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var baseClass = new BaseClass();
            var derivedVirtual = new DerivedVirtual();
            var derivedNew = new DerivedNew();
            var derivedHidden = new DerivedHidden();

            Trace.WriteLine("Not casted versions");
            baseClass.Name();
            derivedVirtual.Name();
            derivedNew.Name();
            derivedHidden.Name();
            Trace.WriteLine("Casted to base versions");
            baseClass.Name();
            ((BaseClass)derivedVirtual).Name();
            ((BaseClass)derivedNew).Name();
            ((BaseClass)derivedHidden).Name();
        }
    }

    public class BaseClass
    {
        public virtual void Name()
        {
            Trace.WriteLine("Base");
        }
    }

    public class DerivedVirtual : BaseClass
        {
            public override void Name()
            {
                Trace.WriteLine("DerivedVirtual");
            }
        }

    public class DerivedNew : BaseClass
    {
        public new void Name()
        {
            Trace.WriteLine("DerivedNew");
        }
    }

    public class DerivedHidden : BaseClass
    {
        public void Name()
        {
            Trace.WriteLine("DerivedHidden");
        }
    }

}

.. and output (in Output window) :
Not casted versions
Base
DerivedVirtual
DerivedNew
DerivedHidden
Casted to base versions
Base
DerivedVirtual
Base
Base


Now it is clear I hope .
If not you can play with this example also from GitHub.