Samstag, 25. September 2021

BASTA'21 impressions - not only c#10 features...

 
https://sharplab.io/ 
-> test c# code on the fly online


https://source.dot.net/
-> observe the source code of dot net. Deep dive into the source of dot net.

github.com
githubs1.com 
-> for alternative layout of github.com; you can also push . when browsing in github.com


https://devblogs.microsoft.com/dotnet/
-> first class microsoft blogs of ms team leaders, managers, high ranking employees


record struct Vector2d(double X, double Y)
{
    public static Vector2d operator +(Vector2d first, Vector2d second) =>
        new Vector2d(first.X + second.X, first.Y + second.Y);
}
-> like normal record but value typed (variable) and not referenced typed (pointer)
-> see         https://anthonygiretti.com/2021/08/03/introducing-c-10-record-struct/


readonly record struct
-> of course - readonly - makes record struct immutable

public string FirstName { get; init; } = "Neo";
-> c# class property set init only
-> read https://www.thomasclaudiushuber.com/2020/08/25/c-9-0-init-only-properties/

with 
var v2 = v1 with { X = 4d }; // clone v1 and override double property X with new value of 4d 
-> clones the source to modify it partially
-> see : https://docs.microsoft.com/de-de/dotnet/csharp/language-reference/operators/with-expression

Remember
4d -> 4.0 double value
4m -> 4.0 decimal value
4f -> 4.0 float value

nameof(myObject)
-> get the name description of the type

is
-> var x = "my text" is String;
-> predicate operation (true/false result) if object is of type ANY. Here is x true finally.

stackalloc
-> value types are stack allocates and not pushed to the heap
-> see https://docs.microsoft.com/de-de/dotnet/csharp/language-reference/operators/stackalloc


Span<Vector2d> vectors = stackalloc Vector2d[]
{
    new Vector2d(3d, 4d),
    new Vector2d(1d, 2d)
};

-> see https://docs.microsoft.com/de-de/dotnet/api/system.span-1?view=net-5.0

and even more....










Montag, 20. April 2020

MS SQL Merge upsert

multiple record writing - steps to achieve the fastest update of an table:

- create temp database table. This is a copy of the destination table to fill for finally.
- fille the temp database table with the bulk copy function of System.data.sqlClient.
- execute the MERGE script.

MERGE example:

MERGE [dbo].[THE_TABLE] as t
USING [dbo].[TEMP_THE_TABLE] as s
ON t.MY_ID=s.MY_ID AND t.MY_SEQUENCE=s.MY_SEQUENCE
WHEN MATCHED THEN 
UPDATE SET
        t.MY_VALUE=s.MY_VALUE,
        t.MY_TIMESTAMP=s.MY_TIMESTAMP
WHEN NOT MATCHED THEN 
INSERT (MY_ID, MY_SEQUENCE, MY_VALUE, MY_TIMESTAMP)
VALUES (s.MY_ID, s.MY_SEQUENCE, s.MY_VALUE, s.MY_TIMESTAMP);

(t=target, s=source)

Dienstag, 7. April 2020

Linq : short basic samples

Linq - basic how to samples:


using System.Linq;

...

[System.Serializable]
public class Item
{
public string Name;
public int ItemID;
public int Buff;
}


public class Main
{

public List<Item> Items;
public void Start()
{

string[] names = { "ralf", "Peter", "Thomas", "Christian", "Patrice" };
/* ANY demo */
var nameFound = names.Any(name => name == "Peter");
Debug.Log("Found name : " + nameFound);
/* Contains */
var nameContained = names.Contains("Christian");
Debug.Log("Found conatined : " + nameContained);
/* Distinct - remove duplicates*/
var uniqueNames = names.Distinct();
/* Where */
var result = names.Where(n => n.Length > 5);
/* select greater than results */
int[] grades = { 10, 20, 30, 40, 50, 60, 65, 70, 75, 33, 80, 13, 90, 100 };
var highGrades = grades.Where(i => i > 65);
foreach (int grade in highGrades)
{
Debug.Log("selected grade : " + grade.ToString());
}
/* select ORDER BY .. DESCENDING  */
var descGrades = grades.OrderByDescending(i => i);
foreach (var item in descGrades)
{
Debug.Log("Int item = " + item);
}
/* precondition before moving on - image the Items collection including 5x Item with various values */
/* check if ItemID 3 exists in the List of Item */
var containsId3 = Items.Where(i => i.ItemID == 3);
var itemId3found = Items.Any(i=>i.ItemID == 3);
Debug.Log("is Items including ItemId 3 : " + itemId3found);
/* select all items with buff greater then 60 and print them out */
var itemsGT60 = Items.Where(i => i.Buff > 60);
foreach (var buff in itemsGT60)
{
Debug.Log("buff Items > 60 : " + buff);
}
/* calculate the average of all the buff stats */
var resultAverage = Items.Average(i => i.Buff);
Debug.Log("Average : " + resultAverage);
}
}

