Identity Model Claims With XML Characters Within Them - wif

I'd like to do something like
outputIdentity.Claims.Add(new Claim("Claim1", "<test>Hi</test>"))
However the security node within the response header itself shows it as
<Attribute Name="Claim1"><AttributeValue><test>Hi</test></AttributeValue></Attribute>
I know they are reserved XML characters getting translated but can't I specify that I want that node structure in my attribute?
NOTE: I've also tried wrapping it in CDATA however it serializes that tag too. When I replace the translated characters, it works.

Serialization of security tokens is done by the SecurityTokenHandler (in your case probably the Saml11SecurityTokenHandler).
If you want to customize serialization you have to overwrite the default behaviour by extending the Saml11SecurityTokenHandler class:
class CustomHandler : Saml11SecurityTokenHandler
{
public Saml11SecurityTokenHandler()
: base()
{
}
public Saml11SecurityTokenHandler(SamlSecurityTokenRequirement samlSecurityTokenRequirement)
: base(samlSecurityTokenRequirement)
{
}
public Saml11SecurityTokenHandler(XmlNodeList customConfigElements)
: base(customConfigElements)
{
}
protected override void WriteAttribute(XmlWriter writer, SamlAttribute attribute)
{
// your code here
}
}
You also have to add your custom security token handler in the web.config file:
<securityTokenHandlers>
<add type="Your.Namespace.CustomHandler, Your.Dll.Name, Version=1.0.0.0, Culture=neutral" />
</securityTokenHandlers>
EDIT: removed <clear />

Can you try wrapping the value in CDATA section? As:
<![CDATA[<test>Hi</test>]]> Not sure whether your SecurityTokenHandler class will handle that properly, but it's worth a try, and easier than introducing custom handlers.

Related

Can I pass other components into Castle Windsor config?

Lets say I have a main component that I want to initialize in a specific way and I have it's constructor take an Interface for this purpose. Is there a way to define the implementation I want for this interface in my xml and in turn inject that into the main component as a parameter? Like this:
public interface IComponent2 {
void DoStuff();
}
public class ConcreteCompImpl2 : IComponent2 {
IComponent1 _comp;
public ConcreteCompImpl2(IComponent1 comp) {
_comp = comp;
}
public void DoStuff(){
//do stuff
}
}
<component id="component1" service="ABC.IComponent1, ABC" type="ABC.ConcreteCompImpl1, ABC" />
<component id="component2" service="ABC.IComponent2, ABC" type="ABC.ConcreteCompImpl2, ABC" >
<parameters>
<component1>???</component1>
</parameters>
</component>
Or am I thinking about this all wrong and there is a much simpler way to accomplish this? The main thing I want to be able to do is configure what 'kind' of IComponent1 will get injected whenever an IComponent2 is created. Thanks
If you have only one concrete class implementing IComponent1, then it will automatically be injected when you resolve IComponent2.
If you have several classes implementing IComponent1 and want a specific one every time IComponent2 is resolved, you need to specific an inline dependency:
container.Register(
Component.For<IComponent2>()
.ImplementedBy<Component2>()
.DependsOn(Dependency.OnComponent<IComponent1, YourSpecialComponent1>())
);
I'm not completely sure you can specify this in the XML configuration, but honestly you should use the Fluent API instead of the XML configuration unless you have a really compelling reason to use it. As mentioned in the above link:
Ability to register components in XML is mostly a leftover from early days of Windsor before Fluent Registration API was created. It is much less powerful than registration in code and many tasks can be only accomplished from code.

Add Resource Bundles Programmatically

