meine Sys/Db admin & Developper Notitzen - wer Rechtschreibfehler findet darf sie behalten ... my Sys/Db Admin and developper notes - I don't care about typos
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
Friday, November 30, 2018
SSRS Sql Server Reporting Services Basics
Insert Chart (rechte Maustaste)
1) Charttyp auswählen2) 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>
<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>
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
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;
}
}
}
{
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.
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
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
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
ü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
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
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;
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
.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
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
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 inC:\Program Files (x86)\Android\android-sdk\platform-tools
adb befehle
adb devices //listet alle verbundenen geräte aufadb shell //linux shell auf android gerät aufmachen
Adb Shell
partitionen
cat /proc/partitionsdf
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 !"
.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
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"
$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
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();
var migrations = hc.History.ToList();
Monday, April 23, 2018
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)
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 ExplorerTextEditor -> c# -> Advanced
Outlining - Collapse #regions when collapsing to definitionsTools:
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;
}
/// <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();
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();
Tuesday, February 20, 2018
Visual Studio aktive Datei im Solution Explorer anzeigen
Tools - Options - Projects and Solutions - Track Active Item in Solution Explorer
Friday, February 16, 2018
Monday, February 05, 2018
gamil gruppen bearbeiten
In der Kontaktansicht mehrere Kontkte auswählen, dann erscheint oben ein Gruppenicon, damit kann man die Kontakte zu Gruppen hinzufügen
Saturday, February 03, 2018
linux owndrive, flash
sudo apt-get install flashplugin-installer
sudo apt-get install owncloud-client
Friday, February 02, 2018
creating TPL Tasks c#
Task.Factory.StartNew(() => CalDaysAndSendMail(taskList), TaskCreationOptions.LongRunning);
Task has constructor from Action or Action
Action a = myVoidMethodWithoutParameters;
Task t = new Task(a);
kurz: var t = new Task(myVoidMethodWithoutParameters);
Action
Task t = new Task(a,obj);
void DoSomething(object o)
from https://www.codeproject.com/articles/189374/the-basics-of-task-parallelism-via-c:
// use an Action delegate and named method
Task task1 = new Task(new Action(printMessage));
// use an anonymous delegate
Task task2 = new Task(delegate { printMessage() });
// use a lambda expression and a named method
Task task3 = new Task(() => printMessage());
// use a lambda expression and an anonymous method
Task task4 = new Task(() => { printMessage() });:
private static void printMessage() {
Console.WriteLine("Hello, world!");
}
Thursday, February 01, 2018
Shortcuts
WINDOWS X, C ... Computerverwaltung
WINDOWS I ... neue Systemeinstellungs App
WINDOWS Q Cortana
WINDOWS I ... neue Systemeinstellungs App
WINDOWS Q Cortana
Wednesday, January 31, 2018
Rechner aufräumen / Bereinigen, Performance
Services abdrehen:
Adobe
Deinstallieren:
Bonjour Apple Dienst
Einstellungs App / Persionalisierung / Farben / unten: Transparenz abschalten
Windows Taste + Pause => erweiterte Systemeinstellungen / Erweitert / Visuelle Effekte
Adobe
Deinstallieren:
Bonjour Apple Dienst
Einstellungs App / Persionalisierung / Farben / unten: Transparenz abschalten
Windows Taste + Pause => erweiterte Systemeinstellungen / Erweitert / Visuelle Effekte
Friday, January 26, 2018
sql server FileTable: Create Path
DECLARE @Val as nvarchar(4000)
DECLARE @NextVal as nvarchar(4000)
DECLARE @Pathlocator as hierarchyid = NULL
DECLARE @ParentLocator as hierarchyid = NULL
DECLARE @LastChildLocator as hierarchyid =NULL
DECLARE curInserted CURSOR LOCAL FOR (select * from STRING_SPLIT('a1\b2\c1.txt','\'))
OPEN curInserted
FETCH NEXT FROM curInserted INTO @NextVal
SET @Val=@NextVal
WHILE (@@FETCH_STATUS = 0)
BEGIN
FETCH NEXT FROM curInserted INTO @NextVal
--check if Directory named Val already there (in Dir with parentLocator)
if (@ParentLocator is null)
BEGIN --------- root level => need parent_Path_locator is null
SET @Pathlocator = (select path_locator from MyFile where name like @Val and parent_Path_locator is null ) -- from main Dir
SET @LastChildLocator = (select top 1 path_locator from MyFile where parent_Path_locator is null order by path_locator desc) -- get latest child
SET @ParentLocator = hierarchyid::GetRoot()
END
ELSE ----- not root level - query with parent_Path_locator = @ParentLocator
BEGIN
SET @Pathlocator = (select path_locator from MyFile where name like @Val and parent_Path_locator = @ParentLocator ) -- from subdir
SET @LastChildLocator = (select top 1 path_locator from MyFile where parent_Path_locator=@ParentLocator order by path_locator desc) -- get latest child
END
if (@Pathlocator is null) --doesn't exist => have to create
BEGIN
-- get new PathLocator in parent Folder
SET @Pathlocator = @ParentLocator.GetDescendant(@LastChildLocator,NULL)
if (@@FETCH_STATUS = 0) -- not the last entry => its a dir
BEGIN
PRINT 'Create SubDir:' + @Val
INSERT INTO [dbo].MyFile ([name],is_directory,path_locator) SELECT @Val, 1, @Pathlocator -- insert next child
END
ELSE --last entry => file
BEGIN
PRINT 'Create File:' + @Val
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT @Val, CONVERT(VARBINARY(MAX),'TestFileText'), @Pathlocator -- insert next child
END
END
ELSE
BEGIN
PRINT @Val +' already exists ...'
END
SET @Val=@NextVal
SET @ParentLocator = @Pathlocator
END --WHILE
CLOSE curInserted
select file_stream.GetFileNamespacePath() as RelativePath, * from MyFile order by creation_time desc
select * from vMyFile where file_stream is null
Thursday, January 25, 2018
sql server: FileTable and hierarchyid, insert folders and files into filetable by tsql
-- Filetablename: MyFile
--create testfolder
INSERT INTO MyFile (name, is_directory) VALUES ('testFolder', 1)
--insert first file into testfolder:
DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(NULL,NULL) -- insert next child
DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent
DECLARE @Child1Locator as hierarchyid = (select top 1 path_locator from MyFile where parent_Path_locator=@ParentLocator order by path_locator desc) -- get latest child
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(@Child1Locator,NULL) -- insert next child
--create testfolder
INSERT INTO MyFile (name, is_directory) VALUES ('testFolder', 1)
--insert first file into testfolder:
DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(NULL,NULL) -- insert next child
DECLARE @ParentLocator as hierarchyid = (select path_locator from MyFile where parent_Path_locator is NULL and name like 'testfolder') --get parent
DECLARE @Child1Locator as hierarchyid = (select top 1 path_locator from MyFile where parent_Path_locator=@ParentLocator order by path_locator desc) -- get latest child
INSERT INTO [dbo].MyFile ([name],[file_stream],path_locator) SELECT 't2.txt', CONVERT(VARBINARY(MAX),'TestFileText'), @ParentLocator.GetDescendant(@Child1Locator,NULL) -- insert next child
sql server STRING_SPLIT
--select * from STRING_SPLIT('\dir1\d2\test.txt','\')
DECLARE @Val as nvarchar(4000)
DECLARE curInserted CURSOR LOCAL FOR (select * from STRING_SPLIT('\dir1\d2\test.txt','\'))
OPEN curInserted
FETCH NEXT FROM curInserted INTO @Val
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Val
FETCH NEXT FROM curInserted INTO @Val
END
CLOSE curInserted
DECLARE @Val as nvarchar(4000)
DECLARE curInserted CURSOR LOCAL FOR (select * from STRING_SPLIT('\dir1\d2\test.txt','\'))
OPEN curInserted
FETCH NEXT FROM curInserted INTO @Val
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Val
FETCH NEXT FROM curInserted INTO @Val
END
CLOSE curInserted
Wednesday, January 24, 2018
Sql Server Datetime Offset SWITCHOFFSET AT TIME ZONE
--AT TIME ZONE: time and offset are calculated for given timezone
--SWITCHOFFSET: only offset is changed, time remains the same
--create example table _dto for datetimeoffset demo
CREATE TABLE [dbo].[_dto](
[id] [int] IDENTITY(1,1) NOT NULL,
[dtoUtc] [datetimeoffset](7) NULL, --utc time
[dtoLocal] [datetimeoffset](7) NULL --local time
) ON [PRIMARY]
GO
--insert winter and sommertime demo test record
INSERT [dbo].[_dto] ( [dtoUtc]) VALUES (CAST(N'2018-01-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- winter time
GO
INSERT [dbo].[_dto] ([dtoUtc]) VALUES (CAST(N'2017-07-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- summer time
GO
--get string values for available sql server time zones:
select * from sys.time_zone_info;
--show result of SWITCHOFFSET and AT TIME ZONE
select dtoUtc , --original Utc Time (offset 00)
SWITCHOFFSET(dtoUtc,1) as switch, -- time remains the same, only offset changes
dtoUtc AT TIME ZONE 'Central Europe Standard Time' as AtTimeZone -- time and offset are transfered to destination time zone, winter and summer time are calculated correct
from _dto order by dto
--update _dto set dtoLocal= dtoUtc AT TIME ZONE 'Central Europe Standard Time' -- calculating local time from utc and store it
select * from _dto
--drop table _dto; --clean up
--SWITCHOFFSET: only offset is changed, time remains the same
--create example table _dto for datetimeoffset demo
CREATE TABLE [dbo].[_dto](
[id] [int] IDENTITY(1,1) NOT NULL,
[dtoUtc] [datetimeoffset](7) NULL, --utc time
[dtoLocal] [datetimeoffset](7) NULL --local time
) ON [PRIMARY]
GO
--insert winter and sommertime demo test record
INSERT [dbo].[_dto] ( [dtoUtc]) VALUES (CAST(N'2018-01-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- winter time
GO
INSERT [dbo].[_dto] ([dtoUtc]) VALUES (CAST(N'2017-07-23T10:00:00.0000000+00:00' AS DateTimeOffset)) -- summer time
GO
--get string values for available sql server time zones:
select * from sys.time_zone_info;
--show result of SWITCHOFFSET and AT TIME ZONE
select dtoUtc , --original Utc Time (offset 00)
SWITCHOFFSET(dtoUtc,1) as switch, -- time remains the same, only offset changes
dtoUtc AT TIME ZONE 'Central Europe Standard Time' as AtTimeZone -- time and offset are transfered to destination time zone, winter and summer time are calculated correct
from _dto order by dto
--update _dto set dtoLocal= dtoUtc AT TIME ZONE 'Central Europe Standard Time' -- calculating local time from utc and store it
select * from _dto
--drop table _dto; --clean up
Thursday, January 18, 2018
Power Shell Variablen Ausgabe (String Concat, Expanding Sub Expressions)
Write-Verbose "ErrCount=$($Error.Count)"
Wednesday, January 17, 2018
Tuesday, January 16, 2018
sql server restore full & transactionlog backups
1) check waths inside the backup file:
RESTORE FILELISTONLY from disk = 'L:\My.bak'
you shoul get a list with first column
LogicalName
My
My_log
RESTORE HEADERONLY FROM DISK='L:\My.trn'
should give you a list of all transaction log backups in this file
next backup FirstLSN=LastLSN of preceeding backup
next backup FirstLSN=LastLSN of preceeding backup
2) restore full Backup:
use NoRecovery only if you want to restore Transaction Log afterwards
restore database myRestore from disk = 'L:\My.bak' with file=1, NORECOVERY,
move 'My' to 'd:\temp\my2.mdf',
move 'My_Log' to 'd:\temp\my2.ldf'
3) restore Transaction Logs:
restore database myRestore from disk = 'L:\My.trn' with file=1
if there are many transaction log backups in the file my.trn you have to restore it like this:
restore database myRestore from disk = 'L:\My.trn' with file=2
RESTORE HEADERONLY FROM DISK='L:\My.trn'
gives a list of backups in the file
Monday, January 15, 2018
c# iif (boolscherAusdruck) ? trueStatement : falseStatement;
(true) ? 1 : 0; //liefert immer 0
string todoStr = (done) ? "done !" : "todo";
Friday, January 12, 2018
local system, local service and so on / lokaler Dienst lokales System usw.
Following are NOT advised as it grant more privileges than required for running SQL Server Services
Local System is a very high-privileged built-in account. It has extensive privileges on the local system and acts as the computer on the network. The actual name of the account is "NT AUTHORITY\SYSTEM".
The Local Service account is a built-in account that has the same level of access to resources and objects as members of the Users group. This limited access helps safeguard the system if individual services or processes are compromised. Services that run as the Local Service account access network resources as a null session without credentials. Be aware that the Local Service account is not supported for the SQL Server or SQL Server Agent services. The actual name of the account is "NT AUTHORITY\LOCAL SERVICE".
The Network Service account is a built-in account that has more access to resources and objects than members of the Users group. Services that run as the Network Service account access network resources by using the credentials of the computer account. The actual name of the account is "NT AUTHORITY\NETWORK SERVICE"
Subscribe to:
Posts (Atom)