Sunday 1 October 2017

Strava open image script

Sometimes I want to download peoples photos from strava.

Click on image to get it full screen

run

$im = $('div[class="photo-slideshow-content"] > image[alt="Photo"]').src
window.open($im)

in console.

Will open the image in a new window so you can download.

Wednesday 20 September 2017

SSRS (2014) Load balancing woes

Symptoms

HTTPS to reporting services only working on prd-web01b, not on 01a.  Checked all  the config etc. and re imported certs from b to a.  SChannell errors were our only clue, although William found some of these on the other server too.  Even rebooted the server for good measure.

How we fixed it

This was the clue - https://support.microsoft.com/en-gb/help/956209/ssl-no-longer-works-after-you-remove-an-ssl-binding-from-sql-server-20

We added the cert into IIS (even though we are running in native mode) , removed it from IIS and rebound it to reporting services and everything now appears ok.

Explanation

Some months ago we upgraded all our certs – I think it was to 2056 bits or such like – as the old ones were becoming invalid.

My theory is on the a server we unbound the old cert – thus removing the crucial registry setting in the above link – and then bound in the new cert.

On the b server we probably just selected the new cert.

I’m not sure who did this work but since a good manager always takes the blame for their teams actions – it was probably me.  (Lesson – sooner we go to scripted deploy the better).

However this did not fix the problem!

2’nd problem

The ever clever mr***suggested looking at the logs – and I found them – FYI there in d:\ Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\LogFiles on our servers.

Found the errors –

library!ReportServer_0-36!1050!09/05/2017-08:54:29:: e ERROR: Error rending control: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

http://go.microsoft.com/fwlink/?LinkID=314055 ---> System.Web.UI.ViewStateException: Invalid viewstate.

                Client IP: *****

                Port: 59222

                User-Agent: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

                ViewState: /wEPDwUKMTEzMjExOTUxNA9kFgQCAQ8WAh4EbGFuZwUFZW4tR0JkAgMPZBYEAgQPZBYEAgEPFgIeBVZhbHVlZGQCAw9kFgJmD2QWAmYPFgIfAWRkAgUPFCsABQ8WCh4UU2hvd1Byb21wdEFyZWFCdXR0b25oHgxTY3JvbGxUYXJnZXRkHhNQcm9tcHRBcmVhQ29sbGFwc2VkZx4QVjFTdHlsZVNoZWV0TmFtZWQeDlJlbmRlcmluZ1N0YXRlCymRAU1pY3Jvc29mdC5SZXBvcnRpbmcuV2ViRm9ybXMuUmVwb3J0UmVuZGVyaW5nU3RhdGUsIFJlcG9ydGluZ1NlcnZpY2VzV2ViU2VydmVyLCBWZXJzaW9uPTEyLjAuMC4wLCBDd

..

How we fixed it

This was easy for a web farm person like me – when you have a .net application  in a web farm you need to add in encryption keys across the farm.

First I checked the instructions as I would have thought that SSRS might do this for me as you actually configure the thing for scale out but MS aren’t that bright – yes you do need to manually put in some keys (https://docs.microsoft.com/en-us/sql/reporting-services/report-server/configure-a-report-server-on-a-network-load-balancing-cluster).

So I generated some for each environment and did this.

Explanation

I always said the old load balancer was not load balancing.  The new ones (F5) are. 

Tuesday 4 July 2017

Import and bind a cert is IIS.

param (
[Parameter(Mandatory=$true)][String]$certpath,
[Parameter(Mandatory=$true)][String]$certpass,
[Parameter(Mandatory=$true)][String]$ip,
[Parameter(Mandatory=$false)][String]$website = "Default Web Site"
)

$mypwd = ConvertTo-SecureString -String $certpass -Force –AsPlainText
$cert  = Import-PfxCertificate -FilePath $certpath Cert:\LocalMachine\My -Password $mypwd -Exportable
$bind = Get-WebBinding -Protocol https -IPAddress $ip  -port 443
if($bind -ne $null) {
    Remove-WebBinding  -Protocol https -IPAddress $ip  -port 443
}

# -Name $website -IPAddress $ip -Protocol HTTPS -Port 443 -HostHeader '' -Binding $ip':433:'
new-WebBinding -Name $website -IPAddress $ip -Protocol https -Port 443 
$bind = Get-WebBinding -Protocol https -IPAddress $ip  -port 443
$bind.AddSslCertificate($cert.GetCertHashString(), "my")
This is for a cert to IP without host header.

Thursday 29 June 2017

Stop, start disable services on multiple machines

$Machines = Get-Content -Path ".\Machines.txt"
$service="Microsoft Deployment Agent"
$credential = Get-Credential
foreach($computer in $Machines) {
    #$result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).stopservice() 
    #$result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).ChangeStartMode("Disabled") 
    $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).startservice()     
    $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).ChangeStartMode("Automatic") 
}
# $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $cred).startservice() 
#Get-Service -Name $Services -ComputerName $Machines -Credential $credential | Set-Service -Status Started -StartupType Automatic 


