Tuesday, October 18, 2016

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

Wednesday, October 05, 2016

get all resources of an assembly

Assembly a = Assembly.GetExecutingAssembly();

string[] allManifestResourceNamess = a.GetManifestResourceNames();



foreach (string resourceName in allManifestResourceNamess)


{
Trace.WriteLine(resourceName);

if (resourceName.EndsWith(".sql")) //SQL script Files


{
using (TextReader tr = new StreamReader(a.GetManifestResourceStream(resourceName)))


{
string s = tr.ReadToEnd();


}
}
else if (resourceName.EndsWith(".resources")) //real resources with key Value pairs


{
using (ResourceReader reader = new ResourceReader(a.GetManifestResourceStream(resourceName)))


{
IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())


{
string key = dict.Key as string;
object val = dict.Value;

}
}
string manifest = resourceName.Replace(".resources", string.Empty);
ResourceManager rm = new ResourceManager(manifest, a);



ResourceSet resourceSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)


{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;


}
}
}

webserver iis install webdeploy


IIS Server

start net start wmsvc

download installer:
https://technet.microsoft.com/en-us/library/dd569059(v=ws.10).aspx

then search webDeploy 3.6 (right upper Corner search field)



net start wmsvc & net start msdepsvc
the Web Managment Service must be started, Port 8172 opened
check with telnet

check with browser:
https://52.174.50.95:8172/msDeploy.axd




To diagnose installation problems, Web Deploy MSI logs are placed under %programfiles%\IIS\Microsoft Web Deploy v3

https://www.iis.net/learn/publish/troubleshooting-web-deploy/troubleshooting-common-problems-with-web-deploy

add USer to IIS Managers !!! and on site level to iis Permissions

if username is wrong or ha sno rights, it could be that error 404 (not found) instead of 401 (no rights) is returned


Visual Studio 2015

Server: Ip Adress or name of server, no http etc
SiteName: Default Web Site/test
Username: localhost\admin
pwd...
DestUrl: http://serverNameOrIp/test

test app has to exist on the server

Tuesday, October 04, 2016

IIS Webserver Anwendungs/Application Pool Timeout

wenn die Website beim ersten Aufruf lange braucht um geladen zu werden, so kann man die AppPool/erweiterte Eigenschaften / Leerlauftimeout erhöhen, z.b 1440 Minuten = 24h (60*24),
schienbar sind 1700min (28,3h) max

if webapp Needs Long to start,, you can increase appPool/ext.properties/idleTimeout eg. 1440 minutes = 24 hours. it seems that 1700 (=28,3h) is maximum

Thursday, September 29, 2016

how to install windows 10 mobile aniversary update version 1607

You can find your Version Number in:
Settings/System/info

1507 orig. Windows 10
1511 November Update
1607 Aniversary Update

1) download Windows 10 upgrade advisor (Aktualisierungsratgeber fĂĽr Windows 10)

Wednesday, September 28, 2016

c# .net Action / Func

Action ist ein delegate fĂĽr eine Methode ohne RĂĽckgabewert. Hier mit Expliziter (statt anaonymer) Methode:

Action<IBeforeChangeEntry<EntityBase>> updateAction = new Action<IBeforeChangeEntry<EntityBase>>(Trigger_Updating);
Triggers<EntityBase>.Updating += updateAction;

        private static void Trigger_Updating(IBeforeChangeEntry<EntityBase> obj)
        {
            obj.Entity.LastChanged = DateTime.Now;
            obj.Entity.Version += 1;
        }


Anonym:
            Triggers<EntityBase>.Updating += x =>
            {
                x.Entity.LastChanged = DateTime.Now;
                x.Entity.Version += 1;
            };

Tuesday, September 27, 2016

Visual Studio 2015 ASP.NET App Authentication

In VS2015 create new webform project, then a requester ask kind of Authentication and Application Type

Add a Foder LoggedInContent
add there a Web Config like:
<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

to protect all files in this folder - only authenticated users can access them
add Master Page Forms too the folder
add links from Default Page (available for everyone) to above added MasterPageSitesin LogedInContent

Wednesday, September 21, 2016

ef framework code first migrations with 2 DbContexts

