is it possible to resolve objects which use generics in unity only using interfaces.
class
public interface ItestObject<T>{ T Create();}
public class testObject<T> : ItestObject<T> where T: class, ICMSBasicTextData, new()
{
public testObject(){}
public T Create()
{
return new T();
}
}
xml config
<alias alias="testObject_I" type="JMJoinery.ItestObject`1, JMJoinery" />
<alias alias="testObject_C" type="JMJoinery.testObject`1[[JMJoinery.CMS.Data.CMSBasicTextData, JMJoinery]], JMJoinery" />
<alias alias="CMSBasicTextData_I" type="JMJoinery.CMS.Data.ICMSBasicTextData, JMJoinery" />
<alias alias="CMSBasicTextData_C" type="JMJoinery.CMS.Data.CMSBasicTextData, JMJoinery" />
<register name="CMSBasicTextData_R" type="CMSBasicTextData_I" mapTo="CMSBasicTextData_C" />
<register name="test" type="testObject_I" mapTo="testObject_C" />
when i try to resolve:
var o2 = JMJoinery.Global.Container.Resolve<ItestObject<ICMSBasicTextData>>();
this error occurs:
"Unable to cast object of type 'JMJoinery.testObject1[JMJoinery.CMS.Data.CMSBasicTextData]' to type 'JMJoinery.ItestObject1[JMJoinery.CMS.Data.ICMSBasicTextData]'."
Using
Container.Resolve<ItestObject<CMSBasicTextData>>();
works, but is it possible to resolve using the interface only
Container.Resolve<ItestObject<ICMSBasicTextData>>();
instead?
Interface and Implementation
public interface ILookupDataReader<T>
{
string LookupTypeID { get; }
}
public class CountryDataReader: ILookupDataReader<ICountry>
{
string ILookupDataReader<ICountry>.LookupTypeID
{
get { return Enum.GetName(typeof(LookupTypeOptions), LookupTypeOptions.Country); }
}
}
Registration
<alias alias="ILookupDataReader" type="Co.Application.Shared.Core.BusinessObject.ILookupDataReader`1,Co.Shared.Impl"/>
<alias alias="ICountry" type="Co.Application.Shared.Core.BusinessObject.Lookup.ICountry, Co.Shared.Impl"/>
<register type="ILookupDataReader[ICountry]" mapTo="Co.Application.Shared.Core.BusinessObject.Lookup.CountryDataReader,Co.Shared.Impl">
<lifetime type="singleton"/>
</register>
Usage
[Dependency]
public ILookupDataReader<ICountry> CountryLookup { get; set; }
Related
I've tried resolving this from answers in other and similar posts, but no luck.
I'm Using MVC 5, framework 4.8 latest VS2017.
Thanks
My Config is: (including other attempts)
<configuration>
<appSettings>
<!--<add key="owin:AutomaticAppStartup" value="false" />-->
<add key="owin:HandleAllRequests" value="true"/>
<!--<add key="owin:AppStartup" value="Api.xxx" />-->
</appSettings>
</configuration>
Startup class is:
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
namespace Api.xxx
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Allow all origins
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
….
}
}
}
and Api is:
namespace Api.xxx
{
[Route("values")]
public class ValuesController : ApiController
{
private static readonly Random _random = new Random();
public IEnumerable<string> Get()
{
var random = new Random();
return new[]
{
_random.Next(0, 10).ToString(),
_random.Next(0, 10).ToString()
};
}
}
}
I think you need to change
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
to
[assembly: OwinStartup(typeof(Api.xxx.Startup))]
Reference: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection
I am using a java object which should return me an endpoint, then I want to invoke a service hosted at the specified endpoint. Please assist.
Below is my effort
In mule.xml
<spring:beans>
<spring:bean id="reqUrl" class="com.mule.sbus.drools.RequestUrl"
scope="singleton" />
</spring:beans>
<bpm:drools />
<http:listener-config name="NorthboundSingleEntrypoint"
host="0.0.0.0" port="8191" doc:name="HTTP Listener Configuration" />
<http:request-config name="HTTP_Request_Configuration"
host="acdc3a38cffc411e5a18606a62b4ee07-877599714.us-west-1.elb.amazonaws.com"
port="80" doc:name="HTTP Request Configuration" />
<flow name="sbusdroolsFlow">
<http:listener config-ref="NorthboundSingleEntrypoint"
path="/*" doc:name="HTTP" />
<set-variable variableName="requestUrl"
value="#[message.inboundProperties.'http.request.path']" doc:name="RequestUrl" />
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
return requestUrl;
]]>
</script:script>
</script:component>
<bpm:rules rulesDefinition="routingRules.drl"
initialFacts-ref="reqUrl" />
<expression-transformer evaluator="groovy"
expression="message.getPayload().getObject()" doc:name="Expression" />
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
</flow>
Below is my drools .drl
#default dialect for the semantic code will be MVEL
global org.mule.module.bpm.MessageService mule;
import com.mule.sbus.drools.RequestUrl
dialect "mvel"
declare RequestUrl
#role(event)
end
rule "test123"
lock-on-active
when
$url:RequestUrl(url=="test123")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test123")}
end
rule "test234"
lock-on-active
when
$url:RequestUrl(url=="test234")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test234")}
end
and my java class
package com.mule.sbus.drools;
public class RequestUrl {
private String url;
private String endPoint;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
/*if(endPoint=="test123")
this.endPoint = endPoint;
else*/
this.endPoint = "/checkcibil";
System.out.println("inside java :::: " + endPoint);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "url : " + url + " endPoint : " + endPoint;
}
}
As you can see I am invoking my setter from the drools file and once I get the string I want to print the same using
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
but I don't know what should be the message value to use. Please assist
Got the answer,
As I am using groovy, have commented drools, and the updated the code as below
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
reqUrl.setEndPoint(requestUrl);
String endpnt = reqUrl.getEndPoint();
message.setProperty('endpnt', endpnt,org.mule.api.transport.PropertyScope.INVOCATION);
]]>
</script:script>
</script:component>
<logger message="#[flowVars['endpnt']]" level="INFO" doc:name="LoggerResp" />
Using groovy I am invoking the setter and the call the getter to have the value in endpt variable. This can now be set as a property in the message and later we can retrieve the same (outside groovy script tags), using #[flowVars['endpnt']]
I have a base class that I'm trying to use in a View. I understand now that #model is really an implementation of 'WebViewPage'. So, I believe there is probably a better way to accomplish what I want, maybe with an Action Filter or my BaseController object.
I was trying to do something like this:
public abstract class AuthenticatedViewPageBase : WebViewPage
{
private Login _user;
protected override void InitializePage()
{
_user = Session["User"] as Login;
}
public bool HasPermission(Permissions permission)
{
return HasPermission(new List<Permissions> { permission });
}
public bool HasPermission(List<Permissions> permissions)
{
if (_user == null)
_user = Session["User"] as Login;
return _user != null && permissions.Any(thisPerm => _user.Permissions.Any(p => p.PermissionId == (int)thisPerm));
}
}
And use it in a List View like this:
#using PublicationSystem.Model.Enums
#inherits PublicationSystem.Helpers.AuthenticatedViewPageBase
#model IEnumerable<PublicationSystem.Model.Profile>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutSmBanner.cshtml";
}
#if (HasPermission(new List<Permissions>
{
Permissions.userCreate
}))
{
<p>
#Html.ActionLink("Create New", "Create");
</p>
}
....
But of course, I cannot use #inherits and #model together. (The Profile class is a simple model.)
What would be a good way to get abilities of function like HasPermission in MVC?
I defined two similar classes:
public abstract class AuthenticatedViewPageBase : WebViewPage
{
//....
}
public abstract class AuthenticatedViewPageBase<TModel> : WebViewPage<TModel>
{
//....
}
Then set \Views\web.config like this:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="PublicationSystem.Helpers.AuthenticatedViewPageBase">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Optimization" />
<add namespace="PublicationSystem" />
</namespaces>
</pages>
</system.web.webPages.razor>
Now my pages can use #model as normally and get the custom methods from my abstract version of WebViewPage.
#model IEnumerable<PublicationSystem.Model.Profile>
I am getting an exception Dispatcher has no subscribers on the outboundChannel and can't figure out why. I am sure its something simple, I have stripped back my code to a very simple sample below:
My context is:
<bean id="requestService"
class="com.sandpit.RequestService" />
<integration:channel id="inboundChannel" />
<integration:service-activator id="service"
input-channel="inboundChannel"
output-channel="outboundChannel"
ref="requestService"
method="handleRequest" />
<integration:channel id="outboundChannel" />
<integration:gateway id="gateway"
service-interface="com.sandpit.Gateway"
default-request-channel="inboundChannel"
default-reply-channel="outboundChannel" />
<bean class="com.sandpit.GatewayTester">
<property name="gateway"
ref="gateway" />
</bean>
My Java code is:
public interface Gateway {
String receive();
void send(String message);
}
public class RequestService {
public String handleRequest(String request) {
return "Request received: " + request;
}
}
public class GatewayTester implements ApplicationListener<ContextRefreshedEvent> {
private Gateway gateway;
public void setGateway(Gateway gateway) {
this.gateway = gateway;
}
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
gateway.send("Hello world!");
System.out.println("FROM SERVICE: " + gateway.receive());
}
}
Note: A breakpoint does tell me that the RequestService is actually handling the request.
receive() with no args needs the reply channel to be a PollableChannel See the documentation.
add <queue/> to the outboundChannel.
Alternatively, You could change your gateway method to be String sendAndReceive(String in) and all will work as expected (and you can even remove the outboundChannel altogether).
I am a newbie at WCF. I created a WCF restful service in VS2010 (WCF service appl). It was targeted for Framework 4.0. I hosted this service on local IIS with appl pool set for framework 4.0. When I call the appl methods from browser or fiddler, they work fine. Now, I created a client console based. When I call any method from client I get the following Communication Exception:
** remote server returned an unexpected response: (405) Method Not Allowed.**
Service Interface file:
namespace MyService
{
[ServiceContract]
public interface ITestService
{
[WebGet(UriTemplate = "GetDateTime")]
[OperationContract]
string GetDateTime();
[WebGet(UriTemplate = "GetName")]
[OperationContract]
string GetName();
}
}
Class that implements the above interface:
namespace MyService
{
public class TestService : ITestService
{
public string GetDateTime()
{
return DateTime.Now.ToString();
}
public string GetName()
{
return "MY name is KingKong";
}
}
}
Web.config file:
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="MyService.TestService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
TestService.svc
<%# ServiceHost Language="C#" Debug="true" Service="MyService.TestService" CodeBehind="TestService.svc.cs" %>
Client app.config:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost/BestService/TestService.svc"
binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService"
name="MyClientConfig" kind="" endpointConfiguration="" />
</client>
</system.serviceModel>
Client program calling proxy class
static void Main(string[] args)
{
TestServiceClient proxy = null;
try
{
proxy = new TestServiceClient();
Console.WriteLine("Test 1: List all products");
string sdatetime = proxy.GetName();
Console.WriteLine("Datetime: {0}", sdatetime);
Console.WriteLine();
// Disconnect from the service
proxy.Close();
}
catch (CommunicationException cex)
{
if (cex.InnerException != null)
{
Console.WriteLine("{0}", cex.InnerException.Message);
}
else
{
Console.WriteLine("General exception: {0}", cex.Message);
}
}
catch (Exception e)
{
if (e.InnerException != null)
{
Console.WriteLine("{0}", e.InnerException.Message);
}
else
{
Console.WriteLine("General exception: {0}", e.Message);
}
}
Console.WriteLine("Press ENTER to finish");
Console.ReadLine();
}
I added a service reference to the application and the Reference.cs file has following partial code:
namespace MyClient.MyService {
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="MyService.ITestService")]
public interface ITestService {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetDateTime", ReplyAction="http://tempuri.org/ITestService/GetDateTimeResponse")]
string GetDateTime();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetName", ReplyAction="http://tempuri.org/ITestService/GetNameResponse")]
string GetName();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface ITestServiceChannel : MyClient.MyService.ITestService, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class TestServiceClient : System.ServiceModel.ClientBase<MyClient.MyService.ITestService>, MyClient.MyService.ITestService {
public TestServiceClient() {
}
public TestServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public TestServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public TestServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public TestServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public string GetDateTime() {
return base.Channel.GetDateTime();
}
public string GetName() {
return base.Channel.GetName();
}
}
}
Please help me as I have spent nearly 2 days trying to figure out the problem in the client
Thanks
VS2010 doesnt have the ability to generate a proxy for a RESTFUL service as it does for a SOAP based service. So the solution is write your own proxy class which inherits from the ClientBase class and use the Channel to call the web methods of the service.