Dailycode.info

Short solution for short problems

Microsoft Update Standalone Package wont run.

I was installing a standalone package as preparation for a SharePoint installation. But it kept giving the error that the service was not started.

I found out that I had to start the windows update service in order to get this working.

After the installation was done, I disabled the windows update again.


Oracle: Concatinate columns in a group by function

I wanted to concatinate information of a column into a ; seperated column in a group by.

eg

Projectmanagerdepartmentcustomer
1MarkABDO
2PietBBDO
3StevenAMicrosoft
I want to count the number of project for each customer and see which managers and departments there are.

With a LISTAGG function this works

SELECT

count(Project) as nr, LISTAGG(manager, ' ') WITHIN GROUP (order by manager) as managers 

FROM table 

GROUP BY customer

ORDER BY customer


result will be

2            Mark;Piet            BDO

1            Steven                Microsoft


IIS: What triggers recycle of a website in IIS?

A colleague and me where thinking about this, because we were copying files to the root directory of the web site. But no worries, this doesn't trigger a recycle. What does trigger a recycle?


Trigger Immediate Recycle

  • Web.config changes
  • Machine.config changes
  • Global.asax changes
  • Bin directory changes
  • App_Code changes

Get String from Excel with DocumentFormat.OpenXml (v2.5.5631.0)

Getting a value from a cell is very easy with the openxml library. But getting a string value isn't that straight forward. You will have to use the SharedStringTablePart. More info on this here: https://msdn.microsoft.com/en-us/library/office/gg278314.aspx

In this example I want to get the value from cell A2 on a worksheet in the excel called test:

Using doc As SpreadsheetDocument = SpreadsheetDocument.Open(localExcel, False)
 Dim workbookPart As WorkbookPart
workbookPart = doc.WorkbookPart
Dim stringTable = workbookPart.GetPartsOfType(Of SharedStringTablePart).FirstOrDefault()
Dim clientSheet As Sheet = doc.WorkbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) s.Name.ToString.ToLower = "test").FirstOrDefault
Dim worksheetPart As WorksheetPart = CType(workbookPart.GetPartById(clientSheet.Id),WorksheetPart)
 
Dim value As String = GetCellValue(stringTable, worksheetPart, "A2")
If Not value = "" Then
clientNumber = value
End If
End Using

Now the GetCellValue will get the string from the sharedStringTable. The index of the string can be found in the theCell.Cellvalue.Text:

Public Function GetCellValue(ByVal stringTable As SharedStringTablePart,ByVal worksheetPart As WorksheetPart,
ByVal addressName As String) As String
Dim value As String = Nothing
 Dim theCell As Cell = worksheetPart.Worksheet.Descendants(Of Cell).Where(Function(c) c.CellReference = addressName).FirstOrDefault
 
 If theCell IsNot Nothing Then
  If theCell.DataType IsNot Nothing Then
Select Case theCell.DataType.Value
     Case CellValues.SharedString
Dim index = Integer.Parse(theCell.CellValue.Text)
      If stringTable IsNot Nothing Then
       value = stringTable.SharedStringTable.ElementAt(index).InnerText
      End If
Case Else
      value = theCell.InnerText
    End Select
   End If
  End If
  Return value
End Function


AngluarJS: Connect to a WebAPI using windows credentials and CORS

First sight this looked very easy. Just put the authentication on your web site to windows authentication. That's it! Or NOT? I kept getting an unauthorized error. So I discovered that I needed to add the withCredentials: true to the get request. 

Now the request looks like this:

var cf = headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
            };
$http.get(APIurl.qarAPI + 'qar/getUser', { withCredentials: true, cf })
    .success(function (data) {
        $rootScope.user = data;
    })
    .error(function (data, status) {
        console.error(JSON.stringify(data));
    });

Now the error message changed into this one:

Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.

 This looked like a good exception that I would google in a minute. But it took some more time. The reason was because the problem was not on the web side, but on the .Net Web Api side. Eventually, I discovered that I needed to add this to the configuration of CORS on the web API:

config.EnableCors(new EnableCorsAttribute("http://localhost:101", "*", "GET, POST, OPTIONS, PUT, DELETE") { SupportsCredentials = true });

When I added this, user credentials are supported in the request and it works. My API call now needly gets the credentials of the windows user that made the request!

[HttpGet, Route("getUser")]
public HttpResponseMessage Get()
{
var identy = this.User.Identity;
 var resp = identy.Name;
 return Request.CreateResponse(HttpStatusCode.OK, resp);
}



AngularJS : Loving it

If made several apps in Angular, but this one is the first I finished completely and which I really like.

Its a card game helper for whist and another. In phase 2 I will try to implement translations, but I'm not sure if I will use an open source solution or develop one myself, because I have some ideas around this involving IndexDB.



