XML Config to initialize simple string in Unity - unity-container

Newbie Microsoft Unity question.
How do I specify the config to initialize a simple string type.
I'm thinking of the below... but it doesn't like the char[] paramater in the constructor.
<register type="string" name="myString" >
<constructor>
<param name="char[]" value="SomeValue">
</param>
</constructor>
</register>

Why don't inject the URL into the object using it, instead of leaving it to call Resolve?
public interface IMyService {
void DoSomething();
}
public class MyServiceRemote : IMyService {
private readonly _url;
public MyServiceRemote(string url) {
_url = url;
}
public void DoSomething() {
...
}
}
and, in the config:
<register type="IMyService" mapTo="MyServiceRemote" >
<constructor>
<param name="url" value="SomeValue">
</param>
</constructor>
</register>

Related

Is there any way to pass a parameter from web.config to HttpHandler

Is there any way to set the Parameter property from web.config?
public class TestHttpHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public string Parameter
{ get; set; }
public void ProcessRequest(HttpContext context)
{
context.Response.Write(Parameter);
}
}
If i do the following it just crashes.
<handlers>
<add name="Test" verb="*" path="/Manual/*"
type="Test.TestHttpHandler, Test" Parameter="test1234 "/>
</handlers>
Parameter is not a valid attribute for the handlers/add note. Just adding a property with the same name to your handler class doesn't make it magically work.
You can not pass a parameter directly in the handler definition, but within the code of your handler class you have full access to any other configuration data in web.config; any AppSetting or your own ConfigSections.

GetClientValidationRules is never called in MVC application

I have a custom ValidationAttribute that implements IClientValidatable. But the GetClientValidationRules is never called to actually output the validation rules to the client side.
There is nothing special about the attribute but for some reason it is never called. I've tried registering an adapter in Application_Start() but that also doesnt work.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class CustomAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return true;
}
#region IClientValidatable Members
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string errorMessage = FormatErrorMessage(metadata.GetDisplayName());
yield return new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = "custom" };
}
#endregion
}
public class CustomAdapter : DataAnnotationsModelValidator<CustomAttribute>
{
public CustomAdapter(ModelMetadata metadata, ControllerContext context, CustomAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return this.Attribute.GetClientValidationRules(this.Metadata, this.ControllerContext);
}
}
In Application_Start() I have:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomAttribute), typeof(CustomAdapter));
When I put a breakpoint inside GetClientValidationRules it is never hit.
In order GetClientValidationRules() method to get called you must enable client-side validation support. It can be done in the following ways:
In the web.config (for all pages of application):
<appSettings>
<add key="ClientValidationEnabled" value="true" />
Or on particular view only:
either
#{ Html.EnableClientValidation(); }
or
#(ViewContext.ClientValidationEnabled = true)
Please note it must go before
#using (Html.BeginForm())
statement.
If you are using jquery unobtrusive validation (which seems to be a standard currently), you'll also need to enable it:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
in web.config or
#Html.EnableUnobtrusiveJavaScript()
for particular views.

Spring StringTrimmerEditor trim all fields except password field