As usual not really my code but plagiarised. Massive apologies to whoever/wherever I got it as I can’t find it again.  As usual – this is really for me!

The Get-Service /  Set-Service script was the obvious candidate to use but wont take a credential.

Put a list of machines in Machines.txt.

Original that I’ve lost also took a list of services!

Thursday 8 June 2017

Grep for PowerShell

Get-Childitem -Path ".\" web.config -Recurse | Select-String -pattern 'dardaudit' –SimpleMatch

Works for me!

Monday 8 May 2017

Resetting the product.

OK – so my audax applicaiton has not received an update in 4 months and I have just completed the paperwork for the Titanic Torr 2017.

Failed.

Thinking about it on my bike the MVP was far to big.

All I really want is a list of entrants details – that’s the MVP – one page – fill in the form.

To close for the North to the South and only a select few idiots elite riders do this but Antrim 300 will be a target!

WCF endpoints authentiction with HTTP and HTTPS

Add in a new endpoint
<endpoint contract="PortalServices.IMenuService" binding="webHttpBinding" address="restService" behaviorconfiguration="restJsonBehaviour" bindingconfiguration="WindowsHttpBindingHttps" />
With a binding confuguration for https with transport security mode.

<binding name="WindowsHttpBindingHttps">
          <security mode="Transport">
            <!-- Needs to be "TransportCredentialOnly" for Windows and "Transport" for https -->
            <transport clientcredentialtype="Windows" />
          </security>        
        </binding>

Enable https on the binding

<servicemetadata httpgetenabled="true" httpsgetenabled="true" />     

 


    
      
        
      
    
    
    
      
        
        
		
            
    
    
      
        
		     
          
          
        
      
    
    
      
        
          
            
            
          		 
        
		
          
            
            
          		 
        
        
          
            
          
        
      
    
  

Monday 20 March 2017

KTA permissions for service accounts

Don’t ask – but heres a script to set permissions for KTA service accounts to run as non admins.

They also need lon on as service account permissions.

script to grant folder permission from here - http://techibee.com/powershell/grant-fullcontrol-permission-to-usergroup-on-filefolder-using-powershell/2158

param (

       [Parameter(Mandatory=$true)][string]$serviceAccount

) 



function Grant-userFullRights( [string[]]$Files, [string]$UserName) {           
 $rule=new-object System.Security.AccessControl.FileSystemAccessRule($UserName,"FullControl","Allow")            

 foreach($File in $Files) {            
  if(Test-Path $File) {            
   try {            
    $acl = Get-ACL -Path $File -ErrorAction stop            
    $acl.SetAccessRule($rule)            
    Set-ACL -Path $File -ACLObject $acl -ErrorAction stop            
    Write-Host "Successfully set permissions on $File"            
   } catch {            
    Write-Warning "$File : Failed to set perms. Details : $_"            
    Continue            
   }            
  } else {            
   Write-Warning "$File : No such file found"            
   Continue            
  }            
 }            
}
[string]$UserName = $serviceAccount

$Files = @("C:\ProgramData\Kofax\AppLogging\DB", "C:\ProgramData\Kofax Image Products\Local\Scripts")

Grant-userFullRights $Files $UserName
netsh http add urlacl http://+:80/Agility.Sdk.Services.StreamingService user=$UserName
netsh http add urlacl  http://+:3581/SALMetadata/ user=$UserName
netsh http add urlacl  http://+:3581/SAL/ user=$UserName
net stop "TotalAgility Streaming Service"
net start "TotalAgility Streaming Service"
net stop "KSALicenseService"
net start "KSALicenseService"

Tuesday 14 February 2017

Powershell endpoints

For old school .svc and .asmx

foreach($dir in ("dir1",”dir2”)) {
    $files = Get-ChildItem -Path  D:\AppWebSites\$dir -Recurse -Include ('*.asmx','*.svc')
    $files
}

Friday 3 February 2017

Quick event logging guide with MS EL–really for me

CONCEPTS

· Source = Only used by the Machine Event Viewer

· EventId  number that goes in the EventId column of database Log

· TraceEventType (System.Diagnostics.TraceEventType) = a system enum for the log level (info, verbose, error, critical)

PROJECT

We need to add a reference to these:

clip_image002

Config

This page explains it - https://msdn.microsoft.com/en-us/library/ff664760(v=pandp.50).aspx

Where is the tool?

The tool is in tfs - /EnterpriseLibrary5/Bin/EntLibConfig.exe

 

REGISTERING SOURCES FOR EVENTS LOG

If you ever need to register a source (for the Event Log), you run this from PowerShell

New-EventLog -LogName Application -SRC MyNewSource –computername <server>,<other>,<servers,go,here>

Is my source registered?

There’s a way to know what sources has been registered in a machine (see attached).

But it is easier to simply run the previous command to make sure

Monday 30 January 2017

ODBC Settings multuple servers

