Optional Resources in Spring.Net - ioc-container

How to include Spring configuration files optionally? I think about something simular to this:
<spring>
<context>
<resource uri="file:///Objects/RequiredObjects.xml" />
<resource uri="file:///Objects/OptionalObjects.xml" required="false" />
</context>
This way I could provide developers the possibility to override some configuration parts (e.g. for a local speed improvement or automatism during app startup) without affecting the app.config and the problem that a developer could checkin his modified file when it is not really his intent to change the config for all.

Not as simple as in AutoFac (because there is already a builtin way) but possible to achieve something similar with a little coding:
using System.IO;
using System.Xml;
using Spring.Core.IO;
public class OptionalFileSystemResource : FileSystemResource
{
public OptionalFileSystemResource(string uri)
: base(uri)
{
}
public override Stream InputStream
{
get
{
if (System.IO.File.Exists(this.Uri.LocalPath))
{
return base.InputStream;
}
return CreateEmptyStream();
}
}
private static Stream CreateEmptyStream()
{
var xml = new XmlDocument();
xml.LoadXml("<objects />");
var stream = new MemoryStream();
xml.Save(stream);
stream.Position = 0;
return stream;
}
}
Register a section handler:
<sectionGroup name="spring">
...
<section name="resourceHandlers" type="Spring.Context.Support.ResourceHandlersSectionHandler, Spring.Core"/>
...
</sectionGroup>
...
<spring>
<resourceHandlers>
<handler protocol="optionalfile" type="MyCoolStuff.OptionalFileSystemResource, MyCoolStuff" />
</resourceHandlers>
...
<context>
<resource uri="file://Config/MyMandatoryFile.xml" />
<resource uri="optionalfile://Config/MyOptionalFile.xml" />
...
You'll find more information about resources and resource handlers in the Spring.Net documentation.

Related

Arquillian - How to debug managed Wildfly container

I am using Arquillian to write black box tests for my RESTful application. I am actually capable of debug the test classes, but unable to debug my application classes. I would like to know exactly how to do that.
My arquillian.xml:
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="jbossas-managed" default="true">
<configuration>
<property name="jbossHome">D:\desenv\arquivos\servidores\wildfly-9.0.1.Final-test</property>
<property name="allowConnectingToRunningServer">true</property>
<property name="javaVmArguments">-Dorg.apache.deltaspike.ProjectStage=IntegrationTest</property>
</configuration>
</container>
One of my test classes:
#RunAsClient
#RunWith(Arquillian.class)
public class AuthenticationBlackBoxTest extends AbstractBlackBoxTest {
#Test
public void testInvalidCredentials(#ArquillianResource URL baseURI) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseURI.toString()).path("api/v1/auth");
Response response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(new Credentials("invalid", "invalid"), MediaType.APPLICATION_JSON));
Assert.assertEquals(401, response.getStatus());
response.close();
client.close();
}
#Test
public void testValidCredentials(#ArquillianResource URL baseURI) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseURI.toString()).path("api/v1/auth");
Entity<Credentials> credentialsEntity = Entity.entity(new Credentials("adm#adm.com", "123"), MediaType.APPLICATION_JSON);
Response response = target.request(MediaType.APPLICATION_JSON)
.post(credentialsEntity);
Assert.assertEquals(200, response.getStatus());
response.close();
client.close();
}
}
Inside arquillian.xml for javaVmArguments element add -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y.
Then in your favourite IDE you have to define a new Remote Debug configuration where you specify the host(localhost), port(8787). Place your break point, then run your test and finally start the remote debug. Official doc here.

Entlib Custom exception handler missing mappings

