Hot to implement wcf client with ws-security with timestamp, username, encrypt and signature? - wcf-client

I try to write wcf client of java server with WS-Security specifications. Is there any way to implement the client programatically in C# with the order I give at the question (timestamp, username, encrypt and signature)

Well is hard to tell by your post what will be your corresponding setup. Here you have the config I use to consume a java web service that use ws-security. In my case i was provided with a client certificate and for the service i exported and install the certificate from the service's site.
For the several gotchas you for sure will have, refer to this site
In the following replace xx with your the certificates Thumbprint.
Let us know your progress.
<system.serviceModel>
<bindings>
<customBinding>
<binding name="MyBindingName" >
<textMessageEncoding messageVersion="Soap11"/>
<security authenticationMode="MutualCertificate" enableUnsecuredResponse="true" allowSerializedSigningTokenOnReply="true"
messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
includeTimestamp="true">
</security>
<httpsTransport />
</binding>
</customBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<clientCredentials>
<clientCertificate findValue="xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx"
storeLocation="CurrentUser" storeName="My"
x509FindType="FindByThumbprint" />
<serviceCertificate>
<defaultCertificate findValue="xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx"
storeLocation="CurrentUser" storeName="My"
x509FindType="FindByThumbprint"/>
<authentication />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://YOURSERVICE_ADDRESS"
binding="customBinding" bindingConfiguration="MyBindingName"
contract="srvContract" name="srvContract" behaviorConfiguration="ClientCertificateBehavior">
</endpoint>
</client>
</system.serviceModel>

Related

Parsing XML for sub children using using python

I am trying to parse the below XML to get the following data. There are multiple rules following, I have shared only one rule below. Is it possible to parse the XML for these values?
name from section header, rule id value, applied-to name, source names, source values, destination name, destination value.
<?xml version="1.0" encoding="UTF-8"?>
<filteredfirewallConfiguration timestamp="1621338984151">
<contextId>globalroot</contextId>
<layer3Sections>
<section id="asdfsdf" name="production" generationNumber="132" timestamp="1621930404081" managedBy="universalroot-0" tcpStrict="false" stateless="false" useSid="false" type="LAYER3">
<rule id="1213213" disabled="false" logged="true" managedBy="universalroot-0">
<name>From Conversion Server</name>
<action>allow</action>
<appliedToList>
<appliedTo>
<name>re-int-dx</name>
<value>universalwire</value>
<type>VirtualWire</type>
<isValid>true</isValid>
</appliedTo>
<appliedTo>
<name>re-ext-ap</name>
<value>universalwire</value>
<type>VirtualWire</type>
<isValid>true</isValid>
</appliedTo>
</appliedToList>
<sectionId>sfsdfafee</sectionId>
<sources excluded="false">
<source>
<name>sdfsdf101</name>
<value>ipset-werfwefdc</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
<source>
<name>sdfsfdf102</name>
<value>ipset-4wsetgfreds</value>
<type>IPSet</type>
<isValid>true</isValid>
</source>
</sources>
<destinations excluded="false">
<destination>
<name>production-database-cluster</name>
<value>sg</value>
<type>SecurityGroup</type>
<isValid>true</isValid>
</destination>
<destination>
<name>newname</name>
<value></value>
<type>IPSet</type>
<isValid>true</isValid>
</destination>
</destinations>
<services>
<service>
<name>servicenwe</name>
<value>application-dgfsdfg</value>
<type>Application</type>
<isValid>true</isValid>
</service>
</services>
<direction>inout</direction>
<packetType>any</packetType>
</rule>
sofar, I have been able to get the section header only.
import requests
import xml.etree.ElementTree as ET
tree = ET.parse("out.xml")
root = tree.getroot()
for child in root.find('./layer3Sections'):
print(child.tag, child.attrib)

Powershell command -- To add a attribute if not exist in a particular node of a XML

