Archiv der Kategorie: Programmierung

VBA: Check if string StartsWith / StartWith or EndsWith / EndWith

Problem

Visual Basic for application does not have function to test, whether a string starts with or ends with another string like it is included in the .NET Framework

Approach

Those function can easily created by using the existing string functions

Solution

The following code can be pasted to a VBA project:

Public Function EndsWith(str As String, ending As String) As Boolean
     Dim endingLen As Integer
     endingLen = Len(ending)
     EndsWith = (Right(Trim(UCase(str)), endingLen) = UCase(ending))
End Function

Public Function StartsWith(str As String, start As String) As Boolean
     Dim startLen As Integer
     startLen = Len(start)
     StartsWith = (Left(Trim(UCase(str)), startLen) = UCase(start))
End Function

Example usage:

If StartsWith(„My string has something in it“, „My string“) Then Msg Box „It is in it!“
If EndsWith(„My string has something in it“, „in it“) Then Msg Box „It is in it!“

How to add CMDER (Console Emulation) on right-click to the context menu of the Windows Explorer

Problem

You want to see an entry that opens cmder.exe in Windows Explorer at the location where you use it.

Approach

Create or download the Windows registry key that enables to open CMDER on right-click with the parameters of the Directory that you are in passed.

Solution

As Code:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\Cmder]
@="Open in Cmder"
"Icon"="D:\\cmder\\Cmder.exe,0"

[HKEY_CLASSES_ROOT\Directory\Background\shell\Cmder\command]
@="\"D:\\cmder\\Cmder.exe\" \"%V\""

[HKEY_CLASSES_ROOT\Directory\shell\Cmder]
@="Open in Cmder"
"Icon"="D:\\cmder\\Cmder.exe,0"

[HKEY_CLASSES_ROOT\Directory\shell\Cmder\command]
@="\"D:\\cmder\\Cmder.exe\" \"%1\""

or download it here.

Visual Studio 2013 : Show folders with *.cs files in the solution explorer after they suddenly disappeared / hidden

Problem

Sometimes it happens, that you have created folders in Visual Studio for your application and had put some *.cs C# Source Code files that suddenly disappeard in the solution explorer.

Analysis

I.e. that can happen when you have forgotten to save your Visual Studio application project, berfore you have closed the IDE.

Solution

Use the file explorer and navigate to your Visual Studio solution (alternatively you can right-click a source code file in your folder and select „Open contained folder“ from the context menu).

Open the .csproj file in your solution in a text editor of your choice:

.csproj files store the project structure of the solution explorer

Go to the section where the <ItemGroup /> tags are declared and add a new section with the folders and source code files you want to show in your solution like in the screenshot below

My folders Command, ViewModelBase, ViewModel and Model disappeard over night, so i readded the marked group

You can add all cs-files with a wildcard star like it is shown in the screenshot above.

Visual Studio 2013 .NET WPF : Where do i get / can i find the WPF Ribbon Control?

Problem

According to the .NET documentation the Ribbon Control should be available since WPF 4.5, what means is available since .NET Framework 4.5 . But you can not find it? Are you even thinking about the download of the Ribbon control for older versions? Not necessary, please see the following points…

Approach

We have to find out the right moment when it is generally possible to use the Ribbon control.

The following table shows, that the first version of WPF (3.0) was released with the .NET Framework 3.0. As you can see the version number of WPF is maintained synchron with the version number of the .NET framework.

WPF VersionRelease (YYYY-MM).NET VersionVisual Studio VersionMajor Features
3.02006-113.0N/AInitial Release.
WPF development can be done with VS 2005 (released in Nov 2005) too with few additions as described here.
3.52007-113.5VS 2008Changes and improvements in:
Application model, data binding, controls, documents, annotations, and 3-D UI elements.
3.5 SP12008-083.5 SP1N/ANative splash screen support, New WebBrowser control, DirectX pixel shader support.
Faster startup time and improved performance for Bitmap effects.
4.02010-044.0VS 2010New controls: Calendar, DataGrid, and DatePicker.
Multi-Touch and Manipulation
4.52012-084.5VS 2012New Ribbon control
New INotifyDataErrorInfo interface
4.5.12013-104.5.1VS 2013No Major Change
4.5.22014-054.5.2N/ANo Major Change
4.62015-074.6VS 2015Transparent child window support
HDPI and Touch improvements
Which WPF Version is included in which version of the .NET Framework?

