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
...

Saturday, March 04, 2017

azure sql db create login and user

CREATE LOGIN my20170403  WITH PASSWORD='pwd1'
alter login my20170403  ENABLE
alter login my20170403  WITH PASSWORD='mypwd'
alter login my20170403 WITH DEFAULT_DATABASE = mydb

create user my20170403 for login my20170403 with default_schema = [dbo]

to connect with sql management studio
also needs user in master database - because deafult database not there

Wednesday, March 01, 2017

address denied exception wcf

Fehlermeldung:
HTTP konnte URL ... nicht registrieren. Der Prozess weist keine Zugriffsrechte für diesen Namepsace auf

allow using the adress / port  with netsh:

for example http:
netsh http add urlacl url=http://+:port/ user=DOMAIN\UserName


Tuesday, February 14, 2017

vstest.console.exe SettingsFile Example for Test Parameters



<RunSettings>
  <!-- Parameters used by tests at runtime -->
  <TestRunParameters>
    <Parameter name="webAppUrl" value="http://localhost" />
    <Parameter name="webAppUserName" value="Admin" />
    <Parameter name="webAppPassword" value="Password" />
  </TestRunParameters>

</RunSettings>

Testclassfile.cs:

    [TestClass]
    public class NoDbTests
    {

        private static string _param1="";

        [ClassInitialize]
        public static void TestClassinitialize(TestContext context)
        {
            _param1 = context.Properties["webAppUrl"]?.ToString();
            Trace.Write("_param1=" +_param1);

            //other settings etc..then use your test settings parameters here...
        }
        /// <summary>tests parameter from runsettings.xml file
        /// vstest.console.exe .\isiQiri.Server.Tests.dll /Tests:RunSettingsTest /Settings:runsettings.xml
        /// </summary>
        [TestMethod]
        public void RunSettingsTest()
        {
            Trace.Write("_param1=" + _param1);
            Assert.AreEqual(_param1, "http://localhost");
        }
}

Test with:
vstest.console.exe .\isiQiri.Server.Tests.dll /Tests:RunSettingsTest /Settings:runsettings.xml

Thursday, February 09, 2017

sssr custom code functions for timestamp, finding max in a row

  Public Function Ms2Str(ms As Int64) As String
        Dim ts As TimeSpan = TimeSpan.FromMilliseconds(ms)
        Dim s As String = String.Format("{0} {1:00}:{2:00}:{3:00}",ts.Days,ts.Hours,ts.Minutes,ts.Seconds)
        Return s
  End Function


    Public Function Sec2Str(sec As Double) As String
        Dim ts As TimeSpan = TimeSpan.FromSeconds(sec)
        Dim s As String = String.Format("{0} {1:00}:{2:00}:{3:00}",ts.Days,ts.Hours,ts.Minutes,ts.Seconds)
        Return s
    End Function

public Function MaxColor(ri as ReportItems, rowNr as integer, colNr as integer, defaultColor as string)

        '1. get value of this cell
        Dim cellName as String
        cellName="c"+rowNr.ToString() +colNr.ToString()
        Dim maxVal=ri(cellName).Value

        '2. check if any other cell has bigger value
        For i As Integer = 0 To 9
            cellName="c"+rowNr.ToString() +i.ToString()
            Dim compare=ri(cellname).Value
            If compare>maxVal Then Return defaultColor   'self not bigger then self
        Next
        '3. No one was bigger => is biggest or equal
        return "LimeGreen"

end Function

.net Formating Timespans

Date Format strings don't work on timespans => have to to it myself

        Dim ts As TimeSpan = New TimeSpan(0,3,5)
        Dim s As String = String.Format("{0} {1:00}:{2:00}:{3:00}", ts.Days, ts.Hours, ts.Minutes, ts.Seconds)

Wednesday, February 08, 2017

ssrs custom code

Report Properties Code:

public Function Test() as integer
return 3
end Function


in a Textbox:
=Code.Test()

Wednesday, January 25, 2017

sql server commandline tool sqlcmd (shell)

display simple query with windows authenticartion (current user should have rights):

sqlcmd -S localhost\sqlexpress -d master -q "select * from sys.tables"

S... server
d ... database
q...query (use -Q to terminate / close  sqlcmd after query execution)

u...user
p...pwd

Thursday, January 05, 2017