enable-migrations -ContextTypeName EFTest.Model2 -MigrationsDirectory: Mig2
Add-migration -configuration EFTest.Mig2.Configuration Mig20001
update-database -configuration EFTest.Mig2.Configuration –Verbose

http://www.codeproject.com/Tips/801628/Code-First-Migration-in-Multiple-DbContext

only one context:
enable-migrations
Add-migration Mig0001
Update-Database

scripting triggers of sql server datatbase

right click on db, Tasks, generate scripts, next, advanced, table/view Options: Script Triggers = true

Monday, September 05, 2016

EF Update in Context existing Entities

there is a entity e1 in dbContext1, already loaded from database and its sent by server over WCF, changed byclient, sent back over WCF to server, its' not the same entity e1, its another object e2.
If you say Save to Context nothing is saved.
dbContext1 is the Ef Cache and should always contain the newest state of all objects


1) create a new context, attach the e2 and save it to database, update the dbContext 1 from database
2) update e1 with values (and references9 from e2, save to database with DbContext1
3) Detach e1 (set State to Detached)  and Attach e2, set e2. EnitytState to modified

Monday, August 29, 2016

visual studio 2015 performance analyse

Debug / Start Deiagnostic Tools Without Debugging
Choose CPU Usage

Look at Call with biggest Total CPU % and  TotalCPU (ms)

Thursday, August 25, 2016

Friday, August 19, 2016

log4view example / beispiels pattern

^%date{yyyy-MM-dd HH:mm:ss.ffff} |%level |%logger |%m |%exception |

Tuesday, July 05, 2016

sql server filestream

1.) Filestream TSQL

check filestream status:
SELECT * FROM sys.configurations WHERE name = 'filestream access level'

A) Pepare SQL Server

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

B) Prepare DATABASE

use testFileStream;


alter database testFileStream ADD FILEGROUP fsg CONTAINS FILESTREAM;


ALTER DATABASE testFileStream ADD FILE ( NAME = N'fsf', FILENAME = N'D:\sqlData\filesteamtest\' ) TO FILEGROUP fsg;


C) Prepare TABLE

its necesarry to have a rowguidcol:

CREATE TABLE dbo.BLOB2 
(
  ID UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL default newid() UNIQUE ,
  BLOB VARBINARY(MAX) FILESTREAM NULL
)
otherwise you get: A table that has FILESTREAM columns must have a nonnull unique column with the ROWGUIDCOL property




alter table blobs add RowID UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL default newid() UNIQUE 
alter table blobs add  [Bytes2] varbinary(max) filestream null;

alter existing Columns doesn't work:

alter table blobs alter column ID UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL default newid() UNIQUE 
alter table blobs alter column [Bytes] varbinary(max) filestream null;


D) Insert Files

 
INSERT INTO dbo.blob2 (blob)


SELECT * FROM
OPENROWSET(BULK N'd:\9bat\test.sql', SINGLE_BLOB) AS Import


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].FileTableTb ([name],[file_stream]) SELECT 'test1.txt', CONVERT(VARBINARY(MAX),'TestFileText') AS FileData

or Update Files:
update [dbo].FileTableTb set [file_stream] =(SELECT * FROM OPENROWSET(BULK N'd:\temp\test2.txt', SINGLE_BLOB) AS FileData) WHERE id=12

E) Check Result



select *, blob.PathName() from blob2;

in D:\sqlData\filesteamtest\
there are dirs named with guids (2-levels)


Monday, July 04, 2016

allowing a url

netsh http add urlacl url= http://+:51915/Server.wcfService/ user=domian\username

Sunday, June 26, 2016

win 10 november update langsam / slow

build 10240 läuft auf meinem lenovo thinkstation mit core i5 recht flott, build 10586 extrem langsam - besonders visual studio

Tuesday, June 21, 2016

windows build nummer

HKCU\Control Panel\Desktop den DWORD-Wert (32-Bit) mit dem Namen PaintDesktopVersion hinzufĂĽgen und auf 1


https://windowsblog.at/2015/07/31/howto-build-nummer-wieder-am-desktop-anzeigen/

Saturday, June 11, 2016

raspberry pi 3 windows 10 iot

windows iot download mit windows iot dashboard installieren (rasperry pi3: insider preview, custom)