AngularJS: Single quotes in a directive template and method binding inside ng-repeat. (all in 1)

I have a directive that creates a button inside a ng-repeat. The button has a ng-click and also ng-class attribute where the class is set based on a value of the model. the ng-click calls a function on the scope of the parent controller and is passed by an attribute to the scope of the directive.

So the HTML code looks like this:

<div class="panel-body" data-ng-repeat="player in players">
    <div player-button="player" on-click="selectPlayer(player)" ></div>
</div>

And the directive looks like this:

.directive('playerButton', function() {
    return {
        scope: { player: '=playerButton', onClick: '&' },
        template: '<button class="btn btn-default input-block-level form-control" ng-click="onClick({player : player})" ng-class="{true : \'btn btn-primary input-block-level form-control\', false : \'btn btn-default input-block-level form-control\' }[player.number > 0]"><div ng-if="player.number != 0" class="label label-info">{{player.number}}</div>&nbsp;{{player.text}}</button>',
    }
})

You see that I had to escape the ' with \' inside the ng-class attribute. I also bind the selectedPlayer(player) to the onClick and pass this. The player from the scope is used because its inside the ng-repeat and it cannot be just the player from the parent scope.



AngularJS: Directive that show the number in red if < 0, green > 0 and black == 0

I have a game where scores are shown in multiple places. The score text should turn red when the score is below zero, green when the score is positive and black when the score is 0. 

Directives make this very easy. 

This directive does the trick:

.directive('valueColor', [
function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs) {

            scope.$watch(attrs.ngModel, function (newValue)
            {
                console.log(newValue);
                var test = parseInt(newValue);

                if (test > 0) {
                    element.css('color', 'green');
                }
                else if (test < 0) {
                    element.css('color', 'red');
                }
                else if (test == 0) {
                    element.css('color', 'black');
                }
                else { console.log('Nan value: ',test);}
            });
        }
    }
}
])

So based on the ng-model value, I change the color of the containing text. The html code only shows this:

<tr class="row">
    <td class="col-md-2">Totaal</td>
    <td class="col-md-2">
        <h3 value-color ng-model="player1.total">{{player1.total}}</h3>
    </td>
    <td class="col-md-2">
        <h3 value-color ng-model="player2.total">{{player2.total}}</h3>
    </td>
    <td class="col-md-2">
        <h3 value-color ng-model="player3.total">{{player3.total}}</h3>
    </td>
    <td class="col-md-2">
        <h3 value-color ng-model="player4.total">{{player4.total}}</h3>
    </td>
</tr>

So you add the directive value-color and the ng-model to the DOM element and it works.

Using directives can clean up your code and improve the maintainability of your app! If I want to do something different with the score, it is very likely that I only have to change the directive and everywhere this change is applied.



AngularJS: Access rootScope in Directive

I made a directive that based on a model change would need do do some calculations on an object on the root scope.

So to access the rootScope, simply use this:

scope.$root.

Then you can access any object in the rootScope. Very powerfull!

Here's the complete directive I've written. This will calculate for a row if the total is not higher then a 'attubute set' number, of higer or some input is not a number, then the row ill appear in red. If lower, then the row will stay white, if equal, it will turn green.

.directive('maxRowValue', [
function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            scope.$watch(function () {
                return ngModel.$modelValue;
            }, function (newValue) {

                var totalRow = 0;
                var goOn = true;
                for (var i = 0 ; i < 4; i++) {
                    if (!isNaN(parseInt(scope.$root.game.scores[attrs.rowNumber][i]))) {
                        totalRow += parseInt(scope.$root.game.scores[attrs.rowNumber][i]);
                    }
                    else {
                        console.log('Nan value inserted');
                        goOn = false;
                        break;
                    }
                }

                if (goOn == true && totalRow < attrs.rowValue)
                {
                    console.log('OK');
                    element.css('background', 'white');
                }
                else if (goOn == true && totalRow == attrs.rowValue)
                {
                    console.log('Complete');
                    element.css('background', 'green');
                }
                else
                {
                    console.log('Row values not correct');
                    element.css('background', 'red');
                }
            });
        }
    }
}
])

So this works nice, you can check this working at my new project DailyCardGames.

Just to show here's a screen shot:



AngularJS: Set ng-style text decoration

I was trying to set the text decoration from the controller to underlined or none, depending on some scope variable.

<row ng-style="{text-decoration: player1.turn}"><h2>{{player1.text}}</h2></row>

But first I got some errors: Error: [$parse:syntax] Syntax Error: Token '-' is unexpected, expecting [:] at column 6 of the expression [{text-decoration:

 Now I found why:

<row ng-style="{'text-decoration': player1.turn}"><h2>{{player1.text}}</h2></row>

I needed to put text-decoration between quotes. player.turn can hold none, underlined or any other decoration.