EF Migrations Start Debugger



            if (System.Diagnostics.Debugger.IsAttached == false)
            {
                System.Diagnostics.Debugger.Launch();
            }

Tuesday, December 27, 2016

windows mobile 10 handy neuer account

Einstellungen -> System - info handy zurücksetzten



Tuesday, December 20, 2016

ef migrate to specific version per code c#

add this method to your context:

        /// <summary>migrates actual Database to given Migration Version
        /// </summary>
        /// <param name="toMigration">"0" ... Version 0 (remove all), "" is newest Version</param>
        public void Migrate(string toMigration)
        {
            var configuration = new Configuration
            {
                TargetDatabase = new DbConnectionInfo(Database.Connection.ConnectionString, "System.Data.SqlClient")
            };

            var migrator = new DbMigrator(configuration);
            migrator.Update(toMigration);
        }

Wednesday, December 14, 2016

TSQL BACKUP OPTIONS

                //COPY_ONLY ... doesn't interrupt TransactionLogBackupCycle
                //STATS ... percent after status is updated
                //NOINIT+SKIP: doesnt't delete old Backups in same file
                //TAPE OPTIONS:
                //NOUNLOAD/NOREWIND: doesn't unload / rewind the tape after backup
                //NOFORMAT (=DEFAULT): doesn't delete old Backups in same file

Tuesday, November 29, 2016

regex Visual Studio search and replace

surround with (), display capture with $1, $2, $n

eg.:

search:  CreateColumnDefinition\(\"(\w*)\",
replace: CreateColumnDefinition("$1", 1,

[ab] only ab
[^ab] everything but ab

 

 

regex Visual Studio search and replace

surround with (), display capture with $1, $2, $n

eg.:

search:  CreateColumnDefinition\(\"(\w*)\",
replace: CreateColumnDefinition("$1", 1,

[ab] only ab
[^ab] everything but ab

Saturday, November 26, 2016

Winform jump back to gui thread with invoke

                PLog.LogInfo($"Thread:{Thread.CurrentThread.ManagedThreadId} Gui");
                Task t = new Task(() =>
                {
                    PLog.LogInfo($"Thread:{Thread.CurrentThread.ManagedThreadId} Background");
                    tableAdapter.FillByKundeId(dtBackground, _kundenId);
                    var delegateCallBack = new Action(LoadDataCallBack);
                    this.Invoke(delegateCallBack); //start Callback on Gui Thread
                });
                t.Start();
            }
        }

        private void LoadDataCallBack()
        {
            PLog.LogInfo($"Thread:{Thread.CurrentThread.ManagedThreadId} Callback");
           
        }

Friday, November 25, 2016

c# background thread / hintergrund thread

before .Net 4.0:

            // init backgroundworker
            _worker = new BackgroundWorker();
            _worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
            _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);



in .Net 4.0 TPL:

Task Paralell Library nützt Mehrkern Prozessoren besser.
wichtigste Klassen: Task<TResult> und Paralell

            Task copyMedia = new Task(CopyMedia,TaskCreationOptions.LongRunning);
            copyMedia.Start();

task returning int:
Task<int> t = new Task<int>(() => { return tableAdapter.FillByKundeId(datatable, _kundenId); });

.Net 4.5

IAsyncResult und AsyncCallback ersetzt durch keywords async und await


public Form1()
{
    InitializeComponent();

    StartAsync();
}

private async void StartAsync()
{
    // do some work
    await Task.Run(() => { Thread.Sleep(1000); });

    // start more work
    var moreWork = Task.Run(() => { Thread.Sleep(1000); });

    // update the UI, based on data from “some work”
    textBox1.Text = "From async method";

    // wait until “more work” finishes
    await moreWork;
}

Tuesday, November 15, 2016

WCF Service Host without app.config (configuration by code) example

using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;


namespace wcf3
{
    class Program
    {
        static void Main(string[] args)
        {

            ServiceHost serviceHost = new ServiceHost(typeof(TestService), new Uri("http://localhost:80/Test3"));

            // Create Meta Behavior
            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
            behavior.HttpGetEnabled = true;

            serviceHost.Description.Behaviors.Add(behavior);

            Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();

            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

            WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.None);

            serviceHost.AddServiceEndpoint(typeof(ITestService), httpBinding, "rest");

            serviceHost.Open();
            Console.WriteLine("TestService is now running. at: " + serviceHost.BaseAddresses.First());
            Console.WriteLine("Press any key to stop it ...");
            Console.ReadKey();
            serviceHost.Close();
        }
    }

    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        string Test(string input);
    }

    public class TestService : ITestService
    {

        public string Test(string input)
        {
            return input + DateTime.Now.ToString();
        }
    }



}