...

// find the entry in an array of objects where each object got the property 'Name'

using System;
string searchForName = "Patrice"
var foundItem = Array.Find(CollectionOfItems, x=> x.Name==searchForName);

Mittwoch, 18. März 2020

json - newtowsoft - JArray - SelectToken

how to fill JArray and select all and specific items? 

private Newtonsoft.Json.Linq.JArray UFOS = new jsonlib.Linq.JArray();

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(myUFOjsonSourceString);

var list = json.list; // List of UFO items - 'list' is the root element of the source JSON structure

foreach (var item in list)
{
..
UFOS.Add(item);
...
}

IEnumerable<jsonlib.Linq.JToken> allUFOS= UFOS.SelectToken("$"); // okay, all UFOs

IEnumerable<jsonlib.Linq.JToken> oneUFO = UFOS.SelectToken("$[?(@.Pilot=='E.T.')]"); // okay, if each item of UFO would contain the property 'Pilot', select the one where Pilot=E.T. (you know, this small odd alien who wants to get home again)

Sample II:

Parse XML using Newtonsoft.Json

<root>
  <light>
    <color>red</color>
    <intensity>bright</intensity>
  </light>
  <light>
    <color>green</color>
    <intensity>light</intensity>
  </light>
</root>

XDocument doc = XDocument.Parse(mySampleXmlString); //or XDocument.Load(path)
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic pseudoXml = JsonConvert.DeserializeObject(jsonText);
Newtonsoft.Json.Linq.JArray lights = (Newtonsoft.Json.Linq.JArray)pseudoXml["root"]["light"];
foreach (var light in lights)
{
    string color = (string)light.color;
    string intensity = (string)light.intensity;
}

Dienstag, 17. März 2020

Pass string parameter plus optional placeholder fill up arguments to a method - method signature for String.Format(..)

how to setup a method getting args to be applied using String.Format(....)?

Example:

        private void log(object text, params object[] param)
        {
            string line;
            if (param != null && param.Length > 0)
                line = String.Format(text.ToString(), param);
            else
                line = text.ToString();
            if (Environment.UserInteractive==true)
                Console.WriteLine(line);
        }

text to enum value

classic request how to convert a text entry to an enum value? See..

Colors orange = (Colors) Enum.Parse(typeof(Colors), "Red, Yellow");

Dienstag, 11. Dezember 2018

how to get the current assembly version

            var assembly = Assembly.GetExecutingAssembly();
            string version = assembly.GetName().Version.ToString();

how to avoid multiple executions of a program

Define any unique ID / UID like 'a2c204cc-50a1-4fde-b47f-5b712821edf3' . If this UID isn't free, abort the application. Otherwise block it with the current process.

prepare application

public static System.Threading.Mutex mutex;
public static bool createdNewMutex;

startup application

mutex = new System.Threading.Mutex(true, "a2c204cc-50a1-4fde-b47f-5b712821edf3", out createdNewMutex);
if (!createdNewMutex) base.Shutdown(0);

final exit of the application:

if (App.createdNewMutex) App.mutex.ReleaseMutex();

Sonntag, 28. August 2016

String to Double value conversion

