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();

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

windows 10 prozesse

nach dem aufsetzten fall creators 35 hintergrundprozesse, 74 windows prozesse

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 a = DoSomething;
            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

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

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



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

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

Thursday, January 18, 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

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"

Wednesday, December 06, 2017

bin und obj rekursiv löschen / Delete bin and obj recursive

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

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

Thursday, October 12, 2017

WPF Extrem Simple Viewmodel Binding

namespace WpfExp
{
    public class ViewModel
    {
        public string ViewModelText => "MyViewModelText";
    }
}

XAML:

im Window Tag: WICHTIG nicht DataContect Direkt im Window Tag angeben, sondern extra wie folgt:
<Window.DataContext><local:ViewModel></local:ViewModel></Window.DataContext>

dann nutzen:

<Button Content="{Binding ViewModelText}" Background="Chartreuse" />




Tuesday, October 03, 2017

collapse Regions in visual studio VS 2017

Extras / Optionen / Text Editor / C# / Erweitert
#regions beim Reduzieren auf Definitionen ausblenden


Thursday, September 21, 2017

asp.net

speichern von Infos, die über page lifetime hinausgehen:
session: wenn sie abläuft sind die daten weg
application: wenn recycled weg
viewstate: wird auf client seite gespeichert

hard links windows

https://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

Windows 10 auf Hyper V installieren: Genration 2 wählen

Bei Generation 1 kommt:
"Die Microsoft-Software-Lizenzbedingungen wurden nicht gefunden. Stellen Sie sicher, dass die Installationsquellen gültig sind, und starten Sie die Installation erneut."

Bei durch VM mit Generation 2 funktioniert alles perfekt

Wednesday, September 20, 2017

make W10 Install ISO / Stick: https://www.microsoft.com/de-de/software-download/windows10

https://www.microsoft.com/de-de/software-download/windows10

sql Server Commandline Installation

Sql Express Setup from Command Prompt

only required parameters:

only sql server (db)

SETUP.EXE /QUIETSIMPLE /ACTION=Install /FEATURES=SQL /INSTANCENAME=SQLEXPRESS /SQLSVCACCOUNT="NT Authority\System" /SQLSYSADMINACCOUNTS="sqlpc\admin" /AGTSVCACCOUNT="NT Authority\System" /SECURITYMODE=SQL /sapwd="abc!" /IAcceptSQLServerLicenseTerms

with reporting services

SETUP.EXE /QUIETSIMPLE /ACTION=Install /FEATURES=SQL,RS /INSTANCENAME=SQLEXPRESS /SQLSVCACCOUNT="NT Authority\System" /SQLSYSADMINACCOUNTS="sqlPc\admin" /AGTSVCACCOUNT="NT Authority\System" /SECURITYMODE=SQL /sapwd="abc!" /IAcceptSQLServerLicenseTerms

with Directories specified


.\SETUP.EXE /QUIETSIMPLE /ACTION=Install /FEATURES=SQL /INSTANCENAME=SQLEXPRESS /SQLSVCACCOUNT="NT Authority\System" /SQLSYSADMINACCOUNTS="sqlPc\admin" /AGTSVCACCOUNT="NT Authority\System" /SECURITYMODE=SQL /sapwd="abc!" /SQLTEMPDBDIR="C:\sqlData\\" /SQLUSERDBDIR="C:\sqlData\\" /SQLUSERDBLOGDIR="C:\sqlData" /IAcceptSQLServerLicenseTerms


Monday, September 18, 2017

c# LINQ Schreibweise

//SQL Like
var ret1 = from sb in colShiftbooks select new {sb.Id};

//function
var ret2 = colShiftbooks.Select(sb => new {sb.Id});

Wednesday, September 13, 2017

c# Task Error Handling

                mail.SendAsync().ContinueWith(antecedent =>
                                              {
                                                  if (antecedent.IsFaulted)
                                                  {
                                                      _logger.Warn(antecedent.Exception, "Failed sending email");
                                                  }
                                                  else if (antecedent.IsCanceled)
                                                  {
                                                  }
                                                  else
                                                  {
                                                      _logger.Info("Succeed send email");
                                                  }
                                              });

Tuesday, September 12, 2017

EF Entity Framework Reload Entities / Refresh Cache

Reload Entities            


foreach (var entity in Context.ChangeTracker.Entries())
            {
                entity.Reload();
            }