Monday, November 14, 2016

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\WcfTestClient.exe

WcfTestClient.exe 
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

System.ServiceModel.AddressAccessDeniedException

netsh http add urlacl url=http://+:8080/MyUri user=DOMAIN\user

Thursday, November 10, 2016

WCF Client without config file

Example 1: NetTcp

var endPoint = new EndpointAddress("net.tcp://localhost:8080/MyService");
var binding = new NetTcpBinding();
var sbNewClient = new SbNew.ShiftbookServiceClient(binding, endPoint);

Example2: custom http

            CustomBinding cb= new CustomBinding();
            SecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
            sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
            sbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            sbe.IncludeTimestamp = false;
            sbe.SetKeyDerivation(true);
            sbe.KeyEntropyMode = System.ServiceModel.Security.SecurityKeyEntropyMode.ServerEntropy;
            cb.Elements.Add(sbe);
            cb.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, System.Text.Encoding.UTF8));
            cb.Elements.Add(new HttpsTransportBindingElement());
            EndpointAddress endPoint = new EndpointAddress("net.tcp://localhost:8080/MyService");

            var sbNewClient = new Service1.ServiceClient(cb,endPoint);

Friday, November 04, 2016

WCF BASICS 2

1) ServiceContract & Implementation

you need a contract  (=Interface with     [ServiceContract] Attribute) like

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

which contains Methods attributed with [OperationContract]

implement the [ServiceContract] Interface:

    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

assume its in namespace WcfServiceLib for hosting below

2) Host the ServiceContract

2a) with IIS

you need a .svc file with one single line:
<%@ServiceHost Service="WcfServiceLib.Service1"%>

and configure the service (provide metadata) within the web.config:


    <system.serviceModel>
      <behaviors>
        <serviceBehaviors>
          <behavior name="MyServiceTypeBehaviors">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="false" />
          </behavior>
        </serviceBehaviors>
      </behaviors>
        <service name="WcfServiceLib.Service1"      behaviorConfiguration="MyServiceTypeBehaviors">
          <endpoint address="" binding="wsHttpBinding"
               contract="WcfServiceLib.IService1"/>
          <endpoint contract="IMetadataExchange"
             binding="mexHttpBinding" address="mex"/>
        </service>
      </services>
    </system.serviceModel>

2b) With .net app:

        static void Main(string[] args)
        {
            Type serviceType = typeof(MyWCFServices.HelloWorldService);

            string httpBaseAddress = ConfigurationManager.AppSettings["HTTPBaseAddress"];
            Uri[] baseAddress = new Uri[] { new Uri(httpBaseAddress) };

            ServiceHost host = new ServiceHost(serviceType, baseAddress);
            host.Open();
            Console.WriteLine("HelloWorldService is now running. at: " +host.BaseAddresses.First());
            Console.WriteLine("Press any key to stop it ...");
            Console.ReadKey();
            host.Close();
        }

Thursday, November 03, 2016

Visual Studio öffnet Fenster in falscher Tab Gruppe / opens window in wrong Tab Group

Menü / Window / Reset Window Layout

Internals in other assembly


add to AssemblyInfo.cs:
[assembly: InternalsVisibleTo("OtherAssemblyName")]

Thursday, October 20, 2016

Sql Server Filetable and Entity Framework





CREATE PROCEDURE SFilesDelete (@fId uniqueidentifier)
AS
BEGIN
SET NOCOUNT ON;
DELETE from SFiles where stream_id = @fId;  
END
GO

ALTER PROCEDURE [dbo].[SFilesInsert]
@fname nvarchar(255)
,@fData varbinary(max)
AS
BEGIN

Declare @fid uniqueidentifier = NEWID();
    INSERT INTO SFiles (stream_id, file_stream, name) VALUES (@fId ,@fdata,@fname);
    SELECT stream_id, file_stream.PathName() as unc_path FROM SFiles where stream_id = @fId
