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();
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, March 05, 2018
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"
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:
{
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" />
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
session: wenn sie abläuft sind die daten weg
application: wenn recycled weg
viewstate: wird auf client seite gespeichert
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
"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!" /IAcceptSQLServerLicenseTermswith 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!" /IAcceptSQLServerLicenseTermswith 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});
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");
}
});
{
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);
Wednesday, August 16, 2017
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
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
- 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
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;
}
{
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();
}
{
// 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);
}
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);
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++; });
var a2 = new Action
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
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
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)
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!";
#!/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
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
sn -T assemblyname
then use it to reference assambly:
Assembly=assemblyname, Version=1.0.0.0, publicKeyToken=7e3e8edbbbdbe145, Culture=neutral
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
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
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"
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 project2) 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 ! -------------------
10>
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.
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
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 servernameEXEC sp_DROPSERVER 'oldservername'EXEC sp_ADDSERVER 'newservername', 'local'restart serverimportant 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
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
/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)
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
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
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: passwd2) 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
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)
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-rrdtoolmysql-server mysql-client
php
php-mysql phpmyadmin
emailserver citadelle
sudo modprobe ipv6sudo 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;
}
}
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."
" 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."
|
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("-------------------------------------------------------");
}
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.rrdhttps://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 //listgit 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 changesgit 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
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
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
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
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)
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
register wcf asp.net on iis
before: ASPNET_REGIIS /I
now: dism /online /enable-feature /featurename:IIS-ASPNET45 /all
now: dism /online /enable-feature /featurename:IIS-ASPNET45 /all
Subscribe to:
Posts (Atom)