I have a faces-config.xml file with some resource bundles declared, like this:
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>es</supported-locale>
<supported-locale>pt</supported-locale>
<supported-locale>zh</supported-locale>
</locale-config>
<resource-bundle>
<base-name>messages.Messages</base-name>
<var>bundle</var>
</resource-bundle>
<resource-bundle>
<base-name>countries.Countries</base-name>
<var>countryBundle</var>
</resource-bundle>
</application>
</faces-config>
These resource bundles are registered and can be used in any .xhtml file, but is there any way to register these resource bundles programmatically? I mean by the use of dynamic code instead of a xml declaration.
Here's a simplified version of what I'm doing using CDI:
#ApplicationScoped
public class BundleProducer {
#Produce #RequestScoped #Named
public ResourceBundle getMsgBundle() {
Locale userLocale = Faces.getLocale();
return ResourceBundle.getBundle("messages", userLocale);
}
}
Note the use of omnifaces' getLocale() to avoid a ton of boilerplace code (for a less sane version, you can substitute FacesContext.getCurrentInstance().getViewRoot().getLocale() like in the tutorial you linked to).
This will cause the CDI framework to call getMsgBundle once each request if it needs to access to msgBundle thanks to the #Named annotation. In this simple case, I'm relying on the ResourceBundle internal caching and lookup mechanisms to produce my bundle efficiently. You can execute any logic you like here (eg, load stuff from the enclosing BundleProducer) as long as you return a ResourceBundle from the method (you're not allowed to return null).
Repeat as you like with more methods producing different bundles.
Not sure if I got what you were after, so just comment if you need more clarification.
For easier handling of FacesMessage stuff, I'd recommend having a look at omnifaces' Messages utility class. I use something like this to be able to optionally give bundle keys as message strings:
#Singleton
#Startup
public class MessageResolverInit {
#PostConstruct
public void initMessageResolver() {
Messages.setResolver(new Messages.Resolver() {
#Override
public String getMessage(String message, Object... params) {
Locale userLocale = Faces.getLocale();
ResourceBundle b = ResourceBundle.getBundle("msgs", userLocale);
if (b.containsKey(message)) {
return MessageFormat.format(b.getString(message), params);
}
return message;
}
});
}
Note that I use b as a variable name only for demo purposes. Usage goes like this:
Messages.addGlobalError("my_msg_key", param1);
Messages.addGlobalInfo("I'm a standalone message");
Here is the answer from Oracle documentation: Using FacesMessage to Create a Message

Print inner text of a HtmlContent in a razor view (MVC4)

Using MVC, look at this example where we have the following HTML code:
<p>Duma</p><img url='..' /><p>Duma</p>
I would like that print only the content of the tags, as: Duma Duma, removing the image, tags and showing only the text (as innerText)
I tried using Html.Raw() but it's not worked. Also I was reading about the class TabBuilder and creating a Html extension method, but I don't have idea about how to implemeted in my razor view.
You could make a string extension to strip the Html tags.
public static class StringExtensions
{
public static string StripHtml (this string inputString)
{
return Regex.Replace
(inputString, "<.*?>", string.Empty);
}
}
Then use it in your view
#myHtmlString.StripHtml()
You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder
#using My.Extensions.Namespace
OR
<system.web>
<pages>
<namespaces>
<add namespace="My.Extensions.Namespace" />
</namespaces>
</pages>
</system.web>
You could also make a Html Helper Extension
public static class HtmlExtensions
{
public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
{
return Regex.Replace
(htmlString, "<.*?>", string.Empty);
}
}
You can use this in your view like this
#Html.StripHtml(myHtmlString)
You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement.

ConfigurationSettings.AppSettings is empty, throws null exception

I have a class like this:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder { get { return ConfigurationSettings.AppSettings["rootFolder"].ToString(); } }
}
When I try to use it like this:
public class TestRxNormFolderManager : ColumnFixture
{
public string RxNormFolder()
{
RxNormFolderMgr folderMgr = new RxNormFolderMgr();
return folderMgr.RxNormFolder;
}
}
I get an error: "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object." The AllKeys property for AppSettings is an array of zero length where I am expecting length of 1.
My app.config file in the project looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="rootFolder" value ="C:\RxNorm" />
<!-- Root folder must not end with slash. -->
</appSettings>
</configuration>
I know ConfigurationSettings.AppSettings is supposed to be obsolete and I should use ConfigurationManager.AppSettings, but I can't even get that to compile. I do have a reference in the project to System.configuration (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll on my machine) and using statement at top of my code.
I am using Fitnesse to test the code, and that's when I get the error. It's my understanding that I should also place a copy of the app.config file in the Bin>Debug folder of the test fixtures project which I have done. So, I don't know why I'm getting this error still.
Please, help.
Also: try using the ConfigurationManager class instead of "ConfigurationSettings":
Use a check for NOT NULL first:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder
{
get
{
if(ConfigurationManager.AppSettings["rootFolder"] != null)
{
return ConfigurationManager.AppSettings["rootFolder"].ToString();
}
return string.Empty;
}
}
}
Is this inside a class library assembly? Those never use their own app.config - but instead the use the host app's app.config (the app that uses the class library).
Marc
When you are testing with FitNesse, the actual executable running is "FitServer.exe" so AppSettings is looking for a "FitServer.exe.config" in the directory with FitServer.exe lives. So a quick and dirty solution is to copy your app.config there and rename it.
A better solution is to specify the app config as described here:
http://www.syterra.com/FitnesseDotNet/ApplicationConfigurationFile.html
or if you're using fitSharp (which is an enhancement of FitNesse.NET):
http://www.syterra.com/Fit/AppConfigFiles.html
Do not put it in appsettings. Use <connectionStrings>
example:
<appSettings/>
<connectionStrings>
<add name="NORTHWNDConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
string cnstr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ToString();

Primitive types and IoC containers

How do you handle primitive types when using a IoC container?
I.e. given that you have:
class Pinger {
private int timeout;
private string targetMachine;
public Pinger(int timeout, string targetMachine) {
this.timeout = timeout;
this.targetMachine = targetMachine;
}
public void CheckPing() {
...
}
}
How would you obtain the int and string constructor arguments?
Make another interface for this.
Then you will get something like:
public Pinger(IExtraConfiguration extraConfig)
{
timeout = extraconfig.TimeOut;
targetmachine = extraconfig.TargetMachine;
}
I don't know about other IOC containers, but Castle Windsor resolves these extra constructor parameters automatically.
I'm not sure if your difficulty is the value types or the concrete type. Neither is a problem. You don't need to introduce a configuration interface (it's useful if you want to pass the same parameters to multiple objects, but not in the case you've given). Anyway, here's the Windsor fluent code, I'm sure someone will submit an XML version soon.
container.Register(
Component.For(typeof(Pinger))
.ImplementedBy(typeof(Pinger)) // This might not be necessary
.Parameters(Parameter.ForKey("timeout").Eq("5000"),
Parameter.ForKey("targetMachine").Eq("machine")
)
);
It depends. The IoC-Container StructureMap will allow you to declare those dependencies when you configure the instance at the beginning of your execution.
e.g. in a registry
ForRequestedType<Pinger>()
.TheDefault.Is.OfConcreteType<Pinger>()
.WithCtorArg("timeout").EqualTo(5000)
.WithCtorArg("targetMachine").EqualToAppSetting("machine");
In Spring, one can look up property values from a property file using ${propertyName} notation
<bean class="blah.Pinger">
<constructor-arg value="${blah.timeout}"/>
<constructor-arg value="${blah.targetMachine}"/>
</bean>
In Spring.net the same functionality is provided by the PropertyPlaceholderConfigurer, which has the same syntax, and uses name value sections in config files.

Resources