Thursday, March 21, 2019

asp.net core and EF (asp.net types: empty, API)

Connection Strings

InMemory Datenbank:

services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));

LocalDb

aus https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db?tabs=visual-studio

var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
    services.AddDbContext<BloggingContext>
        (options => options.UseSqlServer(connection));

leere Web App

Programm.cs startet Webhost mit class Startup und Methode Configure, z.b.: 

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });

einfaches Webservice (API)

webApi Template Projekt erstellen - liefert value1, value2 durch ValuesController, der einfach auf GET Request mit Konstantem String antwortet, dazu genügen die Attribute:
    [Route("api/[controller]")] // antwortet auf SubDir mit Controllername (schneided Controller Suffix weg)
    [ApiController]

in Startup.cs: app.UseMvc();


füge Model Klasse und DbContext hinzu:

Model(s):

    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }

DbContext:

public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
            : base(options)
        {
        }
        public DbSet<TodoItem> TodoItems { get; set; }
    }

in Startup.cs DbContext hinzufügen:
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }


Controller hinzufügen (rechte Maustaste auf Controller Ordner )

1)MVC-Controller leer
2) MVC Controller mit Ansichten unter Verwendung von EF
3) MVC Controller mit Lese/SchreibAktionen
4) API-Controller leer:
    [Route("api/[controller]")]
    [ApiController]
    public class EmptyController : ControllerBase
    {
    }
5) API-Controller mit Lese/Schreibaktionen:
fügt get, post,put und delete Methoden hinzu, unter Annahme einer id vom Typ int,, gibt string "value" zurück
6) API-Controller mit Aktionen unter Verwendung von EF:
in Maske Context und Modell Klasse auswählen => generiert API mit put, get usw.


Statische Files

schließlich jquery static file dass die api nutzt:
in Startup.onfigure:
            app.UseDefaultFiles();
            app.UseStaticFiles();



Wednesday, March 20, 2019

clean obj bin

Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }

asp.net core EF core migrations

1) add a model
    public class TestEntity
    {
        public int Id { get; set; }

        public string TestString { get; set; }

    }

2) add a context
    public class TestContext1 : DbContext
    {
        DbSet<TestEntity> TestEntities { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer(@"Server=localhost\sqlexpress;Database=test;Trusted_Connection=True;");
            }
         

        }
    }

3) start Nuget Package Manager Console: ALT T N O
select the project with your model and context as start project
Add-Migration M0001
update-database

WICHTIG: Projekt mit Context muß als Startup projekt und in Nuget Manager Console ausgewählt sein ! Bei Asp.Net muß der Context auch in der Startup Klasse sein ...

asp.net core using existing db

https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

1) in Packet-Manager-Console: Scaffold-DbContext "Server=localhost\sqlexpress;Database=test;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
=> erzeugt Context und EF Models
2) in Startup.cs Context regisitrieren:
services.AddDbContext<testContext>();

3) rechts click auf Controllers, Add Controller, MVC Controller mit Ansichten (Views) unter Verwendung von EF

4) Starten, und in adresszeile den Modellnamen hinzufügen

Monday, March 18, 2019

einfaches css beispiel

<link rel="stylesheet" type="text/css" href="style.css" />
<h1>header1</h1>
normal
<p style="color:green; font-weight: bold; ">absatz</p>

direkt im code: style="Eigenschaft:wert"

in style.css (einbinden mit link rel="stylesheet" type="text/css" href="style.css" )

h1 { color:red}

wordpress grundlagen

https://www.miss-webdesign.at/wordpress-grundlagen/

theme:
jedes jahr bringt wordpress ein neues theme raus - 2015 twentyFifteen stellt das menü in der sidebar als Baum dar, 2017 twentySeventeen bringt die menüpunkte nebeneinander

child theme:
neuen ordner in wp_content/themes mit parentTheme-child name und 3 dateien: style.css, functions.php und screenshot.png:

siteurls usw. in db in wp_options tabelle

define('FS_METHOD','direct');
chown www-data:www-data wordpress -R