You need to have some wdac sdk on the server and each machine that you connect to.
$credential = Get-Credential
foreach ($server in @("ESS027521","ESS026412","ESS026488","ESS026191")) {
    $session = New-CimSession -ComputerName $server -Credential $credential
    $odbc = Get-OdbcDsn  -CimSession $session
    $server + ":"
    $odbc        
}

Tuesday 10 January 2017

EF lazy and Eager loading–caught out! (Putting lazy load back on)

I was a bit optimistic in my last post on EF.  Turing off Lazy Loading (removing virtual) on a attribute does NOT imply eager loading.  Documentation is unlcear but confirmed by internet -

“IMPORTANT: You could easily think that, once you disable Lazy Loading, the framework will auto-load each and every related property: it won’t.” - http://www.ryadel.com/en/enable-or-disable-lazyloading-in-entity-framework/

So I’m back to the .Include on each of my get methods to ensure consistency.

Not sure the argument “Don’t worry, it’s a good thing! You don’t want your DB to be automatically wasted on each Entity query request.” isn’t a bit of a cop out.  I want to decide which of my attributes are composite – think car and wheels – and load those all the time.

Of course – I can do this with the .Include but its a bit less explicit.  Making the attribute virtual again will at least means the serialisation falls over if I forgot to include the Lazy Load/Serialisation fails as it’s outside the context – so that at least enforces my aggregate.

Monday 9 January 2017

Hype driven development

Following on from Hype Driven Development (HDD) often implemented in CV++ – here is some more data, frameworks and api’s to consider:

-----Original Message-----

Subject: Amusing and/or point-making links for your arsenal!

http://foaas.com/

http://dayssincelastjavascriptframework.com/

http://www.ismycodeshit.com/

http://shouldiblamecaching.com/

http://vanilla-js.com/

http://shouldiuseacarousel.com/

Sunday 8 January 2017

On EF lazy loading and UML, EF and Serialisation

 

On EF and lazy loading and UML

A good few years ago (back in 2010) I looked at EF and one of my concerns was that you could not control the loading.  A had an object which had a collection of objects – like a car and wheels, and when I fetched the car the framework would not fetch the wheels at the same time – it went and got them one at a time.

This did not appear to be a scalable solution.

This time round things seem a lot better and I have been able to use the techniques here - https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx – to control what gets loaded when.  Seems pretty neat.

I am fairly impressed with this as it allows me to decide what is always “Eagerly” loaded in the class model – what in OO days would have been an composite in my UML model and in the LINQ stuff optionally load the association.

On EF, Normalisation and Serialisation

I am using the EF (code first) objects as my “Business Objects”.  Not sure this has lead to massive time savings over raw ADO.NET as all that annotation is quite a pain.  Yes I could just generate the code (I started like that) but I use some pretty old school naming conventions on my database – Hungarian notation – because I’m old – so attribute names become compromised.

One of my other concerns with EF has been security but I’m assured that LINQ for EF will generate parameterised queries which are good (for security) and meet OWSA

So far I’m fairly happy that my object layer is not too normalised – but I’ve yet to tackle anything too serious – like inheritance and a class comprised of two tables.  Not sure about the former yet but a view will probably help the later.

A couple of things – if you are serialising (to JSON in my case for the service layer) then you need to decide how much of the tree you are bringing back and what you will serialise.

  [Table("tblEvent")]
    [DataContract]
    public partial class Event
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Event()
        {
            tblEventParticipants = new HashSet<tblEventParticipant>();
        }

        [Key]
        [Column("intEventId")]
        [DataMember]
        public int EventId { get; set; }

        [Column("dtePlannedDate")]
        [DataMember()]
        public DateTime PlannedDate { get; set; }

       [Column("dteActualDate ")]
       [DataMember()]
        public DateTime? ActualDate { get; set; }

        [Column("intOrganiserId")]
        [ForeignKey("Organiser")]
        [DataMember()]
        public int? OrganiserId { get; set; }

        [Column("intRouteId")]
        [DataMember()]
        [ForeignKey("Route")]
        public int RouteId { get; set; }

        [DataMember()]
        public tblOrganiser Organiser { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tblEventParticipant> tblEventParticipants { get; set; }

       
        [DataMember()]
        public Route Route { get; set; }
    }

So I’m marking my classes with the  DataContract attribute, marking the members to be serialised with DataMember attribute and making sure they are always loaded by removing the virtual keyword (Eagerly loading) else the serialisation will fail.

One hurdle I’ve yet to cross is that I can see times when I may wish to load and serialise some of the associations – will need to work this through.

Saturday 7 January 2017

On very small tasks

Yes I am still going – and starting to get things done.  Spare time projects are hard to work on because code requires lots of long focus.  But, I’ve found that by really breaking down tasks (I believe they call that pebbleisation) to items taking less than an hour I can quickly pick things up and get something done.  On a full time project you can get the whole thing straight in your head and then go ahead and implement but when there’s days or even weeks between then you need to have really recorded what you were going to do.

 

image_thumb[7]