fredag den 26. oktober 2018

Moq – Use Setup arguments (parameters) in the Returns of a mocked function

It can be useful when mocking a function with Moq to use parameters passed into the Setup of a mocked function in the Returns function.
I created a unit test to illustrate the basic idea:
[TestFixture]
public class TestFixture1
{
   public interface ITest
   {
      int Func(int x, int y);
   }

   [Test]
   public void Test()
   {
      Mock<ITest> mockTest = new Mock<ITest>(MockBehavior.Strict);

      mockTest.Setup(x => x.Func(It.IsAny<int>(), It.IsAny<int>()))
         .Returns((int x, int y) => { return FuncData(x, y); });

      ITest test = mockTest.Object;

      Assert.AreEqual(5, test.Func(2, 3));
      Assert.AreEqual(3, test.Func(1, 2));
   }

   private int FuncData(int x, int y)
   {
      return x + y;
   }
}
The main idea is to use a lambda expression in the Returns function that specifies the arguments that can be used in whatever way is needed.

mandag den 22. oktober 2018

Delete all bin+obj folders using powershell

Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }

fredag den 8. januar 2016

Search for files on windows

For some wierd reason windows explorer really really sucks at finding files in its own file system.

Luckily the command line still knows how to:

c:>dir *.cpp *.h *.java /b/s
c:>dir svcutil.exe /b/s
c:>dir myfile.* /b/s 

fredag den 13. juni 2014

WCF: The connection was closed unexpectedly

When SoapUI gives you a hard time and just closing connection, you should try this out.

Insert this config into your x.config file:

<system.diagnostics>
    <!-- This logging is great when WCF does not work. -->
    <sources>
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "c:\temp\trace.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>


And use svctraceviewer.exe to view the file.

lørdag den 4. januar 2014

Ever wanted to delete all tables from a sql server db?

Well here's how to.

/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

fredag den 18. oktober 2013

6 easy foolproof steps to log4net file logging

Just to get you started, I have created this very basic guide to get something into your log file.

  1. Use NuGet to install log4net.
  2. Create a logger instance globally in your code:
    private static readonly ILog logger = LogManager.GetLogger(typeof(MainWindow));
  3. Configure the code to look for XML configuration using XmlConfigurator:
    XmlConfigurator.Configure();
  4. Locate you Assembly.cs file and insert the following line to let log4net know that you are using your App.config file for the configuration of log4net.
    [assembly: XmlConfigurator(Watch = true)]
  5. Insert this into your App.config file:
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </configSections>
     
      <log4net>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
          <file value="example.log" />
          <appendToFile value="true" />
          <maximumFileSize value="100KB" />
          <maxSizeRollBackups value="2" />

          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%level %thread %logger - %message%newline" />
          </layout>
        </appender>

        <root>
          <level value="INFO" />
          <appender-ref ref="RollingFile" />
        </root>
      </log4net>
  6. Start logging by calling any of the logging methods on your logger instance:
    logger.Info("My first log entry");
Thats it! Pretty damn easy!

Watch out for sections like this in your config:
<startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

It might cause some problems, so perhaps just delete it!