wordpress auf linux

Apache, php installieren und testen:

sudo apt install apache2 php libapache2-mod-php -y
sudo service apache2 restart
cd /var/www/html/
create index.php:
<?php echo "hello world"; ?>
<?php echo date('Y-m-d H:i:s'); ?>
<?php phpinfo(); ?>

mysql installieren

sudo apt install mysql-server php-mysql phpmyadmin -y
sudo wget http://wordpress.org/latest.tar.gz
sudo tar xzf latest.tar.gz
=> test localhost/wordpress Directory sollte etwas anzeigen
sudo chown -R www-data: .
sudo mysql_secure_installation

Datenbank anlegen

sudo mysql -uroot -p
create database wordpress;
GRANT ALL PRIVILEGES ON wordpress.* TO 'root'@'localhost' IDENTIFIED BY 'PASSWORD';
FLUSH PRIVILEGES;
Exit the MariaDB database management tool with Ctrl + D.

Wordpress installieren

initial Seite wordpress aufrufen und db daten eingeben

Thursday, March 14, 2019

wpf dependency Properties

Definition 

in z.b. UserControl
public partial class MyUserControl : UserControl
{
        public static readonly DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(string), typeof(MyUserControl ), new FrameworkPropertyMetadata("DefaultHeaderText"));

//zusätzlich um einfacheen Setzten / Lesen der Dep.property:
        public string Header
        {
            get => (string)GetValue(HeaderProperty);
            set => SetValue(HeaderProperty, value);
        }
...

Binding 

im Usercontrol:
<UserControl x:Name="myUserControl"

<TextBlock Text="{Binding Header, ElementName=myUserControl}"/>

wichtig mit ElementName=myUserControl wird richtiger Context hergestellt

asp.net core simple web

create a dir
dotnet new web
creates Startup.cs and other files
dotnet run
browse localhost:5000


static files:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2
in Startup.cs

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseStaticFiles(); }

then create test.htm in wwwroot with any text in it
browse localhost:5000/test.htm

or:
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseStaticFiles();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

Wednesday, March 13, 2019

asp.net core on raspi (rasbian)

Installieren .netcore am rasperry:

This section is sourced from Dave the Engineer’s post on the Microsoft blog website.
The following commands need to be run on the Raspberry Pi whilst connected over an SSH session or via a terminal in the PIXEL desktop environment.
  • Run sudo apt-get install curl libunwind8 gettext. This will use the apt-get package manager to install three prerequiste packages.
  • Run curl -sSL -o dotnet.tar.gz https://dotnetcli.blob.core.windows.net/dotnet/Runtime/release/2.0.0/dotnet-runtime-latest-linux-arm.tar.gz to download the latest .NET Core Runtime for ARM32. This is refereed to as armhf on the Daily Builds page.
  • Run sudo mkdir -p /opt/dotnet && sudo tar zxf dotnet.tar.gz -C /opt/dotnet to create a destination folder and extract the downloaded package into it.
  • Run sudo ln -s /opt/dotnet/dotnet /usr/local/bin` to set up a symbolic link…a shortcut to you Windows folks 😉 to the dotnet executable.
  • Test the installation by typing dotnet -h or dotnet --help

Erstellen einer hello world console app mit windows .net core sdk:

dotnet new console --output sample1 dotnet run --project sample1

Monday, February 25, 2019

WPF SPY Tool SNOOP

1) Fadenkreuz auf das Fenster der WPF Anwendung drag & droppen => Fenster mit GUI-Baum der WPF App öffnet sich
2) mit CRT-SHIFT Mause over wird das Control, über dem sich die Maus befindet im Snoop GUI Baum ausgewählt
3) Datacontext zeigt View Model an

Wednesday, February 20, 2019

powershell Ja Nein (Yes No)

1) mit GridView

        $Answer = "J","N" | Out-GridView -PassThru -Title "Obige Schichten wirklich löschen ?"


2) mit Read-Host

        do
        {
            $Answer = Read-Host "Obige Schichten wirklich löschen ? (J/N)"
        }
        While ($Answer -ne "J" -and $Answer -ne "N")

Powershell Ergebnis sql Abfrage anzeigen Out-Gridview

display sql return:


Write-Verbose $sql;

# if windows user has not enough rights use other eg.: -Username sa -Password xxx
$ret=invoke-sqlcmd  -Query $sql -serverinstance $ServerInstance -Database $Database 

#display in cmd window
write-host ($ret | Format-Table | Out-String)

#display in new window with columns
$Ret | Out-GridView


Tuesday, February 19, 2019

powershell Debug Verbose



  • Run $DebugPreference = 'Continue' to start seeing output from Write-Debug calls.
  • When you're done, restore preference variable $DebugPreference to its default value, using $DebugPreference = 'SilentlyContinue'
  •   $VerbosePreference = "continue"

Wednesday, February 13, 2019

hardlink link erstellen mit miklink (windows )


/J für Verzeichnis:

mklink /J Git C:\Users\myUser\AppData\Local\Programs\Git\

Monday, February 04, 2019

constraint system views sql server


select * from sys.indexes
select * from sys.check_constraints
select * from sys.key_constraints
select * from sys.default_constraints
select * from sys.sysconstraints
select * from sys.foreign_keys

Friday, January 25, 2019

Hinzufügen einer neuen Windows Installation mit bcdboot d:\windows und bcdedit / Adding another Windows Installation with bcdboot D:\Windows and bcdedit

1) make a new partition or add a new hD
2) open admin cmd
3a) bcdedit shows the current bootmenu
3b) change name with bcdedit /set {current} description "my Existing Old Windows"
4) add new partition with bcdboot D:\Windows
5) change name with bcdedit /set {id} description "myNewWindows"

bcdedit /delete {id} deletes an entry in bootmenu / löscht einen eintrag im bootmenu

mit msconfig lassen sich die boot partitionen auch anzeigen


mit shutdown.exe /r /o /t 00
kann das boot menü auffgerufen werden beim neustart

Wednesday, January 23, 2019

linux mount readonly -o ro

sudo mount -o ro /dev/sda5 /media/DatenRo

Friday, January 04, 2019

Ubuntu Mate auf Raspberry


remote Desktop raspberry pi

Server:
 sudo apt-get install xrdp
Client:
 sudo apt-get install Remmina

open ssh

open-ssh installieren (aus ubunto Software Boutique)

wenn ssh nicht startet:
sudo service ssh restart

im /etc/rc.local
service ssh restart
einfügen

Monday, December 31, 2018

Tuesday, December 11, 2018

ssrs Berechtigungen STAMM Ordner



Als Admin einen Browser öffnen, dann localhost/Reports/browse/ aufrufen, dort finden sich die Funktion Neu, Hochladen, Ordner verwalten, Sicht, Suchen
Ordner verwalten erlaubt es die Berechtigungen für den Stamm Ordner zu vergeben

Monday, December 03, 2018

linux scan network (rasperry)

sudo apt-get install nmap

sudo nmap -sn 192.168.1.0/24

https://nmap.org/book/man.html


Friday, November 30, 2018

SSRS Sql Server Reporting Services Basics

Insert Chart (rechte Maustaste) 

1) Charttyp auswählen
2) Felder aus Dataset mit Drag and Drop in die Chart Data ziehen: Summe Values Y Achse, Category Groups X Achse, Series Group: Legende

Toggle Visibility

1) Properties / ToggleItem auf eine Textbox setzen (z.b. tbToggle), neben dieser erscheint ein +- Symbol, Hidden Eigenschaft gibt an, ob die Gruppe anfangs sichtbar ist oder nicht
2) Bei der Toggle Textbox die Eigenschaft InitialToggleState setzten

Wednesday, October 31, 2018

Exchange Server Version



            string exchangeVersion = "";
            exchangeVersion = OwaTools.GetExchangeServerVersion("foo.bar@outlook.com", "pwd", "https://outlook.office365.com/EWS/Exchange.asmx");


using Microsoft.Exchange.WebServices.Data;


        /// <summary>
        /// gets Exchange Server Version
        /// </summary>
        /// <param name="userName">Domain\Username or email adress in some cases (office365)</param>
        /// <param name="userPassword">pwd</param>
        /// <param name="uri">https://server/EWS/EWS/Exchange.asmx e.g. https://outlook.office365.com/EWS/Exchange.asmx  </param>
        /// <returns></returns>
        public static string GetExchangeServerVersion(string userName, string userPassword, string uri)
        {
            var service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            service.Credentials = new NetworkCredential(userName, userPassword);
            service.Url = new Uri(uri);
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // ignore invalid or self signed certificates
            var inbox = Folder.Bind(service, WellKnownFolderName.Contacts);
            var esi = inbox.Service.ServerInfo;
            return esi.VersionString;
        }

Monday, October 01, 2018

wpf Default Style überschreiben, Datatrigger

                        <TextBox x:Name="Tb_Id" Text="bla">
                            <TextBox.Style>
                                <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
                                    <Setter Property="ToolTip" Value="tip1"></Setter>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Id}" Value="ded371c8-ca5c-416f-9879-6325650e279b">
                                            <Setter Property="ToolTip" Value="Tip2"></Setter>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBox.Style>

                        </TextBox>

wpf datatemplate usercontrol

<UserControl x:Class="isiQiri.ConfigTool.View.SupportView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             >
    <UserControl.Resources>
        <DataTemplate DataType="{x:Type class1}">
            <StackPanel Orientation="Horizontal" >
                <TextBlock Text="Shift"></TextBlock>
            </StackPanel>
        </DataTemplate>

        <DataTemplate DataType="{x:Type class2}">
            <StackPanel Orientation="Horizontal" DataContext="{Binding}">
                <TextBlock Text="EditorViewModel: " />
            </StackPanel>
        </DataTemplate>
     
    </UserControl.Resources>

   
    <StackPanel>


   <ContentControl Content="{Binding}"></ContentControl>

Wednesday, August 22, 2018

wpf validierung IDataErrorInfo, ValidatesOnDataErrors=True, NotifyOnValidationError=True

um eigene DataError Validierung durchzuführen, muß das Viewmodel IDataErrorInfo implementieren - das ist ein INdexer auf das Viewmodel, dem als string der Properyname der zu validierenden Eigenschaft übergeben wird, und ein string mit validierungsmessage zurückgibt. null bedeutet kein Fehler.
Im Xaml müssen im Databinding ValidatesOnDataErrors=True, NotifyOnValidationError=True gesetz sein

IDataErrorInfo implementierung:

ganz einfach (in viewmodelbaseclass z.b.)
        public virtual string this[string columnName] => null; // nothing to validate here
        public virtual string Error => EditorResources.DefaultErrorMessage;


oder dann ausimplementiert:

      public override string this[string columnName]
        {
            get
            {
                switch (columnName)
                {
                    case nameof(MinNumericValue):
                    case nameof(MaxNumericValue):
                        return _validateMinMax(_doNumericValidation, MinNumericValue, MaxNumericValue);

                    case nameof(MinDecimalValue):
                    case nameof(MaxDecimalValue):
                        return _validateMinMax(_doDecimalValidation, MinDecimalValue, MaxDecimalValue);

                    case nameof(MinDateTimeValue):
                    case nameof(MaxDateTimeValue):
                        return _validateMinMax(_doDateTimeValidation, MinDateTimeValue, MaxDateTimeValue);

                    default:
                        return null;
                }
            }
        }


die Propery Setter:

        public int? MaxNumericValue
        {
            get => _maxNumericValue;
            set
            {
                _maxNumericValue = value;
                _doNumericValidation = true;
                OnPropertyChanged();
                OnPropertyChanged(nameof(MinNumericValue));
                _doNumericValidation = false;
                IsModified = true;
             
            }
        }



        public int? MinNumericValue
        {
            get => _minNumericValue;
            set
            {
                _minNumericValue = value;
                _doNumericValidation = true;
                OnPropertyChanged();
                OnPropertyChanged(nameof(MaxNumericValue));
                _doNumericValidation = false;
                IsModified = true;
            }
        }

usw.

einfache Min Max Validierung:



        private string _validateMinMax <T>(bool doValidation, T? min, T? max) where T: struct, IComparable<T>
        {
            if (!doValidation || null == min || null == max) return null;


            if (0 >= min.Value.CompareTo(max.Value))
                return null;
            return EditorResources.MinMax_Validation;

        }

auch gut:
https://www.codeproject.com/Tips/858492/WPF-Validation-Using-IDataErrorInfo

Tuesday, August 14, 2018

linux netzwerk befehle

ip a
dhclient interfacename

Monday, July 02, 2018

raspberry pi linux first steps - fixe statische IP Adresse

Keyboard de


sudo nano /etc/default/keyboard
xkblayout="de"

sudo shutdown -r now

sudo raspi-config

fixe statische IP Adresse

sudo nano /etc/dhcpcd.conf:

interface eth0
static ip_address=192.168.1.2/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1
 

interface wlan0
static ip_address=192.168.1.6/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1

Zeitzone

der link /etc/localtime verweist auf die aktuelle lokale Zeitzoneen datei, cat /etc/localtime zeigt diese an, auf CET (Central European Time) setzten mittels:

sudo ln -sf /usr/share/zoneinfo/CET /etc/localtime

überprüfen mit:
date
date -u 

 

Wednesday, June 27, 2018

sql server Row number / Zeilen nummer

select ROW_NUMBER() OVER (ORDER by ColumnDefinition) as rownumber, *
 from sb.RowDefinition  order by ColumnDefinition

Tuesday, June 26, 2018

posh-git power shell erweiterung

auf github posh-git repro runterladen:
git clone https://github.com/dahlbyk/posh-git.git

Power shell Profile Script anlegen wenn noch nicht vorhanden (autoexec):
New-Item -ItemType File -Path $Profile -Force

%HOMEPATH%/Documents/WindowsPowerShell\Microsoft.PowerShell_profile (z.b. C:\Users\xxx\Documents\WindowsPowerShell )

im profile hinzufügen:

$installDir = "D:\github\posh-git"
Import-Module $installDir\src\posh-git.psd1
Add-PoshGitToProfile -WhatIf:$WhatIf -Force:$Force -Verbose:$Verbose

Friday, June 22, 2018

xaml basics (Binding ...)

Element.Eigenschaftsschreibweise

normalerweise werden Attribute (Eigenschaften) als String angegebeen:
<Button Width="100" Background="blue"> (parser creiert Button und setzt dessen Background Eigenschaft vom Typ Brush auf einen Solid...Brush den er aus einem StringToColorConverter erzeugt)

<Button Width="100">
<Button.Background>
<LinearGradientBrush>
<GradientStop Color="RoyalBlue" Offset="0.0" />
<GradientStop Color="White" Offset="1.0" />
</LinearGradientBrush>
</Button.Background>
</Button>

Markup Erweiterungen

system.Windows.Data.Binding, StaticResource, DynamicResource x

Binding:

Quellen: DataContext, Source, RelativSource, Elementname

Default mäßig genügt es eine Eigenschaft des Datacontextes anzugeben (und damit aufs Viewmodel=Datacontext zu binden, dieses wird solange im Baum aufwärts gesucht bis irgendein DataContext gefunden wird):

{Binding MyDatacontextProperty}

 - es ist aber auch möglich auf Eigenschaften von GUI Elemente zu binden mittels der Eigenschaft Elementname:
Text="{Binding MyText, ElementName=MyUserControl}"

<Binding Path ="Foreground" RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=UserControl}"/>

Parent: {RelativeSource AncestorType=ContentControl}

multiBinding:



                            <TextBlock.Foreground>
                                <MultiBinding Converter="{StaticResource ColorStringToBrush}">
                                    <Binding Path="FgColor" />
                                    <Binding Path ="Foreground, Elementname=Root"/>
                                </MultiBinding>
                            </TextBlock.Foreground>


Default Brushes:


_textbox.SystemColors.WindowTextBrush

_textbox.Background = SystemColors.WindowBrush;

c# if (x is Brush brush)

type abfrage gleich in variable

Thursday, June 21, 2018

Wpf Converter with DependendyProperty



    public class ColorStringToBrushConverter : DependencyObject, IValueConverter
    {
        public static readonly DependencyProperty DefaultBrush_PROPERTY = DependencyProperty.Register("DefaultBrush", typeof(Brush), typeof(ColorStringToBrushConverter));

        public Brush DefaultBrush
        {
            get => (Brush)GetValue(DefaultBrush_PROPERTY);
            set => SetValue(DefaultBrush_PROPERTY, value);
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            var brush = DefaultBrush;
            string colorString = value as string;

            if (string.IsNullOrEmpty(colorString)) //use parameter if value not set
                colorString = parameter as string;

            if (!string.IsNullOrEmpty(colorString))
            {
                var colorObject = ColorConverter.ConvertFromString(colorString);
                if (null != colorObject)
                {
                    var color = (Color)colorObject;
                    brush = new SolidColorBrush(color);
                }

            }

            return brush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Tuesday, June 19, 2018

linux hibernate / Ruhezustand

systemctl suspend
sudo pm-suspend

.net colors

            var c1 = System.Drawing.Color.Aqua;
            var c2 = SystemColors.ActiveBorderBrush;
            var c3 = System.Windows.Media.Color.FromRgb(3, 0, 0);

in Wpf gibts vordefinierte Brushes:
System.Windows.Media.Brushes ... eine Liste von SolidColorBrushes

Monday, June 18, 2018

BIOS / Bootmenu

Marke: BIOS / Bootmenu:

Lenovo: F1 / F12

Thursday, June 07, 2018

android debug bridge adb, shell basics Samsung



adb reboot bootloader

adb installieren und starten

entweder android Studio oder sdk installieren, adb.exe ist in
C:\Program Files (x86)\Android\android-sdk\platform-tools

adb befehle

adb devices //listet alle verbundenen geräte auf
adb shell //linux shell auf android gerät aufmachen

Adb Shell

partitionen

cat /proc/partitions
df

Wednesday, June 06, 2018

power shell parameter example cmdlet

<#

    .SYNOPSIS

    Upload a ConfigFile over Default Configuration

 



    .DESCRIPTION

    Uploads File with given Path over Default Configuration (is overwritten !!!)

    of a Database (default Db) of a sql SERVERINSTANCE (default localhost\sqlexpress)



    .EXAMPLE

        .\UploadConfigFile.ps1 D:\temp\Configuration.

            uploads the file Configuration. over the Default Configuration

    .EXAMPLE

        .\UploadConfigFile.ps1 D:\temp\Configuration. -ServerInstance myserver -Database db1

            uploads the file Configuration. over the Default Configuration on Database db1 of Sql Server myserver



    .PARAMETER FilePath

        mandatory, file to be uploaded over the default  configuration

    .PARAMETER Database

        optional, name of Database (default=Db)

    .PARAMETER ServerInstance

        optional, name of Sql Server Instance (default localhost/sqlexpress)







     

#>

[CmdletBinding()]

param

(

    [Parameter(Mandatory=$true)]

    [string]$FilePath,

    [string]$Database="Db",

    [string]$ServerInstance="localhost\sqlexpress"

)



$sqlCmd="exec UpdateConfigFile '$FilePath'"

Write-Debug "invoke-SqlCmd: $sqlcmd"

Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $sqlCmd -QueryTimeout 65000

Write-Host "File uploaded over Default Configuration !"

Monday, June 04, 2018

mysql auf raspi

login von cmd:
mysql -u root -p

show databases;


Friday, May 18, 2018

c# CallerMemberName attribute gibt namen der aufrufender methode zurück

    private string HelpMe([CallerMemberName] string param = "")
    {
        return param;
    }

Wednesday, May 09, 2018

power shell debug verbose

dir variable:*pref*



$DebugPreference = "Continue"

 $VerbosePreference = "Continue"

Programmpfad herausfinden in shell (where in cmd oder power shell)

linux / unix: which
windows cmd: where.exe
power shell: where.exe

n powershell muß man where.exe schreiben, da where abkürzung für Where-Object ist


Monday, May 07, 2018

Getting __MigrationHistory Table

                 HistoryContext hc = new HistoryContext(myContext.Database.Connection,"dbo");
                    var migrations = hc.History.ToList();

Thursday, April 19, 2018

simple sql server merge for insert or update for single row

merge targetTableName as target
using (values (@Key)) as source (keyname)
on [Key]=source.keyname
when matched then
update set bla=@bla
when not matched then
insert ([key], bla)
values (@key, @bla)

Flags


      [Flags]
        public enum SettingFlags : long
        {
            /// <summary>
            /// hidden in config tool for normal users
            /// </summary>
            myflag = 0b1,
            AdvancedSetting = 0b10
        }

       [NotMapped]
        public bool AdvancedSetting
        {
            get => Flags.HasFlag(SettingFlags.AdvancedSetting);
            set => Flags=SetFlag(Flags, value, SettingFlags.AdvancedSetting);
        }

        public static SettingFlags SetFlag(SettingFlags flags, bool value, SettingFlags flag)
        {
            if (value)
                flags |= flag;
            else
                flags &= flag;
            return flags;
        }





oldschool:
        private bool GetBit(SettingFlags position)
        {
            var pos = (byte)position;
            var mask = (1 << pos);
            var bit = Flags & mask;
            return 0<bit ;
        }

        private void SetBit(bool value, SettingFlags position)
        {
            var pos = (byte) position;
            var mask = (1 << pos);
            if (value)
                Flags |= mask;
            else
                Flags &= ~mask;
        }

Wednesday, March 07, 2018

Useful Tools and Settings for Visual Studio

Tools -> Options:

Environment -> InternationalSettings

Language

Environment -> General

Color Theme Dark

Environment -> Fonts & Colors -> Inactive Selected Item

xaml editor better visible

Projects and Solutions –> General

Track Active Item in Solution Explorer

TextEditor -> c# -> Advanced

Outlining - Collapse #regions when collapsing to definitions



Tools:

Match Margin: 
https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MatchMargin


Monday, March 05, 2018

WinForm bei Bedarf in Gui Task zurück

wichtig: Gui im Gui Thread öffnen !

        /// <summary>
        /// 1) check if correct thread, if not call in correct thread
        /// 2) sets Text of Control c
        /// </summary>
        /// <param name="c"></param>
        /// <param name="text"></param>
        public void _SetText(Control c, string text)
        {
            if (this.InvokeRequired)
                this.Invoke(new Action<Control, string>(_SetText), c, text);
            else
                c.Text = text;
        }



        public void _SetMax(int max)
        {
            if (this.InvokeRequired)
                this.Invoke(new Action<int>(_SetMax),max);
            else
                progressBar1.Maximum = max;
        }

        public void _IncProgressBar()
        {
            if (this.InvokeRequired)
                this.Invoke(new Action(_IncProgressBar));
            else
                progressBar1.Value += 1;
        }

longrunning c# Task mit Fehlerbehandlung

                var t = new Task(() => { ImportFile(tablename, conStr, ofd.FileName); },TaskCreationOptions.LongRunning);
                var nextTask = t.ContinueWith(antecedent =>
                {
                    if (antecedent.IsFaulted)
                    {
                        PLog.ShowAndLogError("SqlTools.ImportFile Error: " + antecedent?.Exception?.Message +antecedent?.Exception?.InnerException?.Message);
                    }
                    else if (antecedent.IsCanceled)
                    {
                        PLog.LogWarning("SqlTools.ImportFile Canceled: ");
                    }
                    else
                    {
                        PLog.LogInfo("SqlTools.ImportFile succeeded ! ");
                    }
                });
                t.Start();