or single entity:
Context.Entry(myEntity).Reload();

Refresh Cache

            var objectContext = ((IObjectContextAdapter)Context).ObjectContext;
            objectContext.Refresh(RefreshMode.StoreWins, Context.MyTable);

Thursday, August 10, 2017

using raspberry samba accounts from windows

login with windows explorer failes sometimes - so use:

net use driveletter uncpath /USER:sambauser

net use z: \\192.168.1.4\varbak /USER:sambauser

OsMc auf Raspy pi

Raspi Pi 1:
- von NTFS (Schwarz weiß) auf PAL umschalten
- Zoom einstellen

Pi3:
Audio von hdmi auf klinkenbuchse umstellen

raspberry sd card backup in image file

dd ... tool zum bitgenauen kopieren von hds usw
if ... in file
of ... out file

mmcblk0 ... sdcard 0


sudo dd if=/dev/mmcblk0 of=./20170810pi3Exp.img

Add Logfile To NLOG Config

        public static void AddLogFileToParent(string subLogDir)
        {
            var logDir = Path.Combine(subLogDir, "..");
            Trace.WriteLine("Adding logfile.txt to" + logDir);
            var config = LogManager.Configuration;

            var logFile = new FileTarget();
            config.AddTarget("file", logFile);

            logFile.FileName = logDir + "\\logfile.txt";
            logFile.Layout = "${date} | ${message}";

            var rule = new LoggingRule("*", LogLevel.Info, logFile);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;
        }

init NLOG by Code

        private static  void InitLogger()
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();
            // Step 2. Create targets and add them to the configuration
            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);
            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            // Step 3. Set target properties
            consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}";
            fileTarget.FileName = "${basedir}/file.txt";
            fileTarget.Layout = "${message}";
            // Step 4. Define rules
            var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);
            var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);
            // Step 5. Activate the configuration
            LogManager.Configuration = config;
            LogManager.ReconfigExistingLoggers();
        }

MS Unit Test: use TestContext to get current TestName

1) insert Property TestContext into your TestClass - its filled by MSTest:

public TestContext TestContext { get; set; }

2) then use it in TestInitialize

        [TestInitialize]
        public void TestInitialize()
        {
            LOGGER.Info("Initialize Test {0} TestDir={1}", TestContext?.TestName, TestContext?.TestDir);
}


Wednesday, August 09, 2017

c# Lamda Ausdrücke, Action, Func, Anonyme Methoden (noname, keinName)

(x,y) => x*y;  kurz für (x,y) => { return x*y; } kurz für keinName(x,y){return x*y;}

x => x*x; //nur ein Parameter - kann Klammern weglassen

() => 2*3; //kein Parameter - brauche Klammern

(int x, int y) => x*y; //typisierte parameter


aus:
http://www.lernmoment.de/csharp-programmieren/lambda-ausdruecke-erstellen/


// Deklariere ein Delegate
delegate int RechenOperation(int a, int b);

// verwende Lambda um dem delegate eine Anonyme Methode zuzuweisen.
RechenOperation multipliziere = (x, y) => x * y;

// rufe das delegate auf, um es auszuprobieren
int resultat = multipliziere(4, 5);

Action

            var a1 = new Action(p1 => p1++);
            var a2 = new Action((p1) => { p1++; });
a1=a2

            var a3 = new Action(() =>;
                               {
                                   var x = 1;
                                   x++;
                               }
            );

Func

            var f1 = new Func(() => { return 1; });
            var f2 = new Func(() => 2);

Sunday, August 06, 2017

Android 6 SD Karte partitionieren

siehe https://www.droidwiki.org/wiki/HowTo_SD-Karte_Partitionieren

adb shell

sm list-disks adoptable

sm partition disk:179,128 mixed 75

wird dann zu 75% als externe, 25% interner Speicher formatiert

Sunday, July 16, 2017

remote Desktop raspberry pi: sudo apt-get install xrdp

/etc/xrdp/xrdp.ini und /etc/xrdp/sesman.ini.

Thursday, July 06, 2017

Visual Studio Intellisens Shortcuts crtl-space, crtl-shift-space

most important Visual Studio Intellisens Shortcuts:
crtl-space
crtl-shift-space (for parameter info of a function)

raspberry phyton Hello World: first line has to be #!/usr/bin/python

using any text editor like vi, nano:


#!/usr/bin/python