Solution

When you have installed at least .NET Framework 4.5 you can Add the Reference „System.Windows.Control.Ribbon“ as follows:

1.) Expand the tree in in your Solution Explorer of you WPF application

2.) Right-click the „Add References“ entry and choose „Add Reference“

In the Solution Explorer of your WPF Application right-click the References entry and choose „Add Reference“

3.) In the following dialog search for „Ribbon“ in the search field on the upper right

Search for Ribbon in the Dialog that appears by using the textbox on the upper right corner

4.) After that you should be able to add the reference by using the checkbox

5.) In your XAML Code you are now able to use the <Ribbon/> Tag

Optional: 6.) If you want to use a RibbonWindow instead of a WPF Window which allows you to have the Quick Access Controls at the top of the window, you have to do the declaration in the head of MainWindow.xaml as follows:

<ribbon:RibbonWindow x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ribbon="clr-namespace:System.Windows.Controls.Ribbon;assembly=System.Windows.Controls.Ribbon"
        Title="WPF Layoutmanager" Height="399" Width="763">
    <DockPanel LastChildFill="True">
        <Ribbon DockPanel.Dock="Top" >
        </Ribbon>
         <!-- Put the last Child here -->
    </DockPanel>
</ribbon:RibbonWindow>

Additionally you have to change the base class name in the code behind window and add the using System.Windows.Controls.Ribbon :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFTutorial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Test");
        }
    }
}

.NET WPF : XAML locations to place and change WPF Styles

Intention

Like in HTML/CSS there are different source code locations where it is possible to apply appearance styles to WPF controls. In this article i want to make a really short summary of those points.

Approach

The following examples are showing the declaration places for styles in the order from local control styles to global application styles

Location examples

App.xaml (global application wide styles)

<Application x:Class="WPFTutorial.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="#ff0000" />
                <Setter Property="FontSize" Value="24" />
            </Style>
    </Application.Resources>
</Application>

MainWindow.xaml (local hierarchical inheritance from the WPF DOM)

<Window x:Class="WPFTutorial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Layoutmanager" Height="322" Width="528">
    <Window.Resources>
        <Style TargetType="TextBlock">
            <!-- This sets all TextBlock FontSize Styles within the Grid -->
            <Setter Property="FontSize" Value="15" />
            <Setter Property="Foreground" Value="red" />
        </Style>
        <Style TargetType="TabControl">
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
        </Style>
    </Window.Resources>
    <DockPanel>
        <TextBlock DockPanel.Dock="Top" VerticalAlignment="Center" Text="Ein Dockpanel.Dock=Top ist das hier und TabControl als LastChild gestretcht" />
        <TabControl>
            <TabItem Header="Grid">
                <Grid>
                    <Grid.Resources>
                        <Style TargetType="TextBlock">
                            <!-- This sets all TextBlock FontSize Styles within the Grid -->
                            <Setter Property="FontSize" Value="15" />
                        </Style>
                    </Grid.Resources>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                        <ColumnDefinition Width="1*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="1*" />
                        <RowDefinition Height="1*" />
                        <RowDefinition Height="1*" />
                    </Grid.RowDefinitions>
                    <Button Width="140" Height="50" Click="Button_Click">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="10"  Source="Images/haken.png" Stretch="UniformToFill"/>
                            <TextBlock VerticalAlignment="Center" Text="Play Sound" />
                        </StackPanel>
                    </Button>
                    <Button Grid.Column="1" Grid.Row="2" Width="140" Height="50" Click="Button_Click">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="10"  Source="Images/haken.png" Stretch="UniformToFill"/>
                            <TextBlock VerticalAlignment="Center" Text="Play Sound" />
                        </StackPanel>
                    </Button>
                    <Button Grid.Column="2" Grid.Row="1" Width="140" Height="50" Click="Button_Click">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="10"  Source="Images/haken.png" Stretch="UniformToFill"/>
                            <TextBlock VerticalAlignment="Center" Text="Play Sound" >
                                <TextBlock.Style>
                                    <!-- Dieser Style gilt nur für den Textblock local und überschreibt den GRID Style -->
                                    <Style>
                                        <Setter Property="TextBlock.FontSize" Value="10" />
                                        <Setter Property="TextBlock.FontWeight" Value="Bold" />
                                        <Setter Property="TextBlock.Foreground" Value="#ff00ff" />
                                    </Style>
                                </TextBlock.Style>
                            </TextBlock>
                        </StackPanel>
                    </Button>
                </Grid>
            </TabItem>
            <TabItem Header="StackPanel">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="Dummfug ersetzt Irrsinn"/>
                    <TextBlock Text="Irrsinn ersetzt Dummfug" />
                    <TextBlock Text="Das letzte Child ist im Gegensatz zum Dockpanel nicht gestretcht" >
                        <TextBlock.Style>
                            <Style>
                                <Setter Property="TextBlock.Foreground" Value="#ff00ff" />
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </StackPanel>
            </TabItem>
        </TabControl>
    </DockPanel>
