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

Tuesday, November 29, 2016

Powershell-code inside of my application

Hi,

I wanted to combine powershell and my .net application. In fact this works quite easily. The following link was quite helpful to make this work: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

We see here that an assembly has to be added (System.Management.Automation), but that's more or less it... I encapsulated the invocation of the powershell code into the following class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
using System.Management.Automation;
using System.Collections.ObjectModel;

class PSExecutor
{
    protected Collection<PSObject> Execute(string command, params Tuple<string, object>[] parameters)
    {
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            // add a script that creates a new instance of an object from the caller's namespace
            PowerShellInstance.AddScript(command);
            parameters.ToList().ForEach(x => PowerShellInstance.AddParameter(x.Item1, x.Item2));

            return PowerShellInstance.Invoke();
        }
    }
}

... so we can use this class as a base class (if you want to call the execution of the code directly: change method Execute to be public). The following snippet is an example how to use the base class:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    // https://gallery.technet.microsoft.com/Get-WindowsUpdatesps1-7c82c1f4
    class GetWindowsUpdatePSExecutor : PSExecutor
    {
        public Collection<PSObject> Execute()
        {
            return base.Execute(
@"
$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search(""IsInstalled=0"") # ""IsInstalled=0 and Type='Software' and IsHidden=0""
$SearchResult.Updates |Select-Object -Property Title, Description, SupportUrl, UninstallationNotes, RebootRequired
");
        }
    }

... with the snippet above you can check the OS for pending windows updates.

kr,
Daniel

Friday, September 16, 2016

SQL Server: GO with count | delete table in chunks

Hi,

I was asked to delete parts of a table. Unfortunately the amount of rows was to big to delete them all in a single shot (TLog would exceed the file limit). I tried a different approach deleting the table in chunks using a loop, but this still executes as a single transaction.

Then I thought I could solve the problem by using a top statement and using go... afterwards I would copy these lines some thousand times and go for a coffee... but than the msdn article about go ( https://msdn.microsoft.com/en-us/library/ms188037.aspx ) opened up a very nice alternative.

Go can have an argument "count" with the following description:

count
Is a positive integer. The batch preceding GO will execute the specified number of times.

... nice, but how will it be executed? Statement-Block COUNT times and then one go (same problem like in the loop scenario) or is it a COUNT times series of statement, go, statement, go,...

I was not able to find the answer so I checked it myself with the following code:

waitfor delay '00:01:00'
go 3

the session-details of the activity monitor showed the single waitfor - statement. Proof enough that go with count creates a statement-go-statement-go series which perfectly solves my problem of the first section (see https://technet.microsoft.com/en-us/library/ms175486(v=sql.105).aspx ).

delete top (5000) from table where x = 123;
go 10000

kind regards,
Daniel

Wednesday, August 3, 2016

Dates in WCF - JavaScript communication over JSON

Hi,

today we had really big troubles with WCF and javascript communication. We wanted to send dates over the wire and use its value for additional libraries (which rely on type Date). After hours of playing around I finally solved it with JSON.parse.

Different approaches starting from overriding the WCF object serializer till writing a custom json parser libraries had been tried but finally all these are very unstable.

Resources I found to solve the problem
- Hanselman ... describing my problem
Stackoverflow ... similar issue (solution mentioned)
- Documentation ... after knowing the solution a perfect page :-)

JavaScript/HTML testproject follows...

kind regards,
Daniel




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<html><head></head><body>

<script>
function test() {

var objectString = '{"name" : "Daniel", "date" : "\/Date(1293034567877)\/"}';

//___________________________________________________________________________________
//

var objectDataWithParse =  JSON.parse(objectString);

var objectDataWithDate = {
    "name": objectDataWithParse.name,
    "date": new Date(parseInt(objectDataWithParse.date.substr(6, objectDataWithParse.date.length-8)))
};

function parseReviver(key, value) {
    var a;
    if (typeof value === 'string') {
        if(value.substr(0, 6) == '\/Date(') {

            alert(value.substr(6, value.length-8));
            return new Date(parseInt(value.substr(6, value.length-8)))
        }
    }
    return value;
};

var objectDataWithReviver = JSON.parse(objectString, parseReviver);

//___________________________________________________________________________________
//

var outObj = {};
outObj = objectDataWithDate;
outObj = objectDataWithParse;
outObj = objectDataWithReviver;

//___________________________________________________________________________________
//

document.getElementById('outputDIV_json').innerHTML = objectString;
document.getElementById('outputDIV_name').innerHTML = outObj.name;
document.getElementById('outputDIV_date').innerHTML = outObj.date;

};
</script>

<div>
<button onclick="test()" >test</button>
</div>
<hr />
<div id="outputDIV_json" ></div>
<div id="outputDIV_name" style="float:left;margin-right: 5px;margin-top: 5px; background: lightgreen"></div>
<div id="outputDIV_date" style="float:left;margin-right: 0px;margin-top: 5px; background: orange"></div>

</body></html>

Sunday, June 26, 2016

Castle and WCF (3)

Hi,

I went through hell to get this stuff work, but finally I got it. As partly mentioned in part 2 of this series I wanted to create an IIS hosted rest-service without the need of adding a svc-file. So I created an empty web-project, added a global.asax file and added the following code in the Application_Start method:


WindsorContainer
 container = new WindsorContainer();


ServiceHostFactoryBase factory = new WindsorServiceHostFactory<RestServiceModel>(container.Kernel);
container.AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero)
  .Register(Component.For<IMyService>()
                     .ImplementedBy<MyService>()
                     .LifeStyle.Is(Castle.Core.LifestyleType.Singleton));

RouteTable.Routes.Add(new ServiceRoute("MyService", factory, typeof(IMyService)));

There is no need to configure the service in the web.config-file except ASP.NET Compatibility which is needed by the Routes.Add code-line.

kind regards,
Daniel

Friday, June 17, 2016

Castle and WCF (2)

Hi,

first of all I got the feedback that "Castle" is the wrong naming... so for clarification: with Castle the whole technology-stack of http://www.castleproject.org/ is meant including (especially) DynamicProxy and Windsor.

Further research brought me to the follow up question whether it is possible to implement a service with a non-empty (standard) constructor. Yes, this is also possible ( stackoverflow.com ). You simply need to:

  • create a Custom-ServiceHostFactory (base class: ServiceHostFactory) and 
  • override CreateServiceHost which should create a Custom-ServiceHost. 
  • Each implemented service contract (loop over this.ImplementedContracts.Values) should get a Custom-Behavior (interfaces: IContractBehavior and IInstanceProvider) added. 
  • In the instance provider happens the magic of creating a service with new (override the two GetInstance-methods). 
A step-by-step guide can be found on MSDN here. Here a quote of the github answer referenced above:
You can easily generalize this approach, and in fact some DI Containers have already done this for you (cue: Windsor's WCF Facility).
 A tutorial how to use the WCF facility can be found here and here. A walk-through "DI in WCF in 5min" can be found here (this article shows perfectly that DefaultServiceHostFactory enables you to create services with the full power of DI).

I am looking forward to test that approach with "RouteTable.Routes.Add(new ServiceRoute(...))".

kr, d

Thursday, June 16, 2016

Castle and WCF

Hi,

it is a quite hard task to build a good and stable back-end. The request/response interfaces therefore are often full of boiler plate code. In my .NET applications I rely on WCF and REST services. First questions:


Can I create services on the fly or do I have to create a *.svc-file as described in 90% of the tutorials?

Answer: Yes... with ServiceHostFactory ( http://stevemichelotti.com/restful-wcf-services-with-no-svc-file-and-no-config/ )


Can I/Do I have to still use IIS?

Answer: Both is possible


Do I need to be a web.config expert?

Answer: You can config your stuff in code too.



So summarized: I can create ServiceHostFactories on the fly and can use Castle to inject the dependencies... great. Castle provides even more: WCF Integration Facilities... https://github.com/castleproject/Windsor/blob/master/docs/wcf-facility.md

There seemed to be an active community on writing facility based, config less, castle-driven backends like at https://github.com/vcaraulean/WcfWithoutConfigFile/blob/master/WcfWithoutConfigFile.WebHost.Castle/Global.asax.cs

... really cool... I am looking forward to use that stuff and post some first results...

kind regards,
Daniel

Friday, June 10, 2016

Dependency Injection with Windsor and WPF

Hi,

this month I started reading about dependency injection and found out that castle.dynamicProxy (already mentioned in earlier posts) works great with castle.windsor. This might not be surprising but nevertheless after my first project using both nuget-packages I can definitely say that using these has changed my way of work. In this project my classes are shorter, better testable and my interfaces are more proper. (About a year ago I read the book about Clean Code Development by Robert C. Martin. The book is an advertisement for TDD with some pointers about coding style and development mind sets).

One thing to mention about my project using castle.windsor: it supports even more separation of Views and ViewModels of WPF. I used a custom Activator of generic type T (derived from DefaultComponentActivator) to activate my window and asked the windsor container to resolve a singleton viewModel of type T which can be set as the datacontext (override of CreateInstance). I stored the container as a static member of a centrally available class.

So:

  • WPF-Activator<ViewModel>
  • Still consider to set the DesignViewModel in the XAML code directly
  • create a DIProvider 
  • use windsor - installers
  • remove startup-uri in app.xaml and start mainwindow with showdialog
  • prefer dependency injection over service locator pattern
  • use interfaces instead of implementations


kr, D

Sunday, May 29, 2016

Book-Review: AOP in .NET (Matthew D. Groves)

The book is very good to start with Aspect Oriented Programming in .NET (as the title says it). It starts with a general overview about aspects, advice and point-cut to conquer cross-cutting concerns (as it would be described in a book for aspectJ) and adds understandable examples to show where all this stuff makes sense in combination with TDD.

Later it is shown which kind of aspects there are (those: for methods and those: for properties) and on which levels and ways these can be applied. The most important asset of the book is that it really makes it clear that there are different paradigms to make AOP. The first way described is "weaving" which actually changes the il-code in a post-compile step and "dynamic proxies" which create reflection-assemblies on the fly at runtime (the pros and cons are - in my opinion - the most important part of the book).

After reading the book i'm definitely able to write AOP code in .NET, but there are many references to IoC and DI so I would recommend to read a book about these first.

Kr, Daniel

Thursday, May 19, 2016

Castle DynamicProxy

Hi,

I am currently reading a book about AOP in .NET (book review-post will follow soon). I really fell in love with Castle DynamicProxy and it probably works even better in combination with ninject (see: https://www.nuget.org/packages/Ninject.Extensions.Interception.DynamicProxy/ --> my next topic to dive into). The good thing here is that no weaving process is needed as post-build action. This means that if you debug, you debug the actual code and not manipulated code which might not match (or prevent debugging at all).

Crosscutting-concerns will be tackled by method-interception using a proxy:

var service = new ProxyGenerator().CreateClassProxy<Class1>(new Aspect());

  • Aspect must implement IInterceptor. 
  • Class1 should have decorated its functions as virtual to create the appropriate proxy.

Often implemented aspects: logging, security, caching, threading (Invoke), lazy loading, INPC-implementation, exception handling, defensive programming and argument handling, validation, auditing, monitoring, fault tolerance.

kr, d

Backup

Today i wanted to backup my PC. There are 1000 possible ways to. My favorite solution would be: having 5 Dropbox accounts (1 for each device) with unlimited storage... 

Unfortunately this is only possible with a paid team or business license... So... No... Also any other cloud solution costs...

A possible opportunity was owncloud ... an on-premise solution with support for mobile devices. After spending hours installing a wamp-server and owncloud i found out that this can not be hosted on windows (since a couple of version ... Attention there are youtube tutorials for windows -> legacy! No windows support)

I decided to use copy jobs like robocopy or freefilesync for my PC (all directories except: windows and "program files"). This works great...

Last improvement i found is btsync (bit torrent synchronization), which copies directories over the internet. The sync-app is implemented for a lot of devices, so finally I found a way to backup my mobile phones too! yes!

Friday, May 13, 2016

Webserver cassini

I didn't know that the logic of the IIS is part of .net's fcl... Here a project using this: cassini

See: https://msdn.microsoft.com/de-de/library/bb979483.aspx

King regards,
Daniel

Tuesday, March 22, 2016

comma separated values in a single cell (T-SQL)

Hi,

I reviewed my solution back from 2015-05-27 ( http://itados.blogspot.co.at/2015/05/sql-recursive-functions-linked-lists-in.html ). I thought it would be easy to explain a colleague how to put multiple values into a cell based on this article, but it took me over 5 minutes of staring at the code to remember how this all works...

Here an easier example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
declare @x as table (id int, val int)

insert into @x values (1,1)
insert into @x values (1,2)
insert into @x values (1,3)
insert into @x values (2,1)
insert into @x values (2,2)
insert into @x values (2,4)

select 
  o.id, 
  stuff(
    (
      select ', ' + cast(i.val as nvarchar) 
      from @x i
      where o.id = i.id
      for xml path('')
    ), 1, 2, ''
  )
from @x o 
group by id

kind regards,
Daniel

Wednesday, March 9, 2016

C# switch and double assigned enum values

Hi,

today I wanted to trick C#'s switch-case statement, but failed :-)

I tried to create an enum with 2 values pointing to the same value (yes this do is possible).

    public enum TestEnum : uint
    {
      a = 1,
      b = 1,
    }

Main:
    switch (variable)
    {
      case TestEnum.a:
        Console.WriteLine("a");
        break;
      case TestEnum.b:
        Console.WriteLine("b");
        break;
      default:
        break;
    }
... looking at the second part (only) this code makes perfect sense (as a test-case), but in combination it must be considered that the switch-case statement must find a unique case as a target and resolves the values behind the enumeration.

Compiler Error:

Error CS0152: The switch statement contains multiple cases with the label value '1'

... even if i failed to trick the compiler it is good news that c# is consistent here.

Kind regards,
Daniel

Wednesday, February 24, 2016

My first hour with prolog (Prolog 101)

I started with prolog and it is hard. It really is!
Here I found a portable "IDE" http://portableapps.com/apps/development/swi-prolog_portable and here a video how to use it: https://www.youtube.com/watch?v=6Dh7eux76a8 .
I created a test project to summarize a list of numbers:
File > Edit > [select a file with following content: *.pl]

sumOfItems([], 0).
sumOfItems([H | T], Output) :-
    sumOfItems(T, OutputInner),
    Output is H + OutputInner.

File > Consult > [select same file]
1 ?- sumOfItems([1,2,3,4,5],X).
X = 15.
... from now on changes to the file are taken over if they were compiled.
To check that I added the following function and compiled:
avgOfItems([], 0).
avgOfItems([H], Result) :-
 Result is H.
avgOfItems([H|T], Result) :-
 avgOfItems(T, ResultInner),
 Result is (H + ResultInner)/2.
avgOfItems was callable...

kind regards,
Daniel

Tuesday, February 23, 2016

Filter DataGrid in C#/WPF using ICollectionView

Today I tried to find a bug in a ICollectionView-based WPF filtering action. The problem was fortunately easy to find, but I was shocked that I didn't find an easy example in our projects to explain my colleague the way how this all works... So, here is my easy example of a grid which can be filtered:

I created a standard WPF project and installed the nuget-package mvvm-light (see: http://www.codeproject.com/Articles/321806/MVVMLight-Hello-World-in-10-Minutes if you don't know the nuget package). Long story short: it provides some base classes and some assets like a relay-command which is useful to start your work without the need of creating boiler-plate code again and again. The mvvmlight's viewmodel-locator is defined as a static resource in app.xaml so you can define view-models (and its instances) centrally using an "inversion of control"-container (called SimpleIoc). Here nothing has to be changed, because it creates a MainViewModel (as an example) we will use to create this sample.
I kept the MainWindow.xaml which was created by default and put the needed controls in there:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<Window x:Class="FilteringGrids.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FilteringGrids"
        mc:Ignorable="d"
        Title="Filter-Test" Height="350" Width="525"
        DataContext="{Binding Main, Source={StaticResource Locator}}">
    <Grid Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
 
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
 
        <TextBox Grid.Row="0" Text="{Binding FilterText}" Margin="0,0,10,10"></TextBox>
        <Button Grid.Row="0" Grid.Column="1" Margin="0,0,10,10" Height="25" Width="50" Command="{Binding RefreshCommand}">Refresh</Button>
        <Button Grid.Row="0" Grid.Column="2" Margin="0,0,0,10" Height="25" Width="50"  Command="{Binding FilterCommand}">Filter</Button>
        <DataGrid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" ItemsSource="{Binding Data}" />
    </Grid>
</Window>

As we can see in line 9: the datacontext is wired up with the viewmodel instance created in the ViewModelLocator, so we can use the paradigm of MVVM. In the following XAML code we bind the text to filter, the data and two buttons to the background viewmodel...


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Input;
namespace FilteringGrids.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public class Model
        {
            public string Name { get; set; }
            public string Value1 { get; set; }
            public string Value2 { get; set; }
            public string Value3 { get; set; }
            public string Value4 { get; set; }
        }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            #region Filter
            FilterText = "";
            Predicate<object> filterFunction = (object raw) =>
            {
                Model dataToFilter = raw as Model;
                return
                    dataToFilter.Name.Contains(FilterText) ||
                    dataToFilter.Value1.Contains(FilterText) ||
                    dataToFilter.Value2.Contains(FilterText) ||
                    dataToFilter.Value3.Contains(FilterText) ||
                    dataToFilter.Value4.Contains(FilterText);
            };
            FilterCommand = new RelayCommand(() => DataCollectionView.Refresh(),
                                             () => true);
            #endregion
            #region Init / Refresh
            RefreshCommand = new RelayCommand(() =>
            {
                Data = new List<Model> {
                    new Model() { Name="one",   Value1="1", Value2="1.0", Value3="1.00", Value4="1.000" },
                    new Model() { Name="two",   Value1="2", Value2="2.0", Value3="2.00", Value4="2.000" },
                    new Model() { Name="three", Value1="3", Value2="3.0", Value3="3.00", Value4="3.000" },
                    new Model() { Name="four",  Value1="4", Value2="4.0", Value3="4.00", Value4="4.000" },
                };
                DataCollectionView = CollectionViewSource.GetDefaultView(Data);
                DataCollectionView.Filter = filterFunction;
                this.RaisePropertyChanged("Data");
            }, () => true);
            // init data
            RefreshCommand.Execute(null);
            #endregion
        }
        public string FilterText { get; set; }
        public List<Model> Data { get; set; }
        private ICollectionView DataCollectionView { get; set; }
        public ICommand RefreshCommand { get; set; }
        public ICommand FilterCommand { get; set; }
    }
}


What we see here is that 99% of the magic happens in the constructor of the viewmodel. This is bad style, but keeps the things easy for the example, so please forgive me here. We see here that all members (defined at the end of the class) are bound by the xaml-code except the CollectionView which is used for the actual filtering.
Important here is:

  • if you change the reference of your data source then populate that to the UI (INPC -> RaisePropertyChanged)
  • Filtering over ICollectionView is easily achievable over a Predicate-function
  • recreate the ICollectionView if the original instance of the data changes (you probably don't need a reference to this)
  • if the filter-result might change call CollectionViewInstance.Refresh()

kind regards,
Daniel

Wednesday, February 17, 2016

TableVariables vs. TempTables

Hi,

in short:
- TableVariables don't change the schema, but are also executed in tempdb
- TempTables have statistics in comparison to TableVariables (query fast, costs after change)

I personally use TableVariables more often than TempTables, because I can't forget to drop them :-)


long version:

kind regards,
Daniel

get a random and unique id in a table

Today I created a random ID. The random ID must still be primary key what means that it must be unique. This is a code walk-through to solve this problem:

First of all I created a play-ground to make tests (with 4 test-entries).
declare @tbl TABLE(ID int)
insert into @tbl values (3), (7), (9), (10) 
Then I introduced a parameter to define the scope. Here we see 0 as an error case (no more IDs available) and start with ID 1 to @maxValue.
declare @maxValue int = 10
 Then we create a loop to test the development for example 20 times:
declare @i int = 0
while (@i < 20) begin
The idea now is to create a random value (=myRequestID) and to check whether the ID currently in use (if so, it will be copied to targetID).

    declare @myRequestID int = (cast(   (RAND()*(@maxValue-1))    as int) + 1)
    declare @myTargetID int = 0
    if not exists(select * from @tbl where ID = @myRequestID) begin
            set @myTargetID = @myRequestID
            insert into @tbl values (@myTargetID)
if we have already used this value (it exists in @tbl) then we need to search for an ID after the random value. Therefore we can choose all requested entries after the random value which have no next sibling and return the smallest id + 1
    end else begin      
        select @myTargetID = isnull(MIN(id) + 1, 0) from @tbl t
        where id between @myRequestID and (@maxValue - 1)
        and not exists(select * from @tbl innerT where innerT.ID = t.ID + 1)
if the targetID has a value we found a valid entry, else if the value is zero, we have not found an entry after the random value, so we jump over the maxValue border and restart at the beginning. Here we need to consider that the value 1 is a special case which needs to be handled extraordinary. 
        if @myTargetID <> 0 begin
            insert into @tbl values (@myTargetID)
        end else if not exists(select * from @tbl where ID = 1) begin
            set @myTargetID = 1;
            insert into @tbl values (@myTargetID)
Finally if 1 is already in use we can search for an ID hole from the start to the random value

        end else begin
            select @myTargetID = isnull(MIN(id) + 1, 0) from @tbl t
            where id < @myRequestID
            and not exists(select * from @tbl innerT where innerT.ID = t.ID + 1)
            if @myTargetID <> 0 begin
                insert into @tbl values (@myTargetID)
            end
        end

If no value was found in the end there is probably no hole available and we have no value to return.
        if @myTargetID = 0 begin
            print 'no value'
        end
    end
(end of the loop)
    set @i = @i + 1;
end

kr, Daniel

Tuesday, February 16, 2016

Closures in JavaScript and C#

Hi,

today I dug deeper into the world of javascript closures and found an interesting mozilla.org -page explaining the topic of closures perfectly. I started getting curious about how implementations like in https://jsfiddle.net/v7gjv/ as described in https://developer.mozilla.org/en/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake could look like in C# and whether the same solutions lead to same success.

The problem depicted in the article referenced above is that a closure was used wrongly inside the method "setupHelp".

1
2
3
4
5
6
  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }

The problem (quote taken over from the article):
The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created, but each one shares the same single environment. By the time the onfocus callbacks are executed, the loop has run its course and the item variable (shared by all three closures) has been left pointing to the last entry in the helpText list.
In the article a solution was provided. They used a function factory method, but I think the following solution is a bit better (even if it is possibly the same thing, but with less code and without the need of jumping around on the screen; the cleanliness of this solution might be doubted, but I do like this version the most):

1
2
3
4
5
6
7
8
9
  for (var i = 0; i < helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      var myItem = item;
      return function() {
       showHelp(myItem.help);
      }
    }();
  }

... here we create an anonymous function on line 3 and call it instantly on line 8 to return an actual event handler (line 5). This function call brings us in a new scope in which we can access the variable from line 2 on line 4 and store it inside of our new scope to use it in line 6 from the event handler.

So... can we have such problems in C#?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    class Program
    {
        class MenuItem
        {
            public event EventHandler<EventArgs> onfocus;
            public void Call_onfocus()
            {
                onfocus(this, EventArgs.Empty);
            }
        }

        static void showHelp(string name, string help)
        {
            Console.WriteLine("{0,7}: {1}", name, help);
        }

        static void Main(string[] args)
        {
            var helpText = new List<Tuple<string, string>>{
                new Tuple<string, string>("email", "Your e-mail address"),
                new Tuple<string, string>("name", "Your full name"),
                new Tuple<string, string>("age", "Your age (you must be over 16)"),
            };

            var document = new Dictionary<string, MenuItem>();
            helpText.ForEach(x => document.Add(x.Item1, new MenuItem()));

            for (var i = 0; i < helpText.Count; i++)
            {
                var item = helpText[i];
                document[item.Item1].onfocus += (sender, e) =>
                {
                    showHelp(item.Item1, item.Item2);
                };
            }
            document.ToList().ForEach(x => x.Value.Call_onfocus());
        }
    }

Unfortunately the version that breaks in javascript works just fine in C#. So I needed to change a bit in the for-loop to demonstrate the problem...

1
2
3
4
5
6
7
            for (var i = 0; i < helpText.Count; i++)
            {
                document[helpText[i].Item1].onfocus += (sender, e) =>
                {
                    showHelp(helpText[i].Item1, helpText[i].Item2);
                };
            }

The for-loop now accesses the array directly and here we are... out-of-range-exception,.. boom... because i is 3 when the Call_onfocus (line 36 in the listing above) calls the event calling showHelp (line 5).

Now we know, that the problem is also a real-world problem in .NET environments. Can we now take over the way to fix the issue in javascript to the C# world? It would be helpful to know one working solution for two (or all kind of) different worlds.

I was able to do so, but I admit the solution is a bit ... let's say: different.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
            for (var i = 0; i < helpText.Count; i++)
            {
                document[helpText[i].Item1].onfocus += (
                    new Func<EventHandler<EventArgs>>(
                        () =>
                        {
                            var myItem = i;
                            return (sender, e) => {
                                showHelp(helpText[myItem].Item1, 
                                         helpText[myItem].Item2);
                            };
                        })());
            }

... as we can see here: I reused the solution of listing #2 and stored the changing value into a newly created scope I created by writing an ad-hoc function I instantly call.

The good things here are that we are not limited to pass in data through event args and minimize the lines of code/number of declared functions, but to be honest I would not recommend to use this kind of hoax too much...

kind regards,
Daniel

Wednesday, February 3, 2016

writing an executable in javascipt

Hi,

today I played around with javascript and its possibilities. To execute js in the browser was a quite non-innovative approach. That windows-8/10 apps can be written in js was also not new to me.The missing element to cover all kinds of applications was the desktop application. After 10 seconds of google-ing I found out that this works too. Even better, it works in combination with the .net framework which opens up a lot of possibilities.

The following code snippets show my test case. The resources I used were: http://www.phpied.com/make-your-javascript-a-windows-exe/ and additionally to check for the ability to use WPF components (yes that works too) https://social.msdn.microsoft.com/Forums/vstudio/en-US/bb41013f-e915-4743-81b0-8bea2d9acebb/jscriptnet-wpf?forum=netfxjscript .

make.bat
@echo off
del program.exe
"c:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc" "program.js"
program.exe

program.js
import System;
import System.Windows.Forms;
function outputMessageBox(text) {
 MessageBox.Show(text, "output message");
};
 
function output(text) {
 Console.Write(text);
};
 
output('hello world');
outputMessageBox('hi');


I am looking forward to find a use case for it :-)

kind regards,
Daniel