print "Hello, World!";

simple FileSystemWatcher test example


            FileSystemWatcher fsw = new FileSystemWatcher(@"d:\z");
            fsw.Changed += Fsw_Changed;
            fsw.Created += Fsw_Created;
            fsw.Deleted += Fsw_Deleted;
            fsw.Renamed += Fsw_Renamed;
            fsw.EnableRaisingEvents = true;

 

        private void Fsw_Renamed(object sender, RenamedEventArgs e)
        {
            MessageBox.Show($"{e.FullPath} has been renamed");
        }

        private void Fsw_Deleted(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"{e.FullPath} has been deleted");
        }

        private void Fsw_Created(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"{e.FullPath} has been created");
        }

        private void Fsw_Changed(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"{e.FullPath} has changed");
        }

Friday, June 30, 2017

.net typed Datasets: finding out what caused congurency exception

typed datasets have a update command, which has a where clause specifing all original values - easily traced by SQL Server profiler:

'UPDATE [mytable] SET [field1] = @field1, [field2] = @field2
WHERE (([PrimaryKey] = @Original_PrimaryKey) 
AND ((@IsNull_field1 = 1 AND [field1] IS NULL) OR ([field1] = @Original_field1))
AND ((@IsNull_field2 = 1 AND [field2] IS NULL) OR ([field2] = @Original_field2))
'@field1=123, @field2='newStringValue',
@IsNull_field1=0, @Original_field1=1,
@IsNull_fiels2=0, @Original_field2='oldStringValue'

now you can compare the value in the database with the Original_Value from the command and find out which values are differnet - they are blocking.

to do this automatically, you have to catch the exception, get the modified records of the dataset you tried to save, read them again in another dataset and compare those two datasets - (original values)


Wednesday, June 28, 2017

Visual Studio: Custom Tool: Cannot find custom tool ... on this system

try to debug with procmon
filter:
 processname devenv
 path contains your custom tool name


get public key token of assembly

use signtool:
sn -T assemblyname

then use it to reference assambly:
Assembly=assemblyname, Version=1.0.0.0, publicKeyToken=7e3e8edbbbdbe145, Culture=neutral

Visual Studio Custom Tool


https://www.codeproject.com/Tips/1023337/Custom-Tool-Single-File-Generator-for-Visual-Studi

https://www.codeproject.com/search.aspx?q=Custom+Tool&doctypeid=1%3b2%3b3%3b13%3b14

Power Shell Startup Script (profile1, like autoexec.bat)

das autoexec der power shell heißt Microsoft.PowerShell_ profile.ps1 und der PFad dazu ist in $profile gfespeichert.
wenn es noch keines gibt:

# Command to create a PowerShell profile
New-Item -path $profile -type file -force

dann editieren z,.b,:
Set-Location D:\Powershell

http://www.computerperformance.co.uk/powershell/powershell_profile_ps1.htm

Monday, June 26, 2017

path regasm

c:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe

Wednesday, June 21, 2017

VisualStudio Before / After Build Commands

Very simple Execute Command BeforeBuild

   



using built in Variables

needs File Resource1.Designer.cs

   



declaring Variables

   
<resfile>"$(ProjectDir)\\Resource1.Designer.cs"


Tuesday, June 20, 2017

ways to change standard resource Manager - T4 Template for (standard) Resource Generator

1) use T4 Template instead of Resource Generator


1) add TextTemplate with same name as your resx file
2) copy and paste
3) edit the template to replace standard resourcemanager with your own

//------------------------------------------------------------------------------
//
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34003
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//
//------------------------------------------------------------------------------
<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".Designer.cs" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.IO" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml.Linq" #>

namespace WpfExp
{
    using System.Globalization;
    using System.Resources;


<#
string resxFileName = this.Host.TemplateFile.Replace(".tt", ".resx");
string className = Path.GetFileNameWithoutExtension(resxFileName);
XDocument doc = XDocument.Load(resxFileName);

#>

///