In different cultures differs the decimal delimiter. Therfore you could profit by such an extension method like this one. So it doesn't matter if you are using a english or german client, when converting for instance "4711.10" or "4711,10" to a double value.

        //english/Invariant system . = decimal delimiter
        //DE, NL system            , = decimal delimiter
        public static double ToDoubleEx<T>(this T obj)
        {
            if (obj == null) return 0;
            double result = 0;
            string v = Convert.ToString(obj);
            if (v != null && v.Length > 0)
            {
                var point = v.IndexOf('.');
                var komma = v.IndexOf(',');
                if (point != -1 && komma != -1)
                {
                    if (komma > point)
                        v = v.Replace(".", "");
                    else
                        v = v.Replace(",", "");
                }
                v = v.Replace(",", ".");
                result = Double.Parse(v, System.Globalization.CultureInfo.InvariantCulture); //Invariant behavior like english default behavior
            }
            return result;
        }

Benefit from the best Windows Desktop app in the world and use Strokey.Net!


Sonntag, 30. November 2014

How to cancel a parallel task

a) THREAD A:  The method for the starting of the parallel task instantiates a new System.Threading.CancellationTokenSource Object

b) THREAD A: This CancellationTokenSource is given to the parallel task

c) THREAD B: The underlying method of the parallel task includes the type of CancellationTokenSource in its signature to take it over.


If a "cancel" button was pushed in THREAD A, then CancellationTokens method Cancel must be raised. This is done like this:
CancellationTokenSource.Token.Cancel();

The routine inside THREAD B (expecting while...wend loop for instance) is checking the CancellationTokenSource.Token.IsCancellationRequested = true
state and aborts its work in this case.

done!

based information : http://msdn.microsoft.com/de-de/library/dd997364%28v=vs.110%29.aspx

Benefit from the best Windows Desktop app in the world and use Strokey.Net!

Samstag, 8. Februar 2014

shorter term of exception handling with the help of the Ternary operator

For example:

catch (System.ServiceModel.FaultException<AnyContract.ValidationError> ex)
            {
                Console.WriteLine(ex.Detail != null ? ex.Detail.Message : ex.InnerException != null ? ex.InnerException.Message : ex.Message);
            }

or

catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
            }

Benefit from the best Windows Desktop app in the world and use Strokey.Net!

Freitag, 11. Oktober 2013

How to capture a mouseclick system-wide using System.Runtime.InteropServices

If you need a short sample to handle this rare issue, consider the following steps...

* create a new WPF Application
* add a reference to System.Runtime.InteropServices
* add a public static class called "hook.cs"
* in App.xaml.cs add a static variable to buffer the hook result code
public static int hHook =0 ;

* in hook.cs add the namespace System.Runtime.InteropServices
* in hook cs add a static public method called Register() and save the hook value in the hHook of App.xaml.cs
* in hook.cs add a static public method called Unregister()
* in hook.cs add a static method as the MouseProcedure to handle the global messages
* in hook.cs add 2x Imports to register, unregister the hook and add 1x Import to pass the hook-Event. (DllImport user32.dll)
* in hook.cs -> MouseProcedure reacts on the mouseclick signal WM_LBUTTONDOWN
* register the hook in the startup of the application through calling the static method register() of the class in the hook.cs
* by leaving the application unregister such hook again through the appropriate method in hook.cs

download the short sample project here and check it in detail!

(based on http://www.codeproject.com/Articles/17969/Mouse-Operations)

Benefit from the best Windows Desktop app in the world and use Strokey.Net!

Dienstag, 20. August 2013

variant how to read a text-stream blockwise using StreamReader ReadBlock



string Textfile = @"C:\hello.txt";
Encoding enc = Encoding.Default;

FileInfo fi = new FileInfo(textfile);long remainingTillEnd = fi.Length;

int readTotalUntilNow = 0;int blocksize = 4096;
char[] buffer = new char[blocksize];
 

using (StreamReader sr = new StreamReader(Textfile,enc))
{
bool readon = true;

while (readon)
{
if (remainingTillEnd > blocksize)

{
readTotalUntilNow += sr.ReadBlock(buffer, 0, blocksize);
}
else

{
readTotalUntilNow += sr.ReadBlock(buffer, 0, (int)remainingTillEnd);

readon = false; // last block indicator
}
remainingTillEnd = fi.Length - readTotalUntilNow;
}
}
 


Benefit from the best Windows Desktop app in the world and use Strokey.Net!