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")]