    ///   A strongly-typed resource class, for looking up localized strings, etc.
    ///
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class <#=className#>
    {

       private static global::System.Resources.ResourceManager resourceMan;
     
        private static global::System.Globalization.CultureInfo resourceCulture;
     
        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public <#=className#>() {}
     
        ///





        ///   Returns the cached ResourceManager instance used by this class.
        ///
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfExp.<#=className#>", typeof(<#=className#>).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
     
        ///





        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        ///
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }


<#
if(doc != null && doc.Root != null)
{
foreach(XElement x in doc.Root.Descendants("data"))
    {
        string name = x.Attribute("name").Value;
        WriteLine(string.Empty);
        WriteLine("        public static string " + name);
        WriteLine("        {");
        WriteLine("            get { return ResourceManager.GetString(\"" + name + "\", resourceCulture ?? CultureInfo.CurrentUICulture); }");
        WriteLine("        }");
    }
}
#>

}
}

see also: https://outlawtrail.wordpress.com/2014/03/17/custom-resources-with-t4/

2) change resource.Designer.cs in PreBuild Event:

ProjectProperties , Build Events,  pre build:

powershell.exe -command "(gc ..\..\Resource1.Designer.cs).Replace(\"new global::System.Resources.ResourceManager\", \"new MyResourceManager\") | set-content ..\..\Resource1.Designer.cs -Encoding UTF8"


very simple T4 Example / sehr einfaches T4 Beispiel

1) Add Text Template

Add a new item to your project, choose General/Text Template => TextTemplate1.tt will be added to your project

2) copy and paste below to the tt file:


<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".txt" #>

----------------- BEGINN -----------------------



<#
string name ="mike";
#>

Hello <#= name #> !

<# for (int i=0; i<10 i="" p=""> {
WriteLine("test"+i.ToString());
}
#>

------------------ ENDE ! -------------------


3) look at the results


open child file of texttemplate1.tt, should be TextTemplate1.txt should look like this:
----------------- BEGINN -----------------------




Hello mike !

test0
test1
test2
test3
test4
test5
test6
test7
test8
test9

------------------ ENDE ! -------------------

4) Basic Elements of a tt file:

template language: language in which the tempolate is written
assembly: used to execute
import = using
output= output file extension

every normal Text is simply copied to output (like --- BEGINN ...)

<# // is a code block #>

print variable:

WPF Resource Datei kann nicht aufgelöst werden: Der StaticExtension-Wert Resource kann nicht zu einer Enumeration, einem statischen Feld oder einer statischen Eigenschaft aufgelöst werden.

Der StaticExtension-Wert Resource kann nicht zu einer Enumeration, einem statischen Feld oder einer statischen Eigenschaft aufgelöst werden.

da die Resource Datei defaultmäßig zu einer internal Klasse generiert wird (vom ResXFileCodeGenerator)

Lösung: Properties der Resource Datei, Custum Tool von ResXFileCodeGenerator auf  PublicResXFileCodeGenerator ändern.

Monday, June 19, 2017

SQL SERVER RECOVERY PENDING

cause / Ursache: sql server can't access mdf or ldf file - permissions changed ? enough free space ? / Sql server kann nicht auf das mdf oder ldf file Zugreifen - haben sich die BErechtigungen geändert oder ist zuwenig Speicherplatz frei ?

after file Access is ok / nachdem der Zugriff auf die Files wieder möglich ist:

ALTER DATABASE mydb SET ONLINE;
DBCC CHECKDB('mydb')

or for all pending databases:

select 'DBCC CHECKDB(' + name + ')',* from sys.databases where state=3 -- name like 'mydb%'
select 'ALTER DATABASE ' + name + ' SET ONLINE',* from sys.databases where state=3



Wednesday, June 14, 2017

change sql server hostname

select @@servername -- view servername
EXEC sp_DROPSERVER 'oldservername'
EXEC sp_ADDSERVER 'newservername', 'local'
restart server

important Developer paths / wichtige Entwickler pfade

C:\Program Files\Microsoft SDKs

C:\Program Files (x86)\Microsoft SDKs
C:\Program Files (x86)\Windows Kits

c:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\gacutil.exe

Thursday, June 01, 2017

linux troubleshooting system analyse

top ... zeigt cpu und memory auslastung
/var/log/ ... log dateien

Wednesday, May 31, 2017

xamarin

Error: Embedded Resource ... edit xaml

Anroid Sdk: C:\Program Files (x86)\Android\android-sdk\temp ... zip entzippen und nach tools kopieren
Java must be installed

Anroid Handy: 7 mal in Einstellungen auf Buildnummer tippen, dann in Entwickleroptionen USB Debugging zulassen => wird in VS angezeigt als ... (Android 6 - APi23)


Monday, May 29, 2017

