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

Thursday, April 27, 2017

wpf datagrid simple bind

<Window x:Class="ldapTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ldapTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
        <StackPanel>
            <DataGrid Name="grid1"></DataGrid>
        </StackPanel>
</Window>


        public MainWindow()
        {
            InitializeComponent();
            grid1.ItemsSource = new ObservableCollection<MyData>()
                                    {
                                        new MyData("x@y.z", "my1"),
                                        new MyData("m2@a.b","my2")
                                    };
           
        }


        public class MyData
        {
            public string Email { get; set; }
            public string Name { get; set; }

            public MyData(string email, string name)
            {
                Email = email;
                Name = name;
            }
        }

Wednesday, April 26, 2017

ldap basics

aus https://de.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol:

" Ein einzelnes Objekt wird eindeutig durch den Distinguished Name (DN) identifiziert, wie zum Beispiel uid=juser,ou=People,ou=webdesign,c=de,o=acme. Dieser setzt sich aus einzelnen Relative Distinguished Names (RDN) zusammen. Eine andere Schreibweise für den DN ist der canonical name, der keine Attribut-Tags wie ou oder c enthält und bei dem die Trennung zwischen den RDNs durch Schrägstriche erfolgt. Außerdem beginnt die Reihenfolge, im Gegensatz zum dn, mit dem obersten Eintrag, also zum Beispiel acme/de/webdesign/People/juser."





down voteaccepted
  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component
  • O = Organiszation

Tuesday, April 25, 2017

ldap query c#

using public ldap test server:

            DirectoryEntry rootEntry = new DirectoryEntry("LDAP://ldap.forumsys.com/cn=read-only-admin,dc=example,dc=com");
            rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
            DirectorySearcher searcher = new DirectorySearcher(rootEntry);
            var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
            //TODO searcher.Filter = string.Format(queryFormat, "michael");
            foreach (SearchResult result in searcher.FindAll())
            {
                Console.WriteLine("account name: {0}", result.Properties["samaccountname"].Count > 0 ? result.Properties["samaccountname"][0] : string.Empty);
                Console.WriteLine("common name: {0}", result.Properties["cn"].Count > 0 ? result.Properties["cn"][0] : string.Empty);
            }


read all props:
            var rootEntry = new DirectoryEntry("LDAP://ldap.forumsys.com/cn=read-only-admin,dc=example,dc=com");
            rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
            var searcher = new DirectorySearcher(rootEntry);
            //var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
            //TODO searcher.Filter = string.Format(queryFormat, "michael");
            foreach (SearchResult result in searcher.FindAll())
            {
                foreach (var propertyName in result.Properties.PropertyNames)
                {
                    StringBuilder sb = new StringBuilder();
                    string sPropName = propertyName?.ToString();
                    if (!string.IsNullOrEmpty(sPropName))
                    {
                        sb.Append(sPropName + ":");
                        var vals = result.Properties[sPropName];
                        foreach (var val in vals)
                        {
                            sb.Append(val);
                        }

                        Console.WriteLine(sb);
                    }

                }
                Console.WriteLine("-------------------------------------------------------");
            }

Wednesday, April 19, 2017

c# format Timespan

string s = String.Format("{0} {1:00}:{2:00}:{3:00}", ts.Days, ts.Hours, ts.Minutes, ts.Seconds);

linux rasperry pi rrdtool

erzeuge rrd db beispiel:


echo "Erzeuge rrd Datenbank fuer 3 Werte (Temp, Luftdruck und Höhe), 100 Tage aufbewahrung viertelstuendlicher AVG  100 Jahre aufbewahrung min /max / avg"

#step 900 sec (60*15=900) alle viiertelstunden
#DS Datasource:name:GAUGE:heartbeat 20min=1200sec:min::max
#RRA RoundRobinArchive alle 9600 Zeilen (pro Tag 96 Zeilen (=24*4)
# 100 Jahre aufbewahrung min, max, AVG

rrdtool create bmp.rrd --step 900 \
DS:t0:GAUGE:1200:-50:200 \
DS:t1:GAUGE:1200:-50:200 \
DS:t2:GAUGE:1200:-50:200 \
RRA:AVERAGE:0.5:1:9600 \
RRA:MIN:0.5:96:36000 \
RRA:MAX:0.5:96:36000 \
RRA:AVERAGE:0.5:96:36000