</Window>

C# .NET : Collections im .NET Framework

Intention

Eines der wichtigsten .NET Elemente zum Verwalten vom Datenbeständen im Speicher sind Collections (Auflistungen). Im Vergleich zu normalen Array-Typen bieten diese die Möglichkeit zur Laufzeit Objekte hinzuzufügen, ohne vorher die Größe/die Anzahl der Objekte in der Collection zu kennen. Collections bieten Funktionen zum Hinzufügen, Entfernen und Suchen/Finden von Objekten. Ist ein Objekt in einer Auflistung erstmal gefunden, kann dieses über die Objektreferenz auch direkt in der Auflistung geändert werden.

Typsicher
  • Bessere Leistung
  • keine explizite Umwandlung notwendig um auf Objekteigenschaften zuzugreifen
  • Akzeptieren beim Erstellen einen Typparamter <T>
  • Unterstützung für Windows-Store-Apps
Typsicher…
Generische Auflistungen
Generische Auflistun…
Nicht
generische Auflistungen
Nicht…
Auflistungen
(Collections)
Auflistungen…
Nicht typsicher
  • Speichern Elemente als Objekt (Object)
  • erfordern explizite Umwandlung in den Objekttyp um auf Objekteigenschaften zuzugreifen
  • keine Unterstützung für Windows-Store-Apps
Nicht typsicher…
System.Collections.Concurrent
System.Collections.Concurrent
System.Collections
System.Collections
System.Array
System.Array
System.Collections.Generic
System.Collections.Generic
Threadsicher
Threadsicher
Findet man oft in älterem Code
Findet man oft…
System.Collections.Immutable
System.Collections.Immutable
NuGet-Paket
NuGet-Paket
Actor
Actor
Hinzufügen
Hinzufügen
Ändern
Ändern
Entfernen
Entfernen
Suchen
Suchen
        Collection
  1. Object 1
  2. Object 2
  3. Object 3
  4. Object n
Collectio…
«interface»
 System.Collections.IEnumerable