<APPPOOL APPPOOL.NAME="Classic" RuntimeVersion="v2.0" state="Started">
<add name="Classic" autoStart="true" managedRuntimeVersion="v2.0">
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet" autoStart="true">
my file has many line begining with word "add name".
I want to check if these lines have a string "managedRuntimeVersion".
if not exists, then i need to add managedRuntimeVersion="v2.0" to
that line.
Expected Result as below
<APPPOOL APPPOOL.NAME="Classic" RuntimeVersion="v2.0" state="Started">
<add name="Classic" autoStart="true" managedRuntimeVersion="v2.0">
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet" autoStart="true" managedRuntimeVersion="v2.0">
I have tried with the below script.. but in the result.. it is given only the lines having "add name"
$sfile="C:\Users\subash.s\Desktop\backup\pool.xml"
(((gc "$sfile") | Select-String -Pattern "add name" |
select-string -notmatch "managedRuntimeVersion") -replace '>',' managedRuntimeVersion="v2.0">') |
Set-Content "$sfile"
with the above script. i got below result..
<add name="Classic" autoStart="true" managedRuntimeVersion="v2.0">
<add name="GetServiceDet" autoStart="true" managedRuntimeVersion="v2.0">
For Pete's sake, the configuration file is XML, not a text file! Edit it as an XML document, and you will save a lot of headaches.
There are a few ways to add attributes into such a document. As the XML in the question is a fragment - and of illegal syntax, the sample code uses a bit modified version of the same. Select all add nodes that don't have got managedRuntimeVersion attribute, create one and add attribute with values to the nodes. Like so,
# Dummy data for testing
[xml]$x = #'
<root>
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet2" autoStart="true"/>
</APPPOOL>
<APPPOOL APPPOOL.NAME="Classic" RuntimeVersion="v2.0" state="Started">
<add name="Classic" autoStart="true" managedRuntimeVersion="v2.0" />
</APPPOOL>
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet" autoStart="true"/>
</APPPOOL>
</root>
'#
# Select all add elements that don't have managedRuntimeVersion attribute
$nl=$x.SelectNodes('/root/APPPOOL/add[not(#managedRuntimeVersion)]')
# Add attributes to the elements
foreach($n in $nl) {
# Create new attribute and assign a value
$a = $x.CreateAttribute('managedRuntimeVersion')
$a.Value = 'v2.0'
[void]$n.Attributes.Append($a)
}
# Print modified version to console
$x.save([console]::out)
# Output
<?xml version="1.0" encoding="ibm850"?>
<root>
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet2" autoStart="true" />
</APPPOOL>
<APPPOOL APPPOOL.NAME="Classic" RuntimeVersion="v2.0" state="Started">
<add name="Classic" autoStart="true" managedRuntimeVersion="v2.0" />
</APPPOOL>
<APPPOOL APPPOOL.NAME="GetServiceDet" RuntimeVersion="v2.0" state="Started">
<add name="GetServiceDet" autoStart="true" managedRuntimeVersion="v2.0" />
</APPPOOL>
</root>
Reading the actual file and saving changes to disk are left as an exercise to the reader.

Replacing dynamic variables using REGEX content as variable in Azure CD Pipeline Powershell Task

I'm writing custom Powershell Azure CD Pipeline task(for VM) where my web.config should be replaced with pipeline variables. I have sample config file as with WebService and AuditService defined in my Azure CD pipeline variables.
<client>
<endpoint address="__WebService__" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
<endpoint address="__AuditService__" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
</client>
I have powershell script as
$zipfileName = "$(System.DefaultWorkingDirectory)\_WebService-CI\drop\Service.zip"
$fileToEdit = "web.config"
$reg = [regex] '__(.*?)__'
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
# Open zip and find the particular file (assumes only one inside the Zip file)
$zip = [System.IO.Compression.ZipFile]::Open($zipfileName,"Update")
$configFile = $zip.Entries.Where({$_.name -like $fileToEdit})
# Read the contents of the file
$desiredFile = [System.IO.StreamReader]($configFile).Open()
$text = $desiredFile.ReadToEnd()
$desiredFile.Close()
$desiredFile.Dispose()
$text = $text -replace $reg, $(${1}) -join "`r`n"
#update file with new content
$desiredFile = [System.IO.StreamWriter]($configFile).Open()
$desiredFile.BaseStream.SetLength(0)
# Insert the $text to the file and close
$desiredFile.Write($text)
$desiredFile.Flush()
$desiredFile.Close()
# Write the changes and close the zip file
$zip.Dispose()
So how do I can replace dynamically Regex content within "__" and treat that content as a variable which should look into pipeline variables and replace it in line :
$text = $text -replace $reg, $(${1}) -join "rn"
If you can't use Replace Tokens or Transform Web.config file, here is something :
According to the fact that web.config file contains :
<?xml version="1.0" encoding="utf-8"?>
<!--
For ...
-->
<configuration>
..
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="checkVatBinding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="__WebService__" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
<endpoint address="__AuditService__" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
</client>
</system.serviceModel>
</configuration>
You can try the following :
# Get all the file in a single var in spite of an array
$data = Get-Content "D:\temp\web.config" -raw
$reg = [Regex]::new( '__(.*?)__', [System.Text.RegularExpressions.RegexOptions]::Singleline)
# Here are the vars with the final values
$WebService = "http://Aurillac.fr"
$AuditService = "http://Cantal.fr"
# Here is how to replace
$reg.replace($data, {param ($p);return (Get-Variable -Name $p.groups[1]).Value})
Explanations :
The -raw in Get-Content allows to get all the characters in a single string
I use the .NET RegEx class with the option Singleline to allow search accross cariage return line feed (perhaps not necessary)
I use the Regex Replace method with a MatchEvaluator Delegate method translated in PowerShell by a Scriptblock to get the variable with the name catched by the RegEx.
It gives :
<?xml version="1.0" encoding="utf-8"?>
<!--
For ...
-->
<configuration>
..
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="checkVatBinding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://Aurillac.fr" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="WebServiceClient.ServiceSoap" name="NLSService" />
<endpoint address="http://Cantal.fr" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Audit" contract="AuditApiService.Audit" name="AuditService" />
</client>
</system.serviceModel>
</configuration>
Is there any reason you can't use the Replace Tokens task from the marketplace? This is my go-to for replacing values in config files.
https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens

Excel - How to map XML cells and add a space in between cells

I have an Excel Spreadsheet that I am trying to map the X and Y Values and add a blank cell in between.
My current setup is:
<Override>
<Area>
<Poly>
<Point x="10590.0" y="14850.0" />
<Point x="11000.0" y="15120.0" />
<Point x="11020.0" y="15100.0" />
<Point x="10590.0" y="14810.0" />
</Poly>
</Area>
<Area>
<Poly>
<Point x="11000.0" y="15120.0" />
<Point x="11030.0" y="15140.0" />
<Point x="11045.0" y="15120.0" />
<Point x="11020.0" y="15100.0" />
</Poly>
</Area>
And I want Excel, when I Import it, to do this:
X | Y
10590 | 14850
11000 | 15120
11020 | 14810
10590 | 14810
*This is a blank cell area*
11000 | 15120
11030 | 15140
11045 | 15120
11020 | 15100
*Space between Poly Data, I need Spaces*

Cruise Control.Net 1.5 + Visual Source Safe + MSBuild.exe

I am trying Cruise Control.net 1.5 integrate to Visual Source Safe.
Could any one share with me step by step (configuration for Build+Email+Triggers+Publish)to do cruise control.net with Visual Source safe.
Thanks in advance...
Have you looked at "How to Hook Up a VS.NET 2005 Solution with CruiseControl.NET in a few minutes." ?
The configuration file (for vss) looks like this:
<cruisecontrol>
<project name="Johans Test System">
<sourcecontrol type="vss" autoGetSource="true" applyLabel="true">
<executable>C:\Program Files\Microsoft Visual SourceSafe\ss.exe</executable>
<project>$/JohansTestSystem.root</project>
<username>Johan</username>
<password></password>
<ssdir>c:\vss\</ssdir>
<workingDirectory>C:\CI\</workingDirectory>
<cleanCopy>true</cleanCopy>
</sourcecontrol>
<triggers>
<intervalTrigger seconds="60" />
</triggers>
<tasks>
<msbuild>
<executable>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe</executable>
<workingDirectory>c:\CI\JohansTestSystem</workingDirectory>
<projectFile>JohansTestSystem.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
<targets>Build</targets>
<timeout>15</timeout>
<logger>ThoughtWorks.CruiseControl.MsBuild.XmlLogger,ThoughtWorks.CruiseControl.MsBuild.dll</logger>
</msbuild>
<nunit path="C:\nunit\bin\nunit-console.exe">
<assemblies>
<assembly>C:\CI\JohansTestSystem\Johan.Test\bin\Debug\Johan.Test.dll</assembly>
</assemblies>
</nunit>
</tasks>
<publishers>
<xmllogger />
</publishers>
</project>
</cruisecontrol>
Email blocks documentation is pretty straightforward.
Here is CruiseControl.NET's example:
1<email mailport="25" includeDetails="TRUE" mailhostUsername="smtpuser" mailhostPassword="smtppassword" useSSL="FALSE">
2 <from>buildmaster#mycompany.com</from>
3 <mailhost>smtp.mycompany.com</mailhost>
4 <users>
5 <user name="BuildGuru" group="buildmaster" address="buildguru#mycompany.com" />
6 <user name="JoeDeveloper" group="developers" address="joedeveloper#thoughtworks.com" />
7 </users>
8 <groups>
9 <group name="developers">
10 <notifications>
11 <notificationType>Failed</notificationType>
12 <notificationType>Fixed</notificationType>
13 </notifications>
14 </group>
15 <group name="buildmaster">
16 <notifications>
17 <notificationType>Always</notificationType>
18 </notifications>
19 </group>
20 </groups>
21 <converters>
22 <regexConverter find="$" replace="#TheCompany.com" />
23 </converters>
24 <modifierNotificationTypes>
25 <NotificationType>Failed</NotificationType>
26 <NotificationType>Fixed</NotificationType>
27 </modifierNotificationTypes>
28 <subjectSettings>
29 <subject buildResult="StillBroken" value="Build is still broken for {CCNetProject}" />
30 </subjectSettings>
31 <xslFiles>
32 <file>xsl\header.xsl</file>
33 <file>xsl\compile.xsl</file>
34 <file>xsl\unittests.xsl</file>
35 <file>xsl\modifications.xsl</file>
36 </xslFiles>
37 <attachments>
38 <file>C:\Data\AFile.txt</file>
39 <file>Relative.txt</file>
40 </attachments>
41</email>
and of course if you want to send via gmail, that's cool too:
GMail For sending mail via gmail :
* mailhost="smtp.gmail.com"
* mailport="587"
* mailhostUsername="xxx.yyy#gmail.com"
* mailhostPassword="yourpassword"
* useSSL="TRUE"
You should probably also check out this SO thread about CC.NET email publishing:

Resources