ipadresse:8080 webinerface

powershell admin:
start-service winrm
set-item wsman:\localhost\client\trustedhosts -value * -force
enter-pssession -ComputerName 169.254.63.249 -Credential "169.254.63.249\Administrator"

https://www.hackster.io/
Remote "Desktop":
Windows Iot Remote Clint Universal App Insallieren, im Webinterface am Raspi links unten Remote aktivieren



Monday, May 30, 2016

citadel



list usb devices:
sudo lsusb

list devices
sudo blkid

list partitions:
sudo fdsik -l

list disks by ...:
ls -al /dev/disk/by-uuid/
ls /dev/disk/by-label/

ls /dev/sd*




apt-get install:
ntfs-3g
exfat
hdparm


list power mode of hd:
sudo hdparm -C /dev/sda

dmesg

raspberry pi fernzugriff mittels VNC

vnc server:

sudo apt-get update
sudo apt-get install x11vnc
x11vnc -usepw -forever -rfbport 12345 -display :0

startet server mit port 12345

Saturday, May 14, 2016

W10: UWP Packages auf Windows 10 Handy (Mobile) laden deployen

Visual Studio:
rechte Maustaste auf App, Store, Create Package (No Store)


Handy:
Wlan ein
Einstellungen / Update und Sicherheit / FĂĽr Entwickler / Entwicklermodus,
Gerätesuche ein
Geräteportal ein
unter Geräteportal steht Verbindung herstellen über:
WiFi
https://x.y.z.a (IpAdresse)

mit Browser auf Handy Ip (steht unter Geräteportal siehe oben) verbinden und koppeln - wichtig: Handy und PC müssen im selben Subnetz sein

in App Manager App Uploaden: ....AppxBundle

Friday, May 13, 2016

rasperry pi

LED am GPIO Pin 12 ein und ausschalten:

import Rpi.GPIO as IO
import time
OI.setmode(IO.BOARD)
IO.setp(12,IO.OUT)
state=True
while True:
  IO.output(12,state)
  state= not state
  time.sleep(1)


falls GPIO nicht vorhanden, mit apt-get installieren


Temperatursensor 
Dallas-18820 
1607C4+23AA

Wednesday, May 04, 2016

oracle can connect with sqlplus but not with sql developper / kann mit sqlplus verbinden aber nicht mit sqldeveloper

sqlplus braucht fĂĽr Verbindungen zum lokalen host unter Angabe der Sid scheinbar keinen listener:
sqlplus user/pwd@sid

fĂĽr tns jedoch schon:

splplus user/pwd@tnsName

SQL developper braucht auch einen listener zum verbidnen, wenn also sqlplus funktioniert, dann ist wahrscheinlihc der listener falsch konfiguriert (Hostanem ...)

Thursday, April 28, 2016

oracle tablespace verkleinern / resize smaller


get minimum size of files / minimalgroesse der Datei:
select f.file_name, (t.block_size*max(e.block_id)/1024/1024) MB
from dba_tablespaces t, dba_data_files f, dba_extents e
where e.tablespace_name = 'SYSAUX'
and   e.tablespace_name = f.tablespace_name
and e.tablespace_name = t.tablespace_name
group by f.file_name, t.block_size;


alter database datafile '' resize  ;

durch reorganisieren des frgamentierten Files kann die minimalgroesse herabgesetzt werden - the minimal size can be reduced by reorganicing the fragmented tablespace:

  1. get objects at end of file (first rows):
    set pagesize 3000
    set linesize 3000
    select e.file_id, max(e.block_id),
    e.owner, e.segment_name, segment_type, partition_name
    from dba_extents e
    where e.tablespace_name = 'SYSAUX'
    group by e.file_id, e.owner, e.segment_name, segment_type, partition_name
    order by 1 desc , 2 desc;
  2. reorganize object blocking end of file:
    alter table owner.tablename move;
    alter Index rebuild;
     
  3. get minimum size of file shrink:
    select f.file_name, (t.block_size*max(e.block_id)/1024/1024) MB
    from dba_tablespaces t, dba_data_files f, dba_extents e
    where e.tablespace_name = 'SYSAUX'
    and e.tablespace_name = f.tablespace_name
    and e.tablespace_name = t.tablespace_name
    group by f.file_name, t.block_size;
  4. shrink file:
    alter database datafile 'C:\ORA_DAT\myfile.DBF' resize 4500M;