zeige letzten eintrag in db an:

rrdtool  lastupdate bmp.rrd

https://www.epochconverter.com/ rechnet unix timestamp in datum/zeit um

erzeuge Graph


rrdtool graph tempweek.png \
  -s 'now - 1 week' -e 'now' \
  DEF:temp0=temperature.rrd:temp0:AVERAGE \
  LINE2:temp0#00FF00:Innen \
  DEF:temp1=temperature.rrd:temp1:AVERAGE \
  LINE2:temp1#0000FF:Außen

rrdtool graph temperaturDay.png \
  -s 'now - 1 day' -e 'now' \
  DEF:temp0=temperature.rrd:temp0:AVERAGE \
  LINE2:temp0#00FF00:Innen \
  DEF:temp1=temperature.rrd:temp1:AVERAGE \
  LINE2:temp1#0000FF:Außen

Sunday, April 16, 2017

webserver iis leerlaufzeit (idle time) anwendungspool

in erweiterte eigenschaften des anwendungspoll läßt sich die webserver iis leerlaufzeit (idle time) einstellen, damit eine webseite schneller reagiert (nicht so lange zum Laden braucht) nachdem sie längere Zeit nicht genutzt wurde

Tuesday, April 11, 2017

git basics

basic workflow

Get bzw Checkout - from server to local repro

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

git clone https://github.com/username/reproname.git localDirName //get repro
git status //show changes
git log  //show last commits
git cherry -v //show commits needed to push

git fetch
git pull

anzeigen orgiginal url
git remote -v oder git config --get remote.origin.url.

push / checkin - from local to server

git add -A //stage changes

git commit -m "message"
ändern:
git commit --amend
git commit --amend -m "New commit message"
revert initial commit: git update-ref -d HEAD
git push

Revert

git checkout Dateiname

Stash

git stash list
git stash
git stash drop 1

Branches

switch to branch: git checkout branchname

https://git-scm.com/book/de/v1/Git-Branching-Einfaches-Branching-und-Merging

list all: git branch -a
list local: git branch -r
create: git branch myNewBranchName



merge:
git checkout destinationBranch (eg. master)
git merge branch (e.g. hotfix)
git branch -d hotfix //löschen

rebase:
git rebase -i HEAD~2

letzte 2 commits zusammenführen, es öffnet sich Editor, squash vor den commit schreiben den man "entfernen" will


Special

suda apt-get install git
git init --bare

git init
git remote -v
git remote add 




Git Atlassian Source Tree Basics

shows all commits in one timeline

get: clone / new (from server to local repro and files)
commit => files to local repro
push => from local repro to server


Wednesday, April 05, 2017

javascript basics

display hello msg:
<button onclick="alert('Hallo!')" >Hallo </button>

Monday, April 03, 2017

update Asp.Net USer Db

doesn't help:

ALTER TABLE [dbo].[AspNetUsers] add [Email] [nvarchar](256) NULL
ALTER TABLE [dbo].[AspNetUsers] add [EmailConfirmed] [bit] NOT NULL DEFAULT (0)
ALTER TABLE [dbo].[AspNetUsers] add [PhoneNumber] [nvarchar](max) NULL
ALTER TABLE [dbo].[AspNetUsers] add [PhoneNumberConfirmed] [bit] NOT NULL DEFAULT (0)
ALTER TABLE [dbo].[AspNetUsers] add [TwoFactorEnabled] [bit] NOT NULL DEFAULT (0)
ALTER TABLE [dbo].[AspNetUsers] add [LockoutEndDateUtc] [datetime] NULL
ALTER TABLE [dbo].[AspNetUsers] add [LockoutEnabled] [bit] NOT NULL DEFAULT (0)
ALTER TABLE [dbo].[AspNetUsers] add [AccessFailedCount] [int] NOT NULL DEFAULT (0)


f

Saturday, April 01, 2017

enable telnet

dism /online /Enable-Feature /FeatureName:TelnetClient

register wcf asp.net on iis

before: ASPNET_REGIIS /I
now: dism /online /enable-feature /featurename:IIS-ASPNET45 /all


Friday, March 31, 2017

Web Projects in Visual Studio 2015

have moved from new projects to File / New Web Site

x86 or x64 - DUMPBIN dllname.dll /Headers

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64_x86