I implemented custom exception handler which works, except mappings from xml configuration policy. Those mapping works with standard Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler
My implementation
[ConfigurationElementType(typeof(CustomHandlerData))]
public class IdentityFaultContractExceptionHandler : IExceptionHandler
{
public IdentityFaultContractExceptionHandler(NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(Type faultContractType, string exceptionMessage, NameValueCollection attributes)
{
}
public IdentityFaultContractExceptionHandler(IStringResolver exceptionMessageResolver, Type faultContractType, NameValueCollection attributes)
{
}
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
return new Exception();
}
and part of the configuration
<add name="All Exceptions" type="System.Exception, mscorlib" postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add type="MyClass.IdentityFaultContractExceptionHandler, MyClass" exceptionMessage="An error occurred in the service." faultContractType="MyClass.UnexpectedServerFault, MyClass" name="Fault Contract Exception Handler" >
<mappings>
<add source="{Message}" name="Message" />
</mappings>
</add>
</exceptionHandlers>
</add>
When I remove mappping node service works, when I add, then I got error : unrecognize element mappings.
If you are using a CustomHandlerData attribute then your configuration needs to use XML Attributes which then get passed in as a NameValueCollection to the custom handler constructor. If you want to have custom XML then you will have to use Full Design-time Integration. If you want to go down that road then you should look at the FaultContractExceptionHandlerData source code since your code would probably be quite similar.

Recieving Sms using a broadcast receiver-xamarin

My last question was not a great question.
so here my new one.
I want to write an app that has and activity which get some info(like a phone number) from the user and then It is destroyed and the app icon is also hidden from the user.but i want to continuously receive sms from that phone number and do some stuff.
until now i have learned that if i register my broadcast receiver in the manifest it can still receive even though my app is not running or hidden.
so here is my app which i'm using xamarin (mono android):
my simple activity (it is not complete yet):
my main XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
p1:orientation="vertical"
p1:minWidth="25px"
p1:minHeight="25px"
p1:layout_width="match_parent"
p1:layout_height="match_parent"
p1:id="#+id/linearLayout1">
<EditText
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/txt_phone" />
<Button
p1:text="OK"
p1:layout_width="match_parent"
p1:layout_height="wrap_content"
p1:id="#+id/btn_ok" />
</LinearLayout>
and the activity class:
namespace SmsBroadcastReceiver
{
[Activity (Label = "SmsBroadcastReceiver", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
EditText txt_number = FindViewById<EditText> (Resource.Id.txt_phone);
Button btn_ok = FindViewById<Button> (Resource.Id.btn_ok);
btn_ok.Click += delegate {
//save the number in the sharedpreference and then...
Toast.MakeText (Context, "Your App Will be Closed now", ToastLength.Short).Show ();
};
}
}
}
now my broadcast receiver:
namespace SmsBroadcastReceiver
{
[BroadcastReceiver]
public class SmsReceiver : BroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{
Toast.MakeText (context, "sms rec", ToastLength.Long).Show ();
//get the sharedpreference and then do stuff
}
}
}
and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="SmsBroadcastReceiver.SmsBroadcastReceiver">
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="18" />
<application android:label="SmsBroadcastReceiver">
</application>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>
I know that the using a toast in a BR is not ideal but i just want to see that it is working which is not,everytime i send and sms to my phone it doesn't show anything.
where is my problem?
I think, you created BroadcastReceiver in the wrong way.
You should create it entirely with xamarin attributes.
Mono for Android translates each IntentFilterAttribute into an <intent-filter/> element.
[BroadcastReceiver]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SmsReceiver : BroadcastReceiver
{
...
}
therefore there is no need to write receiver tags manually in your AndroidManifest file.
You can also use attribute's named parameters for Priority, Categories, etc.
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = Int32.MaxValue)]

Red5 Live Streaming using Air to IOS client

