before: ASPNET_REGIIS /I
now: dism /online /enable-feature /featurename:IIS-ASPNET45 /all
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
Saturday, April 01, 2017
Friday, March 31, 2017
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
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:
ps -ef |grep smb
sollte eine oder mehre zeile mit /usr/sbin/smbd liefern
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:
/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
=> 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
BadImageFormatExceptionif it tries to load an x64 assembly. - x86: same as Any CPU.
- x64:
BadImageFormatExceptionalways.
On a 64-bit machine:
- Any CPU: runs as a 64-bit process, can load Any CPU and x64 assemblies, will get
BadImageFormatExceptionif it tries to load an x86 assembly. - x86: runs as a 32-bit process, can load Any CPU and x86 assemblies, will get
BadImageFormatExceptionif 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
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)
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 beEnsure 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
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
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
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)
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()
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
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
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);
}
/// <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
//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
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");
}
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); });
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();
}
}
}
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.
namespace wcf3
{
class Program
{
static void Main(string[] args)
{
ServiceHost serviceHost = new ServiceHost(typeof(
// Create Meta Behavior
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
serviceHost.Description.
Binding mexBinding = MetadataExchangeBindings.
serviceHost.
WSHttpBinding httpBinding = new WSHttpBinding(SecurityMode.
serviceHost.
serviceHost.Open();
Console.WriteLine("TestService is now running. at: " + serviceHost.BaseAddresses.
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
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
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 all2) 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 FILETABLEWITH
(
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_BLOB) AS 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 !
or
INSERT INTO [dbo].[FileTableTb] ([name],[file_stream])SELECT'NewFile.txt', * FROM OPENROWSET(BULK N'd:\NewFile.txt', SINGLE_BLOB) AS 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
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
FileTableRootPath('TestFileTable')+file_stream.GetFileNamespacePath() as AbsPath from TestFileTable
Sql Server Filestream using C#
1) WRITE
using (TransactionScope transactionScope = new TransactionScope()){
//1. create Record with Empty Blob (File)
SqlConnection sqlConnection1 = new SqlConnection(conStr);
sqlConnection1.Open();
SqlCommand sqlCommand1 = sqlConnection1.CreateCommand();
sqlCommand1.CommandText = @"DECLARE @Out TABLE (ID uniqueidentifier)
Insert Into Blob2(Blob) output inserted.ID into @Out values(Cast('' As varbinary(Max)))
Select BLOB.PathName() As Path From BLOB2 Where Id =(SELECT id FROM @Out)";
string filePath1 = (string) sqlCommand1.ExecuteScalar();
//2. Get SqlFileStream to empty File createt in Step 1
SqlConnection sqlConnection2 = new SqlConnection(conStr);
sqlConnection2.Open();
SqlCommand sqlCommand2 = sqlConnection2.CreateCommand();
sqlCommand2.CommandText = "Select GET_FILESTREAM_TRANSACTION_CONTEXT() As TransactionContext ";
byte[] transactionContext1 = (byte[]) sqlCommand2.ExecuteScalar();
//3. Write Data into Stream and Close
SqlFileStream sqlFileStream1 = new SqlFileStream(filePath1, transactionContext1, FileAccess.Write);
byte[] fileData = Encoding.ASCII.GetBytes(nameof(AdoFileStreamTest)+" "+DateTime.Now);
sqlFileStream1.Write(fileData, 0, fileData.Length);
sqlFileStream1.Close();
transactionScope.Complete();
}
2) READ
using (TransactionScope transactionScope2 = new TransactionScope())
{
SqlConnection sqlConnection3 = new SqlConnection(conStr);
sqlConnection3.Open();
//1. Get Path & Transaction Scope
SqlCommand sqlCommand3 = sqlConnection3.CreateCommand();
sqlCommand3.CommandText = @"Select Top 1 Blob.PathName() As Path,
GET_FILESTREAM_TRANSACTION_CONTEXT() As TransactionContext
From Blob2 Order by Created desc";
SqlDataReader reader = sqlCommand3.ExecuteReader();
reader.Read();
string filePath = (string)reader["Path"];
byte[] transactionContext2 = (byte[])reader["TransactionContext"];
//2. read file
SqlFileStream sqlFileStream2 = new SqlFileStream(filePath, transactionContext2, FileAccess.Read);
byte[] data = new byte[sqlFileStream2.Length];
sqlFileStream2.Read(data, 0, Convert.ToInt16(sqlFileStream2.Length));
res = Encoding.ASCII.GetString(data);
sqlFileStream2.Close();
}
3) maybe need to config Distributet Transaction Manager:
down voteaccepted
|
To enable MSDTC on the business management server that is running on Windows Server 2008 click Start, Run, type
dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, and click to expand Distributed Transaction Coordinator.
Right click Local DTC, and click Properties to display the Local DTC Properties dialog box.
Switch to the Security tab.
In the Security Settings section, click Network DTC Access.
In the Client and Administration section, select Allow Remote Clients and Allow Remote Administration.
In the Transaction Manager Communication section, select Allow Inbound and Allow Outbound.
In the Transaction Manager Communication section, select Mutual Authentication Required (if all remote machines are running Windows Server 2003 SP1 or Windows XP SP2 or higher), select Incoming Caller Authentication Required (if running MSDTC in a cluster), or select No Authentication Required if some of the remote machines are pre-Windows Server 2003 SP1 or pre-Windows XP SP2. No Authentication Required is the recommended selection. Select Enable XA Transactions, and then click OK.
|
Monday, October 17, 2016
Entity Framework no InsertFunction element exists
because it has a DefiningQuery and no InsertFunction element exists in the ModificationFunctionMapping element
most likly: No primary key defined => EF treats Table as view and generates read only code
I had to remove the DefiningQuery Element in the .edmx File and also I removed the store:
like described here:
Ef Entity Framework and Filestream
public void WriteAndReadFileTest()
{
var _ctx = new testFileStreamEntities();
//Write
var sw = Stopwatch.StartNew();
string writeString = "Hallo wie gehts ? "+DateTime.Now;
var writeBlobRec = new BLOB2();
writeBlobRec.BLOB = Encoding.ASCII.GetBytes(writeString);
writeBlobRec.ID = Guid.NewGuid();
_ctx.BLOB2.Add(writeBlobRec);
_ctx.SaveChanges();
sw.Stop();
Debug.WriteLine($"Writing took {sw.ElapsedMilliseconds}ms");
//Read
sw.Restart();
var blobRec = _ctx.BLOB2.FirstOrDefault(x => x.ID==writeBlobRec.ID);
string readString = Encoding.ASCII.GetString(blobRec.BLOB);
sw.Stop();
Debug.WriteLine($"reading took {sw.ElapsedMilliseconds}ms for {readString}");
}
Thursday, October 06, 2016
Mehr als eine RemoteDesktop Sitzung unter Windows 10 / more than one Remote Desktop (RDP) session on Windows 10
http://woshub.com/how-to-allow-multiple-rdp-sessions-in-windows-10/
buildnr = ver sion = Name Windows 10 Versionen ( Type ver in commandshell to get buildnr)
10.0.10240 = 1507 = first Windows 10 Version (Threshold1)
10.0.10586 = 1511 = November Update
10.0.14393 = 1607 = Aniversary Update
Subscribe to:
Posts (Atom)
