Friday, December 30, 2016

stateless - workflows in .NET

Hi,

I found some frameworks for handling workflows:

- ApprovaFlow
- simple state machine
- objectflow
- jazz
- nstate 

... but best of all alternatives seems to be "stateless" (see: https://github.com/dotnet-state-machine/stateless ).

The following features / best practices are made (following the examples-folder of the github repo):
  • choose or build a class for State
  • choose or build a class for Triggers
  • create an object for a StateMachine<State,Trigger>
    • initialization / get-set possibility to variables outside)
  • configuring phase
  • stateMachineObject.IsInState(stateItem)
  • stateMachineObject.PermittedTriggers
  • stateMachineObject.CanFire(triggerItem)
  • stateMachineObject.Fire(triggerItem)
  • stateMachineObject.FireAsync(triggerItem)
Configuration Options fluid-api style:
  • stateMachineObject.Configure(stateItem)
    • SubstateOf(stateItem) // Hierarchical State
    • PermitReentry(Trigger)
    • Permit(Trigger, State)
    • PermitIf(Trigger, State, Guard)
    • Ignore(Trigger)
    • InternalTransition
    • OnEntry(() => action());
    • OnEntryAsync(async () => await action());
    • OnEntryFrom(trigger, x => action()); // Parameterized Trigger
    • OnExit(() => action());
Support for DOT-graph - visualization (see: Graphviz): .ToDotGraph()

kr,
Daniel

Thursday, December 29, 2016

Assigning Certificates to applications (without IIS)

Hi,

it is hard work to implement a web page using HttpListener! It is easy to turn the HttpListener to listen to https (by changing the listening prefix) but to get this up and running is still a challenge!

You need to:


I followed the instructions of http://sunshaking.blogspot.co.at/2012/11/https-communication-httplistener-based.html , but still needed more than 4 hours to get it up and running. Important is to work with the generated pfx file! It is clear but it is not mentioned explicitly in the article... also keep an eye on the icons. if you have the pfx file, you need to see a lock symbol in the mmc.

kr,
Daniel

Thursday, December 22, 2016

SQL Server - Checks

Hi,