Tasks zusammanhängen mit ContinueWith und Fehlerbehandlung




      private void CreateAnys(Dictionary<string,Action> createAnyDict)
        {
            var sbNames= new StringBuilder();
            foreach (var AnyName in createAnyDict.Keys)
            {
                sbNames.Append(AnyName);
            }
            if (MessageBox.Show($"create {sbNames} Any ?", "Create Any", MessageBoxButton.YesNo) ==
                MessageBoxResult.No) return;

            SetBusy();

            var firstTask = new Task(() => SetStatusLabel("Creating Any(s)"));
            var nextTask = firstTask;
            foreach (var dictEntry in createAnyDict)
            {

                nextTask = nextTask.ContinueWith(antecedent =>
                {
                    Trace.WriteLine("Result last Task:");
                    if (antecedent.IsFaulted)
                    {
                        Trace.WriteLine("Error: "+antecedent.Exception?.Message);
                    }
                    else if (antecedent.IsCanceled)
                    {
                        Trace.WriteLine("Cancled !");
                    }
                    else
                    {
                        Trace.WriteLine("Succeeded !");
                    }
                    SetStatusLabel($"creating  Any {dictEntry.Key}");
                    try
                    {
                        dictEntry.Value.Invoke();
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine($"Error creating {dictEntry.Key}:{ex.Message}");
                    }
                });

            }
            nextTask = nextTask.ContinueWith((t) =>
                                             {
                                                 SetStatusLabel("finished creating Any(s) - ready ...");
                                                 SetReady();
                                             });

            try
            {
                firstTask.Start();
                //task0.Wait();
            }
            catch (AggregateException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

create ssh key for git

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"


list all ssh keys: ls ~/.ssh
create key: ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
passphrase eingeben
zu github unter profil ssh keys hinzufügen durch cat ~/.ssh/id_rsa.pub, kopieren und einfuegen


start ssh agent: eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa

z.b. zum .profile file im homedir hinzugeben

WPF Gui Thread Label aktualisieren



            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                                                                  { lbConStr.Content = DbHelper.GetConnectionString(); }
                ));

Tuesday, May 23, 2017

raspberry pi one wire Temperaturmessung / temperature measurement 1 wire

One wire treiber unterstützt 10 sensoren gleichzeitig

One Wire kann im Setup Menü von Rasperry unter Interfaces eingeschalten werden



sudo apt-get install rrdtool python-rrdtool

Tuesday, May 16, 2017

invoke-sqlcmd try catch : need switch -ErrorAction


you need the switch  -ErrorAction 'Stop' (of invoke-sqlcmd) to be able to  catch a invoke-sqlcmd error:


    try
    {
        invoke-sqlcmd  -Query $sqlCmd -serverinstance $ServerInstance -ErrorAction 'Stop' # if windows user has not enough rights use other eg.: -Username sa -Password xxx
    }
    catch
    {
        Write-Host "-------------------------------------------------------------" -ForegroundColor Yellow
        Write-Warning "Error in sqlcmd" $sqlCmd
        Write-Warning $_.Exception.Message
    }

Saturday, May 13, 2017

configure raspi raspberry pi noobs raspian statisch Ip

Grundlegendes

1) change password: passwd
2) enable wifi by clicking on wifi icon top right
3) enable ssh and 1wire by menu/preferances/interfaces

static statische IP:

/etc/network/interfaces:


# Ethernet
auto eth0
allow-hotplug eth0
iface eth0 inet static
address 192.168.1.2
netmask 255.255.255.0
gateway 192.168.1.1

dns-nameservers 192.168.1.1

/etc/dhcpcd.conf


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

Zusatz Pakete

update source lists (fetch): sudo apt-get update
bringt alle pakete auf neuersten stand: sudo apt-get upgrade

sudo apt-get install git
git clone https://github.com/...raspi.git
chmod 744 allgemein/install.sh
7 rwx
4 r

xrdp (remote desktop)
apache2 -y (apache)
round robin Db (messwerte speichern): sudo apt-get install rrdtool python-rrdtool
mysql-server mysql-client
php
php-mysql phpmyadmin


emailserver citadelle

sudo modprobe ipv6
sudo apt-get install citadel-suite

internen webserver starten mit webcit, lauscht auf port 2000

http://www.pc-magazin.de/ratgeber/raspberry-pi-als-mailserver-einrichten-installieren-1836244.html