In registered a StringTrimmerEditor in a Spring controller.
Of course when I now enter a password starting or ending with whitespace it is trimmed as well. But an user doesn't recognize this trimming.
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
}
So is it possible to 'exclude' the password field from trimming.
Should I register a StringTrimmerEditor for each field or just declare password as char[]?
Although this is an old question, if you still get tripped on this then here is how I solved this.
Say we have this form src/main/webapp/view/greet-form.html (I am using Thymeleaf)
<form action="/something" th:attr="action=#{/greet}" method="post" th:object="${student}">
<p><strong>Enter your first name</strong></p>
<p><input type="text" th:field="*{firstName}" th:value="*{firstName}"> <span class="error">*</span><br />
<span class="error_message" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></span></p>
<p><strong>Enter your secret code</strong></p>
<p><input type="text" th:field="*{secretCode}" th:value="*{secretCode}"> <span class="error">*</span><br />
<span class="error_message" th:if="${#fields.hasErrors('secretCode')}" th:errors="*{secretCode}"></span></p>
<p><input type="submit" value="Submit"></p>
</form>
When the form is submitted, we want Spring to trim the value of firstName but leave secretCode as it is.
This is our form backing class, defined in src/main/java/Student.java. The trick is not to use String type for secretCode but some other custom type. This way, StringTrimmerEditor will not be used for the secretCode and the data will not be trimmed.
public class Student {
private String firstName;
private SecretString secretCode;
public Student() {
//
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public SecretString getSecretCode() {
return secretCode;
}
public void setSecretCode(SecretString secretCode) {
this.secretCode = secretCode;
}
}
Here is the definition of SecretString in src/main/java/SecretString.java
public class SecretString {
private String secret;
public SecretString() {
secret = "";
}
public SecretString(String secret) {
//mandatory null check
secret = (secret == null)? "" : secret;
this.secret = secret;
}
#Override
public String toString() {
return secret;
}
}
But now Spring will complain about not being able to convert String to SecretString. This can be solved with a custom property editor or a custom converter (if you are using Spring 3+). I used a custom converter like this.
First define the code in src/main/java/SecretStringConverter.java
import org.springframework.core.convert.converter.Converter;
public class SecretStringConverter implements Converter<String, SecretString> {
#Override
public SecretString convert(String source) {
return new SecretString(source);
}
}
Then register our converter class with a conversion-service factory bean (I am using src/main/webapp/WEB-INF/spring-mvc-demo-servlet.xml)
<context:component-scan base-package="your package" />
<mvc:annotation-driven conversion-service="app_conversion_service"/>
<bean id="app_conversion_service" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="SecretStringConverter"></bean>
</list>
</property>
</bean>
Set password as disallowed field
binder.setDisallowedFields("password");

OSGi Declarative services injection

I am trying to do a simple OSGi service using Declarative Services on a local Glassfish server. The plugin which provides is always active.
I got trouble with the injection into my servlet that consumes my service, the reference is null when the servlet gets called because it isn't the same object that the one which got injected with the service reference.
I tested it by putting a breakpoint into my reference setter, and I saw my service getting injected, but when I click on the button that calls my servlet into my application the service reference is null because it isn't the same object (i.e. gets injected in servlet_Instance #1 but invoke the method on servlet_Instance #2. I must be missing a little detail, because I can find and use my service when doing
final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
loggingTestServiceInterface = (LoggingTestServiceInterface) bundleContext.getService(bundleContext
.getServiceReference(LoggingTestServiceInterface.class.getName()));
The plugin used to generate my XMLs files : maven-scr-plugin
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.14.0</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
<configuration>
<supportedProjectTypes>
<supportedProjectType>war</supportedProjectType>
<supportedProjectType>jar</supportedProjectType>
<supportedProjectType>bundle</supportedProjectType>
</supportedProjectTypes>
</configuration>
</plugin>
This is my service class
#Component(immediate = false, name = "Shikashi", service = {LoggingTestServiceInterface.class}, enabled = true)
public class LoggingTestService implements LoggingTestServiceInterface
{
private final LoggerUtils loggerUtils = new LoggerUtils();
public LoggingTestService()
{
}
#Activate
public void start(final BundleContext bundleContext)
{
System.out.println("StartTest Service Fune");
}
#Deactivate
public void stop()
{
System.out.println("Stop Test Service Jitensha");
}
#Modified
public void modify()
{
System.out.println("Stop Test Service onnanogo");
}
private Logger createLogger(final Class<?> clazz)
{
return Logger.getLogger(clazz);
}
#Override
public void logDebug(final Class<?> clazz, final String message)
{
logDebug(clazz, message, null);
}
#Override
public void logDebug(final Class<?> clazz, final String message, final Throwable throwable)
{
final Logger logger = createLogger(clazz);
logger.debug(message, throwable);
}
}
the generated XML is
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
<scr:component enabled="true" immediate="false" name="Shikashi" activate="start" deactivate="stop" modified="modify">
<implementation class="com.sti.logging.service.LoggingTestService"/>
<service servicefactory="false">
<provide interface="com.sti.loggingservices.serviceinterface.LoggingTestServiceInterface"/>
</service>
</scr:component>
My servlet is
#WebServlet(name = "Wakarimashita", urlPatterns = { "/Wakarimashita"})
#Component
public class Wakarimashita extends HttpServlet
{
private LoggingTestServiceInterface loggingTestServiceInterface;
#Override
protected void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException
{
// Method just to setup the Servlet to understand how it works
final String language = "language";
final String path = "/sigbud/language/";
if (httpServletRequest.getParameter(language) != null)
{
if (httpServletRequest.getParameter(language).equalsIgnoreCase("Nihongo"))
{
httpServletResponse.sendRedirect(path + "nihongo.jsp");
}
else if (httpServletRequest.getParameter(language).equalsIgnoreCase("Eigo"))
{
httpServletResponse.sendRedirect(path + "eigo.jsp");
}
else if (httpServletRequest.getParameter(language).equalsIgnoreCase("Funansugo"))
{
httpServletResponse.sendRedirect(path + "funansugo.jsp");
}
else
{
httpServletResponse.sendRedirect(path + "unknown.jsp");
}
}
else
{
super.doGet(httpServletRequest, httpServletResponse);
}
loggingTestServiceInterface.logError(getClass(), "Wakarimasen");
}
#Reference(service = LoggingTestServiceInterface.class, cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC)
public void bindLoggingTestServiceInterface(final LoggingTestServiceInterface loggingTestServiceInterface)
{
this.loggingTestServiceInterface = loggingTestServiceInterface;
}
public void unbindLoggingTestServiceInterface(final LoggingTestServiceInterface loggingTestServiceInterface)
{
if (this.loggingTestServiceInterface.equals(loggingTestServiceInterface))
{
this.loggingTestServiceInterface = null;
}
}
#Activate
public void start(final BundleContext bundleContext)
{
System.out.println("StartTest Service Taisho");
}
#Deactivate
public void stop()
{
System.out.println("Stop Test Service Fukutaisho");
}
#Modified
public void modify()
{
System.out.println("Stop Test Service san jyû kyû");
}
}
the Generated XML
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
<scr:component name="com.sti.sigbud.servlet.Wakarimashita" activate="start" deactivate="stop" modified="modify">
<implementation class="com.sti.sigbud.servlet.Wakarimashita"/>
<reference name="LoggingTestServiceInterface" interface="com.sti.loggingservices.serviceinterface.LoggingTestServiceInterface" cardinality="1..1" policy="dynamic" bind="bindLoggingTestServiceInterface" unbind="unbindLoggingTestServiceInterface"/>
</scr:component>
Also I tried, but no luck because my servlet doesn't seem to be found (Error 404 - The requested resource () is not available.), to do as Peter Kriens wrote there : How to consume OSGi service from OSGi HTTP Service
So I modified my servlet like so :
#Component(service = Servlet.class, property = {"alias=/Wakarimashita"})
public class Wakarimashita extends HttpServlet
The generated XML is
<?xml version="1.0" encoding="UTF-8"?>
<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0">
<scr:component name="com.sti.sigbud.servlet.Wakarimashita" activate="start" deactivate="stop" modified="modify">
<implementation class="com.sti.sigbud.servlet.Wakarimashita"/>
<service servicefactory="false">
<provide interface="javax.servlet.Servlet"/>
</service>
<property name="alias" value="/Wakarimashita"/>
<reference name="LoggingTestServiceInterface" interface="com.sti.loggingservices.serviceinterface.LoggingTestServiceInterface" cardinality="1..1" policy="dynamic" bind="bindLoggingTestServiceInterface" unbind="unbindLoggingTestServiceInterface"/>
</scr:component>
I access the servlet from my JSP
<form action="Wakarimashita" method="GET">
<input type="text" name="language" size="50"/>
<input type="submit" value="Submit" />
</form>
To test the above I have in my deployed bundles org.apache.felix.http.api-2.2.1, org.apache.felix.http.whiteboard-2.2.1 just as in the post. Didn't find if there is a switch to put on.
Also I checked with org.apache.felix.webconsole-4.2.0-all the bundles, and the service is there up and running, it says that my consumer bundle is using it.
You have two parties creating instances of your servlet. Once is DS and the other is the web container. You cannot have 2 masters. The web container basically has to be in charge since it will only send requests to the instance of your servlet that it creates.
If there was an implementation that supported both web container and DS, then you would be set. But I have never heard of such a thing.
I don't know if Glassfish supports the OSGi Web Application Specification (Ch 128). If it does, then you can interact with the OSGi service layer as described in 128.6.

"The name ProfileCommon does not exist in the current context"

..been browsing the net but no luck.. I need to use the ProfileCommon but I can't reference any assemblies to use it.. can someone help?
When you have an ASP.NET web site, not application project, and make use of Profile the ProfileCommon file gets autogenerated in the temporary ASP.NET files. When you're using an ASP.NET project however you'll need to create that on your own. Take a look at this sample on how to implement it on your own. The sample is for usage in an MVC application project but since that's based on ASP.NET itself the concepts remain the same.
This is a dynamic type generated by the framework.
On runtime the type 'ProfileCommon' exists.
If you can use the C# 4.0 language features you can wrap the behavior of ProfileCommon in a dynamic object.
I have the following extended properties
<profile enabled="true" >
<properties>
<add name="FirstName" type="String" />
<add name="LastName" type="String" />
</properties>
</profile>
The code example to use the dynamic object is
dynamic profile = new ProfileData();
var name = profile.FirstName + ' ' + profile.LastName;
The implementation of ProfileData:
public class ProfileData: DynamicObject
{
private readonly ProfileBase profileBase;
/// <summary>
/// Profile Data for the current user.
/// </summary>
public ProfileData()
{
profileBase = HttpContext.Current.Profile;
}
/// <summary>
/// Profile data for user with name <paramref name="userName"/>
/// </summary>
/// <param name="userName"></param>
public ProfileData(string userName)
{
profileBase = ProfileBase.Create(userName);
}
// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
try
{
result = profileBase.GetPropertyValue(binder.Name);
}
catch(SettingsPropertyNotFoundException)
{
result = null;
return false;
}
return true;
}
// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(SetMemberBinder binder, object value)
{
try
{
profileBase.SetPropertyValue(binder.Name, value);
return true;
}
catch (SettingsPropertyNotFoundException)
{
return false;
}
}
/// <summary>
/// Persist the profile data.
/// </summary>
public void Save()
{
profileBase.Save();
}
}

Resources