try to start a list of most important things (not in order) to check as a DBA in operation:


  • Services Running
    (see: sys.dm_server_services)
  • FileSystem Space
    (see: sp_spaceused and sp_MSforeachtable / sys.master_files + sys.databases / msdb.sys.dm_io_virtual_file_stats)
  • Error Log (Agent and DB)
    (see: xp_readerrorlog)
  • Locks and Waits
    (see: sys.dm_exec_requests (wait_type), sys.dm_exec_connections, sys.dm_exec_sql_text, trace-flags 1204, 1222)
  • Backups
    (see: msdb.dbo.backupmediafamily, msdb..backupset)
  • expensive queries
    (see: dm_exec_query_stats, dm_exec_sql_text, dm_exec_query_plan)
  • index fragmentation
    (see: sys.dm_db_index_physical_stats)
  • statistics
    (see: dbcc show_statistics)
  • consistency
    (see: dbcc checkdb / progress: SYS.DM_EXEC_REQUESTS, SYS.DM_EXEC_SQL_TEXT)
  • overview of sessions (users)
    (see: sys.dm_exec_sessions, kill)
  • Shrink
    (see: dbcc shrinkfile / don't do that if not edge case)
  • User Handling
    (see: create user/login, sp_change_users_login)
  • Update Process
  • Logging Data-Changes
    (see: Change Data Capture (msdn), Trigger)
  • Firewall Security
  • Automation
    (see: SQL Server Agent, Powershell, SSIS, ETL)
Supporting Tools: Management Studio, Profiler, SSDT / BIDS, Configuration Manager, PowerShell, Nagios, IIS Crypto, sqlcmd, bcp, tsqlt 

kr,
Daniel

C# WCF WebOperationContext - best practice in error handling

Hi,

WebOperationContext is typically used in a WCF REST method so that method can access the incoming request and outgoing response.

(see: http://stackoverflow.com/questions/18747581/difference-between-weboperationcontext-current-and-httpcontext-current )


... in my projects I wrap OperationContract-ed methods with error handling. You can imagine that with a standard method like MessageWrapper which uses an Action or Function and implements the code in lambda-style in-line. The MessageWrapper handles the Exception handling and sets the Response ErrorCode (WebOperationContext.Current.OutgoingResponse.StatusCode) to 200 if everything is fine or to error if an exception occurred.

public T MessageWrapper(Func<T> action) where T : class{
  try 
    SetStatusOK(); 
    return action(); 
  } catch (Exception exc){
    SetStatusError(exc);
    return null;
}

public ReturnObject Operation() {
  MessageWrapper(()=> return new ReturnObject("some", "parameters"));
}

... here I would love to mention, that with Castle you can create interceptors where you don't have to put the MessageWrapper inside the business logic code. You can keep this as an aspect (AOP) which can be configured at startup.

And here one more thing that helped a lot me during development time. You can set additionally to the StatusCode also a StatusDescription which e.g.: is displayed in your browser of choice as an explanation for an error. So StatusDescription = exc.Message is simply gold!

kr,
Daniel

Wednesday, December 14, 2016

monitor sql server table to track changes in .net c# projects

Today I found a class in the .net framework which makes it possible to get events about data changes of a sql server table (idea of a trigger, but outside the db in a higher layer) what is perfect for caches: SqlDependency. Internally it uses the service broker of the sql server what sounds quite reliable in comparison to watch dogs. (About 2 years ago I made such a watch dog framework,... my experience: don't do that...)

kr,
Daniel

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx

http://stackoverflow.com/questions/5288434/how-to-monitor-sql-server-table-changes-by-using-c

https://github.com/dyatchenko/ServiceBrokerListener

Thursday, December 8, 2016

REST APIs

found 2 very nice projects which are used to develop REST APIs. They are designed high level and can be used for code generation and documentation.


  • http://swagger.io/
  • http://raml.org/

with the ability to move swagger to raml using the project swagger to raml ( http://raml.org/projects/projects#q:swagger2raml ).

Important for me: both work with Java and .NET ... Swagger even has Client Generation for Angular (1 and 2).

Currently not available: .NET WebApi which would be great.

kr,
Daniel

Powershell functions

I needed a simple .NET application with less than 10 lines of code... after writing the code in less than 2 minutes I thought about the maintenance, deployment, version control and so on...

Finally I decided to change the c# code into powershell and was surprised how easy it was to call .NET functions and how hard it was to work with functions... (this is a different example but with better param-handling and with about the same complexity).


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function CountOfDaysSince
{
    param(  [Parameter(Mandatory=$True ,Position=0)] [DateTime] $date,
            [Parameter(Mandatory=$False           )] [bool    ] $logging = $false);
    
    
    [int] $delta = ([System.DateTime]::Now.Subtract($date)).TotalDays;

    if($logging) {
        "Date is            : " + $date.ToShortDateString() | Write-host ;
        "Diff in Days to now: " + $delta                    | Write-host ;
    }

    return $delta
}

$x=CountOfDaysSince (New-Object System.DateTime(2012,08,04)) -logging $false
[int] $count = $x[-1]
Write-Host $count

For me functions are quite complex because I am not used to the syntax or the way how powershell functions are used. Even the naming is not very powershell-ish (Probably Count-DaysSince?). Writing return $delta returns $delta, but in fact the return type is object[]. I read on stackoverflow that return $a is equivalent to "$a; return;" what opens up the possibility to easily return 2 return values like "$a; $b; return". This is quite similar to stored procedures in SQL Server where a stored procedure can return multiple record sets. Nice, but not very intuitive. Thats the reason why line 18 gets one array item. With index -1 you will receive the last element of the array, which is also nice, but... :-)

kr,
Daniel

WPF and Castle Windsor

Before using Castle Windsor I used to implement a provider keeping static references to view-models and reference these in the View using Xaml Databinding... something like DataContext="{x:static ViewModelProvider.MainViewModel}".

Now after getting to know Castle Windsor and its ability to handle references it makes totally sense to solve that differently (or to be concrete: to solve that better). For development time we still need to hard code a design-time-view-model cause else we loose all the features of the IDE... Nevertheless Windsor should take over the control about the wiring of View and ViewModel. Main reason therefore is the power (features like Interceptors) and the flexibility (DynamicParameters, Load Config from XML, work with interfaces) coming up with.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public class ActivatorWPFVM<T> : DefaultComponentActivator
    {
        public ActivatorWPFVM(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
            : base(model, kernel, onCreation, onDestruction)
        {

        }
        protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
        {
            var component = base.CreateInstance(context, constructor, arguments);
            if(component is Window)
            {
                ((Window)component).DataContext = DIProvider.Container.Resolve<T>();
            }
            return component;
        }
    }

So by calling...

container.Register(
   Component
      .For<MainWindow>() 
      .Activator<ActivatorWPFVM<MainViewModel> >() 
      .LifestyleTransient());

... we can create a Window reference with an already wired up connection to its ViewModel (in config section where it should be).

kr,
Daniel

Tuesday, December 6, 2016

sqlcmd nowadays

Hi,

it is quite uncommon for MS-SQL Server-DBAs to work in command line (or much more uncommon in comparison to oracle or pg-sql DBAs). Nevertheless there is a tool from the stone-age called sqlcmd which has very nice features and which is actively developed by Microsoft up to now. See here: http://www.sqlserverspecialists.com/2012/10/sqlcmd-commands-sql-server-tool.html and https://msdn.microsoft.com/en-us/library/ms162773.aspx .

Main thing is:
- connect to different db
- call dos commands (mixing up OS and DB)
- set and use variables
- load sql files for execution
- redirect output to filestreams (file, stdout, stderr)
- change output format to XML

... even if this sounds quite limited it is still helpful for many purposes like e.g.: scheduled tasks. Especially the OS / DB combination is often very useful if you need to wait for the execution of A to start db-job B.

In SQL Server Management Studio the so called sqlcmd-mode to be used inside the query window is implemented which allows a limited feature set in comparison to the command line features seen above. See: https://msdn.microsoft.com/en-us/library/ms174187.aspx

Using SQL Server Agent you need to use an Operating-System Job-Step to work with sqlcmd (like with any other OS application). See an article about differences between TSQL-JobSteps and CmdExec using sqlcmd here: http://www.travisgan.com/2014/04/sql-server-agent-job-and-sqlcmd.html

So finally: with sqlcmd scripting can be improved by using variables, call different scripts and call the OS. In the original command line version it has some possibilities (like opening a dedicated admin connection) which are nice, but another very helpful thing is that it is kept small and performant.

Kr,
Daniel

simple secure data safe

Hi,

today I added a new github repo which contains a script toggling a folder to be

1) a password secured file or
2) a data folder to work in

https://github.com/starkeeny/SSDS

I will go on working on this, but I think it is a nice start for securing my data.

Btw: there is a nice hint from codeproject related to the topic of securing data http://www.codeproject.com/Articles/1151836/How-to-hide-your-files-in-windows-using-unmounted , but I think to remove the drive letter from a drive is not my favourite solution. Nevertheless as a user I wouldn't have expected to find data on an "un-named" drive... so this is a nice and still simple trick...


Kr,
Daniel

Saturday, December 3, 2016

SQL Server - Providing Demo Data (temporary)

Today I found a new solution to provide temporary data! Additionally to creating a table (not really temporary), creating a temp table (create table #xy) and declare a table variable (declare @xy table(...)) there is also the possibility to put values directly into a select statement:

select * from
(
  values 
    (1,2,3),
    (2,3,4),
    (3,4,5)
) as myValues (nr1, nr2, nr3);


this looks quite easy and can be very useful in a with block, because you can use this adhoc-values like a table and if it is necessary you can move them very easily into a table.

with config as (
  select * from ( values ('dataFolder', '/home/...') as config (key, val)
)
select 
  dataFolder.Value + data.FileName, data.Content
from 
  data, config dataFolder
where 
   dataFolder.Key = 'dataFolder'


... but this is probably not the best show case... I think demonstration / training about SQL would be a better use-case (e.g.: showing how join statements work or stuff like this... would be the first training explaining "with" before "join" :-) ... nevertheless I was fascinated and love this feature...).

kr,
Daniel