Thursday, April 14, 2016

Entity Framework AddOrUpdate

funktioniert gut, solange das Objekt nicht im lokjalen Speicher vorhanden ist - dann macht die Methode nämlich gar nichts

https://blog.oneunicorn.com/2012/05/03/the-key-to-addorupdate/

Außerdem ist es möglich, dass die DbSet Listen Einträge mit doppeltem Key enthalten - der wird dann erst beim Schreiben in die Datenbank geprüft und man erhält dann eine Key Violation. Daher besser zunächst zu suchen und dann zu adden.

Saturday, April 02, 2016

ssl zertifikat erstellen und iis https (ssl) einrichten

1) SLL Zertifikat erwerben und installieren am IIS:

1a) Zertifikats Anforderung erstellen:

Im IIS unter server \ serverzertifikate mit rechter Maustasete eine Zertifikatsanforderung erstellen und speichern => man erhält ein Textfile das in etwa so aussieht:
oder auf bestehendes Zertifikat renew klicken

-----BEGIN NEW CERTIFICATE REQUEST-----
blablabla
-----END NEW CERTIFICATE REQUEST-----

1b) Zertifikat von Zertifizierungsstelle austellen lassen:

diesen Text dann in die Zwischen ablage kopieren und beim Zertifikatsanbieter einfĂĽgen.
kostenlose Webzertifikate gibt z.b. startssl.com - allerdings seit ende 2016 werden diese von vielen Browsern nicht mehr als sicher erachtet.

1) email adresse angeben => erhalte code, mit diesem wird dann ein zertifiakt ausgestellet, das man in den Webbrowser importieren muĂź (neu starten des Webbrowsers) dann wieder startssl.com ansurfen, einloggen
2) hostname validieren
3) zertifikat erstellen mittels wizard => zip file enthält iis.zip, dieses enthält ein CRT File

sslmarket.at
1) konto erstellen
2) zertifikat beantragen => brauche Emailadresse fĂĽr die ssl domain


1c) Zertifikat importieren in IIS:

Intermediate Zert sollte vorher in die Zwischenzertifizierungsstellen importiert werden (Zert Manager)

das File von der Zertifizierungsstelle dann im IIS unter server\serverzertifikate mit rechter Maustaset Zertifikatsanforderung abschließen importieren (*.* bei txt auswählen)
bei Problemen zunächst als Perönliches Certt abschließen, exportieren (pfx), löschen und neu importieren als Webhosting

2) Webinhalt fĂĽr https freigeben

2a) Website ssl Bindung hinzufĂĽgen

Website auswählen, bei Bindungen https hinzufĂĽgen und zuvor importiertes Zertifikat auswählen, es sollten dann z.b.  eine Bindung fĂĽr Port 80 und eine fĂĽr 443 existieren,

2b) Firewall Port 443 freigeben

2c) Web Servicekonfigurieren

http://blog.adnanmasood.com/2008/07/16/https-with-basichttpbinding-note-to-self/

The modified basicHttpBindinging to allow security mode = Transport
<bindings>
            <basicHttpBinding>
                <binding name="defaultBasicHttpBinding">
                    <security mode="Transport">                        <transport clientCredentialType="None"/>
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <services>
            <service behaviorConfiguration="MyServiceBehavior"
            name="MyServiceName">   
                <endpoint address="https://AdnanMasood.com/MyService.svc"
                            binding="basicHttpBinding"
                            bindingConfiguration="defaultBasicHttpBinding"
                            contract="Axis.IServiceContract" />
            <serviceBehaviors>           
                <behavior name="MyServiceBehavior">
                    <serviceMetadata httpsGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <add key="CustomIISServiceHostEndPoint" value=https://AdnanMasood.com/MyService.svc"/>
    </appSettings>

which corresponds to your end point.
<system.serviceModel>        
and the httpsGetEnabled
<behaviors>
and last but not least, if hosting in IIS, here is the key for custom factory. Details about how to do this part can be found on the MSDN article "Deploying an Internet Information Services-Hosted WCF Service" referenced below.
    <appSettings>