Hi i have a Red5 Application Server running and a NetConnection using Air to IOS to connect to the Red5 Application Server.
But the problem is that i get an error like:
2014-07-01 04:43:04,475 [NioProcessor-6] ERROR o.r.server.service.ServiceInvoker - Method addSomething with parameters [2, 3] not found in org.red5.server.CoreHandler#ebf5a1
I understand that the Method is not being called for some reason but can understand why, can anyone help please?
CODE
SERVERSIDE
package com;
import java.util.HashMap;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.Red5;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.service.*;
import static java.lang.System.*;
import java.util.Stack;
public class Application extends ApplicationAdapter{
//private static final Log log = LogFactory.getLog( Application.class );
public boolean appStart(IScope scope){
out.println("Adding: ");
return true;
}
public void appStop(){
out.println("Adding: ");
// This function fires when the app is closing
}
public double addSomething(double a, double b){
// This is a method we will call from our flash client
out.println("Adding: "+a+" + "+b);
return a+b;
}
public boolean connect(IConnection conn, IScope scope, Object[] params) {
// This is the master connection method called every time someone connects
// to the server.
out.println("Adding: ");
//ServiceUtils.invokeOnAllConnections(scope, "joinuser", null);
return true;
}
/*
* (non-Javadoc)
* #see org.red5.server.adapter.ApplicationAdapter#disconnect(org.red5.server.api.IConnection, org.red5.server.api.IScope)
* disconnect an user form the chat and notify all others users
*/
public void disconnect(IConnection conn, IScope scope) {
// Function called every time someone disconnects from the server.
//ServiceUtils.invokeOnAllConnections(scope, "removeuser",null );
super.disconnect(conn, scope);
}
}
CLIENT
------
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.Responder;
var nc:NetConnection;
var good:Boolean;
var netOut:NetStream;
var netIn:NetStream;
var cam:Camera;
var mic:Microphone;
var responder:Responder;
var r:Responder;
var vidOut:Video;
var vidIn:Video;
var outStream:String;
var inStream:String;
trace("hello");
var rtmpNow:String="rtmp://localhost/Test1";
nc=new NetConnection;
nc.client = this;
nc.connect(rtmpNow,"trik");
nc.addEventListener(NetStatusEvent.NET_STATUS,getStream);
function getStream(e:NetStatusEvent):void
{
good=e.info.code == "NetConnection.Connect.Success";
if(good)
{
trace("hello");
// Here we call functions in our Java Application
//responder=new Responder(streamNow);
r = new Responder(adder);
nc.call("addSomething",r,2,3);
//nc.call("streamer",responder,"test");
}
}
function adder (obj:Object):void{
trace("Total = ",obj.toString());
}
function streamNow(streamSelect:Object):void
{
setCam();
setMic();
setVid();
trace("We've got our object",streamSelect.toString());
switch(streamSelect.toString())
{
case "left" :
outStream="left";
inStream="right";
break;
case "right" :
outStream="right";
inStream="left";
break;
}
//Publish local video
netOut=new NetStream(nc);
netOut.attachAudio(mic);
netOut.attachCamera(cam);
vidOut.attachCamera(cam);
netOut.publish(outStream, "live");
//Play streamed video
netIn=new NetStream(nc);
vidIn.attachNetStream(netIn);
netIn.play(inStream);
}
function setCam():void
{
cam=Camera.getCamera();
cam.setMode(240,180,15);
cam.setQuality(0,85);
}
function setMic():void
{
mic=Microphone.getMicrophone();
mic.rate=11;
mic.setSilenceLevel(12,2000);
}
function setVid():void
{
vidOut=new Video(240,180);
addChild(vidOut);
vidOut.x=25;
vidOut.y=110;
vidIn=new Video(240,180);
addChild(vidIn);
vidIn.x=vidOut.x+260;
vidIn.y=110;
}
RED5 PROPERTIES FILE
--------------------
webapp.contextPath=/Test1
webapp.virtualHosts=localhost, localhost:5080
RED5 WEB XML FILE
-----------------
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/red5-web.properties" />
</bean>
<bean id="web.context" class="org.red5.server.Context" autowire="byType" />
<bean id="web.handler" class="com.Application" />
<bean id="web.scope" class="org.red5.server.scope.WebScope" init-method="register">
<property name="server" ref="red5.server" />
<property name="parent" ref="global.scope" />
<property name="context" ref="web.context" />
<property name="handler" ref="global.handler" />
<property name="contextPath" value="${webapp.contextPath}" />
<property name="virtualHosts" value="${webapp.virtualHosts}" />
</bean>
</beans>
RED5 WEB XML FILE
-----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns
/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test1</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>/Test1</param-value>
</context-param>
<listener>
<listener-class>org.red5.logging.ContextLoggingListener</listener-class>
</listener>
<filter>
<filter-name>LoggerContextFilter</filter-name>
<filter-class>org.red5.logging.LoggerContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Forbidden</web-resource-name>
<url-pattern>/streams/*</url-pattern>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
</web-app>
The issues is that the "numbers" are not coming to the server as the expected type of "double". There are several solutions to this:
Change the parameter type on your addSomething method to int.
Send your parameters from the client with a decimal point (2.0 vs 2)

MVC 5 NHibernate Autofac, not able to see database data

I'm building an MVC5 web app connecting to a MS SQL 2008 database, so that the users can search and make changes to data stored there. I've looked at a bunch of autofac tutorials and examples, but can't seem to make any of them work.
I'm assuming my autofac configuration is the problem, because when I run the app it says my model is null. Which I think means the autofac is not connecting to the datbase.
So, in my global.asax.cs file I have the following:
protected void Application_Start()
{
#region Autofac
// Register Controllers
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly); //all controllers in assembly at once ?
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();
// Set the Dependency Resolver
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// Register Model Binders
builder.RegisterModelBinders(typeof(MvcApplication).Assembly); //all binders in assembly at once ?
builder.RegisterModelBinderProvider();
// Register Modules
builder.RegisterModule<PersistenceModule>();
#endregion
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I have a hibernate.cfg.xml file as
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=DEVSRV\SQLSERVER;Initial Catalog=tipdemo;Persist Security Info=True;User ID=admin;Password=***********</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<!--<mapping assembly="NHibernateTest"/> -->
</session-factory>
</hibernate-configuration>
</configuration>
And my PersistenceModule class is:
public class PersistenceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
if (builder == null)
throw new ArgumentException("builder", "builder is null");
base.Load(builder);
}
private ISessionFactory ConfigureDB()
{
Configuration cfg = new Configuration().Configure(System.Web.HttpContext.Current.Server.MapPath("~/Config/hibernate.cfg.xml"));
cfg.AddAssembly(typeof(Domain.General.Project).Assembly);
return cfg.BuildSessionFactory();
}
}
You can't register things in the container after it's built.
On line 11 in the sample for Application_Start you're building the container, but then after you set the DependencyResolver you're registering more stuff with the ContainerBuilder. You can't do that - you have to register everything first, then build the container as the last thing you do.
That's why it's never entering your PersistenceModule - you've already built the container, so it's not actually getting registered.
If, for some reason, you need to add registrations to an already-built container, you need to create an all new ContainerBuilder and call builder.Update(container). However, I strongly recommend you just reorder things so the container is built last rather than go the Update route if possible.