END

Entity Framework Code First Alter Database for FileTable

if (not exists (select * from sys.filegroups where name ='FStream'))
begin
declare @FilePathAndName nvarchar(4000)= (select physical_name FROM sys.master_files where database_id=db_ID() and file_id=1)
set @FilePathAndName= REPLACE(@FilePathAndName,'.mdf','_FileStream.fs')
--print @FilePathAndName
declare @sqlStr as nvarchar(max) ='alter database ' + db_name() +' ADD FILEGROUP FStream CONTAINS FILESTREAM'+CHAR(13)
set @sqlStr = @sqlStr  + 'ALTER DATABASE ' + db_name() +' ADD FILE ( NAME = N''FStream'', FILENAME = N'''+@FilePathAndName +''' ) TO FILEGROUP fStream'+CHAR(13)
set @sqlStr = @sqlStr  + 'ALTER DATABASE ' + db_name() +' SET FILESTREAM (NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'''+db_name()+'FilesDir'')'+CHAR(13)
set @sqlStr = @sqlStr + 'CREATE TABLE dbo.MyFiles AS FILETABLE WITH ( FILETABLE_DIRECTORY = ''MyFileDir'')'+CHAR(13)
print @sqlStr
exec (@SqlStr)
end

Tuesday, October 18, 2016

Sql Server Filetable (since 2012)

1.) Filestream TSQL

A) Pepare SQL Server

1) configuration Manager / SQL-Server Db Service Propteries / Filestream Tab: Check all
2) EXEC sp_configure filestream_access_level, 2  RECONFIGURE
3) restart SQL Server Service

B) Prepare DATABASE

ALTER DATABASE testFileTable SET FILESTREAM (NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'FilesDir')

alter database testFileTable  ADD FILEGROUP fsg CONTAINS FILESTREAM;
ALTER DATABASE testFileTable  ADD FILE ( NAME = N'fsf', FILENAME = N'D:\sqlData\filesteamtest\' ) TO FILEGROUP fsg;
ALTER DATABASE testFileTable  SET READ_COMMITTED_SNAPSHOT OFF WITH NO_WAIT;


C) Prepare TABLE

CREATE TABLE dbo.MyFiles AS FILETABLE
WITH
(
FILETABLE_DIRECTORY = 'MyFilesDir',
FILETABLE_COLLATE_FILENAME = database_default
)


D) Write Files

just drag them into the filetabledir - get UNC Path of it:
SELECT FileTableRootPath('TestFileTable') AS FileTableRootPath

or
INSERT INTO [dbo].[FileTableTb] ([name],[file_stream])SELECT'NewFile.txt', * FROM OPENROWSET(BULK N'd:\NewFile.txt'SINGLE_BLOBAS FileData
or
INSERT INTO [dbo].StpFile ([name],[file_stream]) SELECT 'test1.txt', CONVERT(VARBINARY(MAX),'TestFileText') AS FileData

create Dir:
INSERT INTO FileTableTb (name, is_directory)   VALUES ('testFolder', 1)

GO


create file in subdir: have to get pathlocator first:

select GetPathLocator(CONCAT(FileTableRootPath('FileTableTb'), '\testFolder')).GetDescendant(Null,NULL);

INSERT INTO [dbo].FileTableTb  ([name],[file_stream],path_locator) SELECT 'test1.txt', CONVERT(VARBINARY(MAX),'TestFileText'), GetPathLocator(CONCAT(FileTableRootPath('FileTableTb'), '\testFolder')).GetDescendant(Null,NULL) AS FileData

Parent_Path_Locator column is readonly !

E) Read Files

with Explorer - get UNC Path of filetable:
SELECT FileTableRootPath('TestFileTable') AS FileTableRootPath


physical path of filetable isn't available, this UNC Path is given by a virtual device
The Filetable stores the files like filestream in a guid structure but offers a filesystemdriver, which respresents those files in a more readable form under a UNC Path, which is available from:
SELECT FileTableRootPath('TestFileTable') AS FileTableRootPath

select stream_id, name, convert(varchar(max), file_stream) as textContent, file_stream.GetFileNamespacePath() as RelPath,
FileTableRootPath('TestFileTable')+file_stream.GetFileNamespacePath() as AbsPath from TestFileTable