Monday, March 27, 2017

bat datei log date time

echo Begin >ExecAnalyticsDataReportingLog.txt
Date /T >>ExecAnalyticsDataReportingLog.txt
TIME /T >>ExecAnalyticsDataReportingLog.txt
sqlcmd -S localhost\sqlexpress -D StpDb -Q "exec mySP"
echo Finish >>ExecAnalyticsDataReportingLog.txt
Date /T >>ExecAnalyticsDataReportingLog.txt
TIME /T >>ExecAnalyticsDataReportingLog.txt

Tuesday, March 21, 2017

osmc samba (linux)

prüfen ob installiert:
ps -ef |grep smb
sollte eine oder mehre zeile mit /usr/sbin/smbd liefern


install:
sudo apt-get install samba

adduser peter
smbpasswd -a peter


/etc/smb.conf

[freigabename]
path = /srv/data
wrtiteable = yes
valid users = peter



neustart:
sudo systemctl restart smbd.service



https://wiki.ubuntuusers.de/Samba_Server/

sudo smbpasswd -a <username> # Fügt den Benutzer <username> der Samba Datenbank hinzu und aktiviert diesen
sudo smbpasswd -x <username> # Entfernt den Benutzer <username> aus der Samba Datenbank
sudo smbpasswd -d <username> # Deaktiviert den Benutzer <username> in der Datenbank
sudo smbpasswd -e <username> # Aktiviert den vorher deaktivierten Benutzer <username> in der Datenbank wieder 


Wednesday, March 15, 2017

signing assembly strong name / signtool

A) STRONG NAME

1) you need SDK Tool SN:
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\sn.exe

2) create key file:
sn -k StrongNameKeyFile.snk

3) sign the assembly in Visual Studio
in VisualStudio open Project Properties,
Signing,
Sign the assembly and choose the StrongNameKeyFile.snk from (2)

4) check if assembly is strong named:
sn -v assembly name
=> output ....exe stellt keine Assembly mit einem starken Namen dar.
oder
=> output Die Assembly "....exe" ist gültig

readmore:
https://www.linkedin.com/pulse/code-signing-visual-studio-jason-brower

B) SIGNTOOL

C:\Program Files (x86)\Windows Kits\10\bin\x64

/a automatically selects the code signing certificate with the longest valid date:
signtool sign /a yourApp.exe 
=> output Done Adding Additional Store 
Succeddfully signed: yourapp.exe

=> there is a new Tab in Windows File Properties named "Digital Certificates" which shows the cert owner

buildtarget and BadImageFormatException

http://stackoverflow.com/questions/5229768/c-sharp-compiling-for-32-64-bit-or-for-any-cpu


On a 32-bit machine:

  • Any CPU: runs as a 32-bit process, can load Any CPU and x86 assemblies, will get BadImageFormatException if it tries to load an x64 assembly.
  • x86: same as Any CPU.
  • x64BadImageFormatException always.

On a 64-bit machine:

  • Any CPU: runs as a 64-bit process, can load Any CPU and x64 assemblies, will get BadImageFormatException if it tries to load an x86 assembly.
  • x86: runs as a 32-bit process, can load Any CPU and x86 assemblies, will get BadImageFormatException if it tries to load an x64 assembly.
  • x64: same as Any CPU.
It is the JIT compiler that generates an assembly code that's compatible with the requested target based on this flag.

Tuesday, March 14, 2017

code signing certificate

StartCom:
easy: upload documents, wait 1 day for validation
comodo (and resellers): have to go to notary and send letter to usa

Saturday, March 11, 2017

UEFI New Boot drive


https://forum.acronis.com/forum/25975

On a Dell Latitude I had to go into the BIOS settings under boot sequence. Then under the UEFI settings it will show the Windows Boot for the old hard drive. It seems to be tied to the serial of the drive. If you click on add new, it will populate with the cloned drive serial, you simply just give it a name (I called it Windows New) and copy the boot location from the existing entry (bottom line). The EFI files it needs to boot with are stored in a hidden partition on the drive (which also much be cloned) - this is what you are pointing to.

Thursday, March 09, 2017

certificates / Zertifikate basics

Zertifikat anzeigen im Browser:

Chrome