«interface»…
foreach(Object o in Collection) 
{
  o.Property…
}
foreach(Object o in Collectio…
«interface»
 System.Collections.Generic.IEnumerable
«interface»…
LINQ
var
query = from Object o in Collection
where o.Attribute > 95
select o;

foreach (Object o in query) {
Console.WriteLine(o.Attribute + „“
);
}
LINQ…
Viewer does not support full SVG 1.1

Auflistungen implementieren das Interface „IEnumerable“, um das Iterieren durch die Objekte in der Liste zu ermöglichen. Die foreach-Schleife nutzt beispielsweise dieses Interface um durch alle Objekte einer Collection zu iterieren.

Über die Abfragesprache LINQ (Language Integrated Query) lassen sich SQL-ähnliche Abfragen auf Collections durchführen,

Namespaces / Namensräume

Der Namensraum für .NET Framework Collections liegt unter System.Collections.*, wobei weitere Sub-Namensräume existieren.

  • System.Collections.Concurrent (mehrere Threads / Tasks können parallel auf diesen Collections im Speicher operieren)
  • System.Collections.Immutable (man arbeitet hierbei nur auf Kopien / die ursprünglichen Daten werden nicht geändert – muss zusätzlich über NuGet-Paket installiert werden)
  • System.Collections.Generic

Dynamische Strukturen/Collections allokieren immer 2^n Speicher-Plätze

Die Property „Capacity“, welche an jeder Collection anhängt, zeigt die Anzahl der Speicherplätze, die die Collection intern als Array alloziert hat. Bei 1025 Elementen werden intern 2048 Plätze vorbereitet. Bei 2049 Elementen werden intern 4096 Plätze vorbereitet.

Microsoft SQL Server: How-to realize a SQL Statement that only returns the maximum or the minimum rows of a group (similar to an non-existing aggregate function for the GROUP BY clause)

Actual situation

A change request (field „pcr“) only can have one unique assigned user that shall be informed about the assignment every night.

The assigned user (field „created_by“) of a change requests (field „pcr“) is changing several times a day. Every time the user (field „created_by“) changes to another user, a table entry with the actual time stamp (field „created_on“) is inserted to a SQL table.

At the end of the day, the system shall report via email the users that have been assigned to a PCR (only one user per change request).

The following table contains entries with people wo shall be informed every evening.

idpcrcreated_oncreated_by
1PCR-12020-02-26 09:20:52.977user1
2PCR-12020-02-26 09:20:54.667user1
3PCR-22020-02-26 09:20:57.137user1
4PCR-22020-02-26 09:20:59.003user1
5PCR-22020-02-26 09:21:07.540user3
6PCR-32020-02-26 09:21:09.850user3
7PCR-42020-02-26 09:21:12.850user3
8PCR-42020-02-26 09:21:15.100user3
9PCR-52020-02-26 09:21:55.323 user3
10PCR-22020-02-26 09:22:06.037user2
11PCR-52020-02-26 09:22:07.037user2
12PCR-72020-02-26 09:22:08.760 user2
13PCR-72020-02-26 10:20:07.233user2
14PCR-82020-02-26 10:20:08.967user2
15PCR-82020-02-26 10:20:13.393user1
16PCR-92020-02-26 10:20:15.020user1
17PCR-72020-02-26 10:20:19.497user3
18PCR-92020-02-26 10:20:20.163user3

A nightly executed batch job (at 23:59h every evening) shall provide the possibility to inform user1, user2 or user3 about their assigned PCR’s. Only the latest entry per PCR, that can be recognized by the timestamp (field „created_on“) represent the user assigned user at the end of the day

Problem

The SQL Statement shall output the latest entry per assigned user of each PCR. With a standard aggregate function this is not possible because the whole row entry has to be retrieved.

Approach

The Microsoft SQL Server has a proprietary function RANK(), that prints out the ranking of the PCR entry in connection with PARTITION BY and ORDER BY. The ORDER BY has to be used DESC, so that the latest entry always is on rank 1.

Because this methods only can be used within the SELECT statements fields and not withing WHERE, we need a second parent query to select everything with rank 1.

Solution

SELECT *
FROM (
	SELECT	id, 
			pcr,
			created_on, 
			created_by,
			RANK () OVER ( 
				PARTITION BY pcr
				ORDER BY created_on DESC
			) as biggestHasRangOne
	FROM nightly_email
)tab 
WHERE biggestHasRangOne=1 
AND CONVERT(date, GETDATE())=CONVERT (date, created_on)
Only the latest PCR assignment has been selected for that day.

To get the smallest one (minimum) in for that day you have to use

ORDER BY created_on ASC

In the RANK() – Partition by -Syntax.

Python: Getting started with Python

Intention

Since JAVA has been overtaken by Oracle, it can’t be mistaken to get skilled with the basic concepts of Python. So this is my short Getting Started tutorial with my personal conclusion.

Instead of getting annoyed about the glorification of Python, it would be better to spend some time to have a short look at this programming framework.

In the most cases a language itself is not the crucial point, but it’s what it’s framework is providing for the developer.

So the most popular thing we hear about is the capabiliy that Python is good for…

  • Data Science
  • Arteficial Intelligence (especially the library Tensor flow)

Installation

To install Python, you have to go to https://www.python.org/downloads/ and download and install Python. The website is clearly arranged and you don’t have to spend much time to search for the correct runtime according to your needs.

After you have downloaded Python, a installation wizard guides you through the installation process in two steps. It catches to my eye that there are not so much options to choose except for the folder where you want to install it.

Getting started

So what do we need now… a development environment? Hmm… well because I have installed a Visual Studio 2013, i want to test the free „Python support for Visual Studio 2013), which can be found for different Visual Studio versions here:

https://github.com/Microsoft/PTVS/releases/v2.2.2

Python Tools for Visual Studio 2013 can be downloaded from GitHub

After the installation, there is a new Project Type available, when choosing

Visual Studio 2013 menu: File –> New Project

A new Python menu appears on the left side and we can choose to create a console application

After that you can immediatly start to code Python and press the Start-Button. Here is the „Hello World!“-Program:

A „Hello World!“-Program just consists one command.

What is a little bit weird is, that it doesn’t seems to matter if you use the following Syntax instead of the function-based print:

# This Python comment is like a UNIX Shellscript comment
print "Hello world!" # Is it possible to append a comment to the end?

# Is this really clean code if it doesn't matter how you write it?
print ("Hello world!") 

# How do you write multi line?
print ("Hello "
"world!") # this works without line break

print "Hello "
"world!" #this not

print """Hello 
 world!""" #this works but shows the line break

# without declarion of a variable
print "Number 1:";
x = input(); # My first Input 
print "Number 2:";
y = input("Here you can enter the input prompt:"); # My next Input 
print """

The result is:
==============
"""

print "The result is " + str(x + y) # working
# Python is not converting 
#automatically like C# when concatenating an Int to a String

print x #works
print y #works
print "A string for x: " + str(x) +"" #working 
print "A string for y: " + y +"" #not working 
#because he thinks that y is an Integer

In console applications it is possible to work simply with input and print. By experimenting a while you can find out what is working and what is not…
An input like „2“ will be automatically converted as an integer type (when it only contains an integer). It is possible to print the integers using the function (or command) „print“, but it is not possible to print an integer concatenated to a string.

My first conclusion

„Wenn Sie Python sehen wollen, dann gehen sie doch ins Dschungelcamp!“

Nico Gerbig in WhatsApp

For non programmers it seems to be really easy to write small console programs, but the language itself allows much syntax variants that i don’t would expect as clear readable code (especially in Python 2.7 what i have been used ).

But as shown in the following Screenshot newer python versions are a little bit more strict concerning procedure-based-programming.

In newer Python versions the BASIC-like command syntax is replaced by a real procedure syntax.

As you can see above, there is a small onboard IDE shipping with python that has a console in which it is possible to execute python code directly. Additionally it allows you to write programs in whole Python files by selecting the „File->New File“ in the menu.

The IDE can be found in the Start menu after installing a
Python package

One thing that makes me muse about the language concept is the missing option for variable declaration. Learing tutorials and guides are always promoting the omission of type-safe variable declaration as innovative concept and benefit in comparison to other common programming languages. I think it would be eligable to ask the question: „Why do non type-safe languages like JavaScript need a type-safe extension like TypeScript?“. Languages like Visual Basic (for applications) have introducted the „option explicit“ command to force the developer to do this … why? 🙂

Next steps

In further steps i want to find out how to point my Visual Studio to the newer Python framework. Python 3.8 is already installed but i do not have the choice to change it in Visual Studio. So i guess there must be a seperate configuration for this.

I am looking forward to evaluate the Tensorflow AI library and what benefit i can get from it.