I'm using a NativeActivity with a child activity called Body and a ActivityAction called OnFault, this is my code:
[Designer(typeof(RetryDesigner))]
public sealed class Retry : NativeActivity {
public Activity Body { get; set; }
public ActivityAction<Exception> OnFault { get; set; }
protected override void CacheMetadata(NativeActivityMetadata metadata) {
metadata.AddChild(Body);
metadata.AddDelegate(OnFault);
base.CacheMetadata(metadata);
}
protected override void Execute(NativeActivityContext context) {
context.ScheduleActivity(Body, OnBodyCompleted, OnBodyFaulted);
}
void OnFaultCompleted(NativeActivityContext context, ActivityInstance instance) {
context.ScheduleActivity(Body);
}
void OnBodyCompleted(NativeActivityContext context, ActivityInstance instance) {
}
void OnBodyFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom) {
faultContext.HandleFault();
if (OnFault != null) {
faultContext.ScheduleAction<Exception>(OnFault, propagatedException, OnFaultCompleted);
}
}
}
and my main looks like this:
static void Main(string[] args) {
Variable<Exception> ex = new Variable<Exception>();
DelegateInArgument<Exception> exception = new DelegateInArgument<Exception>();
Retry retry = new Retry {
Body = new Sequence {
Variables = { ex },
Activities = {
new Assign<Exception> {
To = new OutArgument<Exception>(ex),
Value = new InArgument<Exception>((env) => new Exception("test"))
},
new Throw {
Exception = ex
}
}
},
OnFault = new ActivityAction<Exception> {
Argument = exception,
Handler = new Sequence {
Activities = {
new WriteLine{
Text = new InArgument<string>(env =>
exception.Get(env).Message)
}
}
}
}
};
var workflow = new WorkflowInvoker(retry);
workflow.Invoke();
Console.WriteLine();
}
The problem is that the exception don't stop in the OnBodyFaulted callback and appear on the main as an unhedled expetion.
How can I stop the Exception inside the OnBodyFault callback, is there any state or property on the workflow to do that?
The problem is that in the OnFaultCompleted() you are calling context.ScheduleActivity(Body) again. This time without a fault handler so that causes the same fault to occur again and the complete workflow to fault.
Related
I'm trying to make async call with WSDL that belongs to SIRI (SIRI
Service Interface for Real Time Information), How can I "catch" the response if I call "GetStopMonitoringServiceAsync" ?
Relevant part from the WSDL:
public void GetStopMonitoringServiceAsync(ServiceRequestStructure Request) {
this.GetStopMonitoringServiceAsync(Request, null);
}
/// <remarks/>
public void GetStopMonitoringServiceAsync(ServiceRequestStructure Request, object userState) {
if ((this.GetStopMonitoringServiceOperationCompleted == null)) {
this.GetStopMonitoringServiceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetStopMonitoringServiceOperationCompleted);
}
this.InvokeAsync("GetStopMonitoringService", new object[] {
Request}, this.GetStopMonitoringServiceOperationCompleted, userState);
}
private void OnGetStopMonitoringServiceOperationCompleted(object arg) {
if ((this.GetStopMonitoringServiceCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetStopMonitoringServiceCompleted(this, new GetStopMonitoringServiceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
Managed..
SS.GetStopMonitoringServiceCompleted += new GetStopMonitoringServiceCompletedEventHandler(GetStopMonitoringServiceCompletedEventHandler);
static void GetStopMonitoringServiceCompletedEventHandler(object sender, GetStopMonitoringServiceCompletedEventArgs e)
{
ServiceDeliveryStructure Response = new ServiceDeliveryStructure();
Response = e.Result;
}
The function onCurrentProfileChanged doesnt get called everytime I logout and login, but if I remove the profiletracker, the profile comes as null for the first time login.How do i resolve the issue?. I have pasted the code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferenceManager.setApplicationContext(getApplicationContext());
onregister();
SharedPreferenceManager.setPreference("notificationcount", 0);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Profile.setCurrentProfile(currentProfile);
profileTracker.stopTracking();
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject jsonObject,
GraphResponse response) {
try {
dismissProgressDialog();
final Profile profile = Profile.getCurrentProfile();
SharedPreferenceManager.setPreference("id", profile.getId());
email = jsonObject.getString("email");
gender = jsonObject.getString("gender");
if (mAuthTask == null) {
mAuthTask = new UserLoginTask(email, "", profile.getName(), "facebook", profile.getId(), AccessToken.getCurrentAccessToken().getToken(), gender, getRegistrationId(getApplicationContext()));
//Log.v("token", loginResult.getAccessToken().getToken());
mAuthTask.execute((Void) null);
}
} catch (JSONException exe) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
};
profileTracker.startTracking();
}
#Override
public void onCancel() {
dismissProgressDialog();
LoginManager.getInstance().logOut();
}
#Override
public void onError(FacebookException exception) {
dismissProgressDialog();
LoginManager.getInstance().logOut();
}
});
Have you added this line in your code
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile,email"));
before call registerCallback?
I Am Trying to load a dynamic URL for Mediaplayer. How to handle various kinds of exceptions like file not found & timeout Exceptions that arise during execution.
public class MediaAsynchTask extends AsyncTask<String, Void, Object> {
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(AudioView.this);
progress.setMessage("LOADING........");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
progress.show();
}
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if(result!=null){
progress.dismiss();
}else{
Audio.this.finish();
}
}
Protected Object doInBackground(String... params) {
try {
if (!true)
{
MediaPlayer m = MediaPlayer.create(Audio.this,Uri.parse("audiourl.mp3"));
myProgressBar.setMax(mMediaPlayer.getDuration());
}return mMediaPlayer;
}catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Check Your NetWork and Data Connection",Toast.LENGTH_LONG).show();
}
});
}
return mMediaPlayer;
}
}
its very simple you can do it like this:
try{
**//your code goes here**
}catch(FileNotFoundException exception){
//handle exception
}//**handle other possible exceptions**
catch(JsonParseException exception){
exception.printStackTrace();
}catch(JsonProcessingException exception){
exception.printStackTrace();
}
I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.
I've wrote some unit-tests for my project who tests my presenters, these presenters queries an EF context with SingleOrDefault, all the unit-tests are successful. But when I run my ASP.NET application I get continuously the error "'Single' not supported by Linq to Entities?" I want to know why this behavior is kicking in? I can't find any documentation about this behavior.
I use the following code:
Presenter:
public class ManagedQueryPresenter : BasePresenterMetModel<IManagedQueriesView, ManagedQueryBeheerModel>, IWebPartPresenter
{
public ManagedQueryPresenter(IManagedQueriesView view) : base(view, new ManagedQueryBeheerModel()) { }
#region IPagePresenter Members
public void OnViewInitialize()
{
}
public void OnViewInitialized()
{
}
public void OnViewLoaded()
{
}
#endregion
public void OnManagedQueriesSelecting()
{
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryInserted(ManagedQuery entity)
{
Model.AddManagedQuery(entity);
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryUpdated(ManagedQuery entity)
{
Model.UpdateManagedQuery(entity);
}
public void OnManagedQueryDeleted(ManagedQuery entity)
{
Model.DeleteManagedQuery(entity);
}
}
Model:
public class ManagedQueryBeheerModel : BaseModel, IModel
{
public void AddManagedQuery(ManagedQuery entity)
{
...
}
public void DeleteManagedQuery(ManagedQuery entity)
{
...
}
public void UpdateManagedQuery(ManagedQuery entity)
{
DoEntityAction<bool>(context =>
{
ManagedQuery toUpdate = context.ManagedQueries.Include(q => q.ManagedQueryParameters).SingleOrDefault(x => x.ID == entity.ID);
...
context.SaveChanges();
return true;
});
}
public IList<ManagedQuery> GetAll()
{
return DoRepositoryAction<ManagedQuery, List<ManagedQuery>>(repository => (List<ManagedQuery>)repository.GetAll());
}
public ManagedQuery Get(long ID)
{
return DoRepositoryAction<ManagedQuery, ManagedQuery>(repository => repository.GetSingleOrDefault(x => x.ID == ID));
}
}
UnitTest:
[TestMethod()]
public void OnManagedQueryUpdatedTest()
{
IManagedQueriesView view = new MockedManagedQueriesView();
ManagedQueryPresenter target = new ManagedQueryPresenter(view);
ManagedQuery entity = ManagedQueryHelper.CreateNewRecord(target.Model);
entity.Name += "Updated";
target.OnManagedQueryUpdated(entity);
}
public static class ManagedQueryHelper
{
public static ManagedQuery CreateNewRecord(ManagedQueryBeheerModel model)
{
ManagedQuery entity = new ManagedQuery
{
Description = "Test Query",
Name = "Test",
QueryText = #"SOME QUERY",
HasOutput = true,
Category = "Test",
};
model.AddManagedQuery(entity);
return entity;
}
}
ASP.NET View (Codebehind of ascx):
public partial class ManagedQueriesUserControl : WebPartMangedUserControlWithPresenter<ManagedQueryPresenter>, IManagedQueriesView
{
protected ASPxGridView _grid;
protected ObjectContainerDataSource _ocdsManagedQueries;
#region IServicesView Members
public IList<Entities.ManagedQuery> ManagedQueries
{
set
{
_grid.ForceDataRowType(typeof(ManagedQuery));
_ocdsManagedQueries.DataSource = value;
}
}
#endregion
protected void _ocdsManagedQueries_Deleted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryDeleted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Updated(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryUpdated((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Inserted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryInserted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Selecting(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceSelectingEventArgs e)
{
Presenter.OnManagedQueriesSelecting();
}
#region IWebPartView Members
public bool IsValid()
{
return Page.IsValid;
}
public string ErrorText
{
set { }
}
#endregion
}
I believe you can find the answer on this thread Error, method not supported by LINQ to Entities
I was forgotten that unittests are by default in VS2010 written in .NET 4 and my code in .NET3.5 so therefore it isn't working. In EF4 Single(OrDefault) is supported!