drei Punkte Menü ganz rechts, unteres Drittel weitere Tools, Entwickler => Security Tab (fentesr etwas breiter machen damit Security Tab sichtbar wird)

Klassen

Class 1 for individuals, intended for email.
Class 2 for organizations, for which proof of identity is required.
Class 3 for servers and software signing, for which independent verification and checking of identity and authority is done by the issuing certificate authority.
Class 4 for online business transactions between companies.
Class 5 for private organizations or governmental security.

Formate:


  • .csr This is a Certificate Signing Request. Some applications can generate these for submission to certificate-authorities. The actual format is PKCS10 which is defined in RFC 2986. It includes some/all of the key details of the requested certificate such as subject, organization, state, whatnot, as well as the public key of the certificate to get signed. These get signed by the CA and a certificate is returned. The returned certificate is the public certificate (which includes the public key but not the private key), which itself can be in a couple of formats.
  • .pem Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys.
  • .key This is a PEM formatted file containing just the private-key of a specific certificate and is merely a conventional name and not a standardized one. In Apache installs, this frequently resides in /etc/ssl/private. The rights on these files are very important, and some programs will refuse to load these certificates if they are set wrong.
  • .pkcs12 .pfx .p12 Originally defined by RSA in the Public-Key Cryptography Standards, the "12" variant was enhanced by Microsoft. This is a passworded container format that contains both public and private certificate pairs. Unlike .pem files, this container is fully encrypted. Openssl can turn this into a .pem file with both public and private keys: openssl pkcs12 -in file-to-convert.p12 -out converted-file.pem -nodes
A few other formats that show up from time to time:
  • .der A way to encode ASN.1 syntax in binary, a .pem file is just a Base64 encoded .der file. OpenSSL can convert these to .pem (openssl x509 -inform der -in to-convert.der -out converted.pem). Windows sees these as Certificate files. By default, Windows will export certificates as .DER formatted files with a different extension. Like...
  • .cert .cer .crt A .pem (or rarely .der) formatted file with a different extension, one that is recognized by Windows Explorer as a certificate, which .pem is not.
  • .p7b Defined in RFC 2315, this is a format used by windows for certificate interchange. Java understands these natively. Unlike .pem style certificates, this format has a defined way to include certification-path certificates.
  • .crl A certificate revocation list. Certificate Authorities produce these as a way to de-authorize certificates before expiration. You can sometimes download them from CA websites.

In summary, there are four different ways to present certificates and their components:
  • PEM Governed by RFCs, it's used preferentially by open-source software. It can have a variety of extensions (.pem, .key, .cer, .cert, more)
  • PKCS7 An open standard used by Java and supported by Windows. Does not contain private key material.
  • PKCS12 A private standard that provides enhanced security versus the plain-text PEM format. This can contain private key material. It's used preferentially by Windows systems, and can be freely converted to PEM format through use of openssl.
  • DER The parent format of PEM. It's useful to think of it as a binary version of the base64-encoded PEM file. Not routinely used by much outside of Windows.

pem, crt 

pem ist standardformat vieler ssl tools (z.b. openssl)

-----BEGIN CERTIFICATE-----
base64code
-----END CERTIFICATE-----

crt kann in cer mittels windows zertifikats assistent umgewandelt werden (2.Tab Datei erstellen)

cer

kann entweder base64 oder binär DER codiert sein:
base 64 encoded X.509
-----BEGIN CERTIFICATE-----
base64code
-----END CERTIFICATE-----

der codiert binär X.509
unlesbar

Tools

microsoft:

signtool (C:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe)
certutil (C:\WINDOWS\system32\certutil.exe  )

java

keytool (C:\Program Files\Java\jdk1.8.0_131\bin\keytool.exe)
signing: java -jar jsign-2.0.jar  ( https://ebourg.github.io/jsign/ )

Code Signing


http://stackoverflow.com/questions/3580349/code-signing-microsoft-authenticode

Tools

  • signtool.exe - the code signing tool (C:\Program Files (x86)\Windows Kits\10\bin\x64 )
  • makecert.exe - creates a digital certificate
  • cert2spc.exe - converts a digital certificate into the Software Publisher Certificate (code signing) format
  • pvk2pfx.exe - imports the private key and software publisher certificate into the .pfx file format required by signtool.exe.

how to check if a cert is a code signing cert:

look at the purpose: should be
Ensure software cam from software publisher
...